merge: stack widget modernization on dnd kit
This commit is contained in:
940 files changed
+104475
-33649
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { createRscTrpcContext } from "./rsc-context";
|
||||
import { boardRouter } from "./router/board";
|
||||
|
||||
const createBoardCallerAsync = async () => boardRouter.createCaller(await createRscTrpcContext());
|
||||
|
||||
export const getBoardByNameAsync = cache(async (name: string) => {
|
||||
const caller = await createBoardCallerAsync();
|
||||
return await caller.getBoardByName({ name });
|
||||
});
|
||||
|
||||
export const getHomeBoardAsync = cache(async () => {
|
||||
const caller = await createBoardCallerAsync();
|
||||
return await caller.getHomeBoard();
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from "./router/custom-widget/configuration-requests";
|
||||
export { configurePreviewSessionSource } from "./router/custom-widget/preview-sessions";
|
||||
export {
|
||||
parseStoredCustomWidgetDefinition,
|
||||
serializeCustomWidgetDefinition,
|
||||
} from "./router/custom-widget/stored-definition";
|
||||
export { configureCustomWidgetSourceFromRequest } from "./router/custom-widget/secret-persistence";
|
||||
@@ -1,16 +1,34 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createBooleanSchema, createEnv } from "@homarr/core/infrastructure/env";
|
||||
import { normalizeHttpUrl } from "@homarr/workshop/schema";
|
||||
|
||||
const publicHttpUrl = (variableName: string) =>
|
||||
z.string().transform((value, context) => {
|
||||
try {
|
||||
return normalizeHttpUrl(value, variableName);
|
||||
} catch (error) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: error instanceof Error ? error.message : `${variableName} is invalid`,
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
});
|
||||
|
||||
export const env = createEnv({
|
||||
server: {
|
||||
KUBERNETES_SERVICE_ACCOUNT_NAME: z.string().optional(),
|
||||
DEMO_MODE: createBooleanSchema(false),
|
||||
DEMO_READ_ONLY: createBooleanSchema(true),
|
||||
HOMARR_WEBSITE_URL: publicHttpUrl("HOMARR_WEBSITE_URL").default("https://homarr.dev"),
|
||||
WORKSHOP_API_URL: publicHttpUrl("WORKSHOP_API_URL").optional(),
|
||||
},
|
||||
runtimeEnv: {
|
||||
KUBERNETES_SERVICE_ACCOUNT_NAME: process.env.KUBERNETES_SERVICE_ACCOUNT_NAME,
|
||||
DEMO_MODE: process.env.DEMO_MODE,
|
||||
DEMO_READ_ONLY: process.env.DEMO_READ_ONLY,
|
||||
HOMARR_WEBSITE_URL: process.env.HOMARR_WEBSITE_URL,
|
||||
WORKSHOP_API_URL: process.env.WORKSHOP_API_URL,
|
||||
},
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { bazarrRouter } from "./router/widgets/bazarr";
|
||||
import { serverSettingsRouter } from "./router/serverSettings";
|
||||
import { beszelRouter } from "./router/widgets/beszel";
|
||||
import { calendarRouter } from "./router/widgets/calendar";
|
||||
import { customWidgetRouter } from "./router/custom-widget/custom-widget-router";
|
||||
import { dnsHoleRouter } from "./router/widgets/dns-hole";
|
||||
import { downloadsRouter } from "./router/widgets/downloads";
|
||||
import { healthMonitoringRouter } from "./router/widgets/health-monitoring";
|
||||
@@ -35,6 +36,7 @@ export const mcpRouter = createTRPCRouter({
|
||||
serverSettings: serverSettingsRouter,
|
||||
beszel: beszelRouter,
|
||||
calendar: calendarRouter,
|
||||
customWidget: customWidgetRouter,
|
||||
dnsHole: dnsHoleRouter,
|
||||
downloads: downloadsRouter,
|
||||
healthMonitoring: healthMonitoringRouter,
|
||||
|
||||
@@ -1,22 +1,54 @@
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
|
||||
export const queryCacheDefaultStaleTimeMs = 0;
|
||||
// RSC-prefetched data must survive the hydration pass without an immediate
|
||||
// duplicate fetch. Widget-specific intervals still control live refreshes.
|
||||
export const queryCacheDefaultStaleTimeMs = 30_000;
|
||||
export const queryCacheDefaultRefetchIntervalMs = 30_000;
|
||||
export const queryCacheDefaultGcTimeMs = 1000 * 60 * 60 * 24;
|
||||
export const queryCacheMaxValueBytes = 1024 * 1024;
|
||||
export const queryCacheStoragePrefix = "homarr-widget-query";
|
||||
export const queryCacheBuster = "v2-superjson";
|
||||
export const queryCacheDefaultGcTimeMs = 1000 * 60 * 5;
|
||||
export const queryCacheMetadataStaleTimeMs = 1000 * 60 * 5;
|
||||
|
||||
let activeQueryCacheBoardId: string | null = null;
|
||||
const widgetDataQueryPaths = new Set(["app.byId", "app.byIds", "docker.getContainers", "integration.byIds"]);
|
||||
const excludedWidgetPaths = new Set(["widget.app.ping", "widget.beszel.getSystemStats"]);
|
||||
|
||||
export const setActiveQueryCacheBoardId = (boardId: string | null) => {
|
||||
activeQueryCacheBoardId = boardId;
|
||||
export const isWidgetDataTrpcPath = (path: string) => {
|
||||
if (path.startsWith("widget.")) return !excludedWidgetPaths.has(path);
|
||||
return widgetDataQueryPaths.has(path);
|
||||
};
|
||||
|
||||
export const getActiveQueryCacheBoardId = () => activeQueryCacheBoardId;
|
||||
|
||||
const persistableQueryPaths = new Set(["app.byId", "app.byIds", "docker.getContainers", "integration.byIds"]);
|
||||
const excludedWidgetPaths = new Set(["widget.app.ping", "widget.beszel.getSystemStats"]);
|
||||
// These supporting queries can be numerous on a dashboard. Give them a
|
||||
// predictable refresh policy instead of refetching all of them after every tab
|
||||
// focus/reconnect event. Metadata can refresh after a bounded stale window;
|
||||
// Docker state remains live on a single shared timer.
|
||||
export const dashboardSupportingQueryPolicies = [
|
||||
{
|
||||
queryKey: [["app", "byId"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["app", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["integration", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["docker", "getContainers"]],
|
||||
refetchInterval: queryCacheDefaultRefetchIntervalMs,
|
||||
staleTime: queryCacheDefaultStaleTimeMs,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
},
|
||||
] as const;
|
||||
|
||||
const getTrpcPathFromQueryKey = (queryKey: QueryKey) => {
|
||||
const first = queryKey[0];
|
||||
@@ -26,11 +58,9 @@ const getTrpcPathFromQueryKey = (queryKey: QueryKey) => {
|
||||
return parts.length > 0 ? parts : null;
|
||||
};
|
||||
|
||||
export const isPersistableWidgetQueryKey = (queryKey: QueryKey) => {
|
||||
export const isWidgetDataQueryKey = (queryKey: QueryKey) => {
|
||||
const path = getTrpcPathFromQueryKey(queryKey);
|
||||
if (!path) return false;
|
||||
|
||||
if (path[0] === "widget") return !excludedWidgetPaths.has(path.join("."));
|
||||
|
||||
return persistableQueryPaths.has(path.join("."));
|
||||
return isWidgetDataTrpcPath(path.join("."));
|
||||
};
|
||||
@@ -24,7 +24,6 @@ export const appRouter = createTRPCRouter({
|
||||
cronJobs: lazy(() => import("./router/cron-jobs").then((mod) => mod.cronJobsRouter)),
|
||||
apiKeys: lazy(() => import("./router/apiKeys").then((mod) => mod.apiKeysRouter)),
|
||||
media: lazy(() => import("./router/medias/media-router").then((mod) => mod.mediaRouter)),
|
||||
queryCache: lazy(() => import("./router/query-cache").then((mod) => mod.queryCacheRouter)),
|
||||
updateChecker: lazy(() => import("./router/update-checker").then((mod) => mod.updateCheckerRouter)),
|
||||
certificates: lazy(() => import("./router/certificates/certificate-router").then((mod) => mod.certificateRouter)),
|
||||
bangs: lazy(() => import("./router/bangs/bangs-router").then((mod) => mod.bangsRouter)),
|
||||
|
||||
@@ -173,7 +173,7 @@ export const appRouter = createTRPCRouter({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Create a new app (bookmark/shortcut to a service). REQUIRED: name (string), iconUrl (icon URL string), href (app URL, http/https or blank). OPTIONAL: description (string or null), pingUrl (URL to check reachability, or empty string)",
|
||||
"Create a new app (bookmark/shortcut to a service). REQUIRED: name (string), iconUrl (icon URL string), href (app URL or custom URI scheme such as vscode://, or blank). OPTIONAL: description (string or null), pingUrl (URL to check reachability, or empty string)",
|
||||
},
|
||||
})
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
|
||||
+286
-144
@@ -29,12 +29,16 @@ import {
|
||||
sections,
|
||||
users,
|
||||
} from "@homarr/db/schema";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import type { BoardLane, WidgetKind } from "@homarr/definitions";
|
||||
import {
|
||||
boardLanes,
|
||||
emptySuperJSON,
|
||||
everyoneGroup,
|
||||
getBoardLaneColumnCount,
|
||||
getRootSectionLane,
|
||||
getPermissionsWithChildren,
|
||||
getPermissionsWithParents,
|
||||
rootSectionOffsets,
|
||||
widgetDefaultSizes,
|
||||
widgetKinds,
|
||||
} from "@homarr/definitions";
|
||||
@@ -61,6 +65,10 @@ import { sectionSchema, sharedItemSchema } from "@homarr/validation/shared";
|
||||
|
||||
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "./board/board-access";
|
||||
import {
|
||||
throwIfCustomWidgetBoardDuplicationForbidden,
|
||||
throwIfCustomWidgetPlacementChangeForbidden,
|
||||
} from "./board/custom-widget-placement-access";
|
||||
import { generateResponsiveGridFor } from "./board/grid-algorithm";
|
||||
import { validateTimetableOptionsChangeAsync } from "./widgets/timetable";
|
||||
|
||||
@@ -318,6 +326,8 @@ export const boardRouter = createTRPCRouter({
|
||||
id: createId(),
|
||||
name: "Base",
|
||||
columnCount: input.columnCount,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 0,
|
||||
boardId,
|
||||
});
|
||||
@@ -373,6 +383,7 @@ export const boardRouter = createTRPCRouter({
|
||||
}
|
||||
|
||||
const { sections: boardSections, items: boardItems, layouts: boardLayouts, ...boardProps } = board;
|
||||
throwIfCustomWidgetBoardDuplicationForbidden(ctx.session.user.permissions.includes("admin"), boardItems);
|
||||
|
||||
const newBoardId = createId();
|
||||
|
||||
@@ -686,6 +697,11 @@ export const boardRouter = createTRPCRouter({
|
||||
saveLayouts: protectedProcedure.input(boardSaveLayoutsSchema).mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
|
||||
|
||||
const requiredGutterRoots = (["left", "right"] as const).filter((lane) =>
|
||||
input.layouts.some((layout) => getBoardLaneColumnCount(layout, lane) > 0),
|
||||
);
|
||||
await ensureGutterRootSectionsAsync(ctx.db, input.id, requiredGutterRoots);
|
||||
|
||||
const board = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id);
|
||||
|
||||
const addedLayouts = filterAddedItems(input.layouts, board.layouts);
|
||||
@@ -697,14 +713,6 @@ export const boardRouter = createTRPCRouter({
|
||||
for (const addedLayout of addedLayouts) {
|
||||
const layoutId = createId();
|
||||
|
||||
layoutsToInsert.push({
|
||||
id: layoutId,
|
||||
name: addedLayout.name,
|
||||
columnCount: addedLayout.columnCount,
|
||||
breakpoint: addedLayout.breakpoint,
|
||||
boardId: board.id,
|
||||
});
|
||||
|
||||
const sortedLayouts = board.layouts.toSorted((layoutA, layoutB) => layoutA.columnCount - layoutB.columnCount);
|
||||
// Fallback to biggest if none exists with columnCount bigger than addedLayout.columnCount
|
||||
const layoutToClone =
|
||||
@@ -715,13 +723,27 @@ export const boardRouter = createTRPCRouter({
|
||||
previous: {
|
||||
layoutId: layoutToClone.id,
|
||||
columnCount: layoutToClone.columnCount,
|
||||
leftGutterColumnCount: layoutToClone.leftGutterColumnCount,
|
||||
rightGutterColumnCount: layoutToClone.rightGutterColumnCount,
|
||||
},
|
||||
current: {
|
||||
layoutId,
|
||||
columnCount: addedLayout.columnCount,
|
||||
leftGutterColumnCount: addedLayout.leftGutterColumnCount,
|
||||
rightGutterColumnCount: addedLayout.rightGutterColumnCount,
|
||||
},
|
||||
});
|
||||
|
||||
layoutsToInsert.push({
|
||||
id: layoutId,
|
||||
name: addedLayout.name,
|
||||
columnCount: addedLayout.columnCount,
|
||||
leftGutterColumnCount: addedLayout.leftGutterColumnCount,
|
||||
rightGutterColumnCount: addedLayout.rightGutterColumnCount,
|
||||
breakpoint: addedLayout.breakpoint,
|
||||
boardId: board.id,
|
||||
});
|
||||
|
||||
itemSectionLayoutsToInsert.push(...updatedBoardLayout.itemSectionLayouts);
|
||||
sectionLayoutsToInsert.push(...updatedBoardLayout.sectionLayouts);
|
||||
}
|
||||
@@ -742,16 +764,25 @@ export const boardRouter = createTRPCRouter({
|
||||
for (const updatedLayout of updatedLayouts) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const dbLayout = board.layouts.find((layout) => layout.id === updatedLayout.id)!;
|
||||
let updatedBoardLayout: ReturnType<typeof getUpdatedBoardLayout> | undefined;
|
||||
|
||||
if (dbLayout.columnCount !== updatedLayout.columnCount) {
|
||||
const updatedBoardLayout = getUpdatedBoardLayout(board, {
|
||||
if (
|
||||
dbLayout.columnCount !== updatedLayout.columnCount ||
|
||||
dbLayout.leftGutterColumnCount !== updatedLayout.leftGutterColumnCount ||
|
||||
dbLayout.rightGutterColumnCount !== updatedLayout.rightGutterColumnCount
|
||||
) {
|
||||
updatedBoardLayout = getUpdatedBoardLayout(board, {
|
||||
previous: {
|
||||
layoutId: dbLayout.id,
|
||||
columnCount: dbLayout.columnCount,
|
||||
leftGutterColumnCount: dbLayout.leftGutterColumnCount,
|
||||
rightGutterColumnCount: dbLayout.rightGutterColumnCount,
|
||||
},
|
||||
current: {
|
||||
layoutId: dbLayout.id,
|
||||
columnCount: updatedLayout.columnCount,
|
||||
leftGutterColumnCount: updatedLayout.leftGutterColumnCount,
|
||||
rightGutterColumnCount: updatedLayout.rightGutterColumnCount,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -797,6 +828,8 @@ export const boardRouter = createTRPCRouter({
|
||||
.set({
|
||||
name: updatedLayout.name,
|
||||
columnCount: updatedLayout.columnCount,
|
||||
leftGutterColumnCount: updatedLayout.leftGutterColumnCount,
|
||||
rightGutterColumnCount: updatedLayout.rightGutterColumnCount,
|
||||
breakpoint: updatedLayout.breakpoint,
|
||||
})
|
||||
.where(eq(layouts.id, updatedLayout.id));
|
||||
@@ -856,6 +889,11 @@ export const boardRouter = createTRPCRouter({
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
|
||||
|
||||
const dbBoard = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id);
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: ctx.session.user.permissions.includes("admin"),
|
||||
submittedItems: input.items,
|
||||
storedItems: dbBoard.items,
|
||||
});
|
||||
|
||||
for (const item of input.items) {
|
||||
if (item.kind !== "timetable") continue;
|
||||
@@ -876,32 +914,32 @@ export const boardRouter = createTRPCRouter({
|
||||
addedSections.map((section) => ({
|
||||
id: section.id,
|
||||
kind: section.kind,
|
||||
yOffset: section.kind !== "dynamic" ? section.yOffset : null,
|
||||
xOffset: section.kind === "dynamic" ? null : 0,
|
||||
options: section.kind === "dynamic" ? superjson.stringify(section.options) : emptySuperJSON,
|
||||
name: "name" in section ? section.name : null,
|
||||
yOffset: section.kind === "empty" ? section.yOffset : null,
|
||||
xOffset: section.kind === "empty" ? section.xOffset : null,
|
||||
options: section.kind === "empty" ? emptySuperJSON : superjson.stringify(section.options),
|
||||
name: null,
|
||||
boardId: dbBoard.id,
|
||||
})),
|
||||
);
|
||||
|
||||
if (addedSections.some((section) => section.kind === "dynamic")) {
|
||||
await transaction.insert(schema.sectionLayouts).values(
|
||||
addedSections
|
||||
.filter((section) => section.kind === "dynamic")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof schema.sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
),
|
||||
const sectionLayoutsToInsert = addedSections
|
||||
.filter((section) => section.kind === "container")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof schema.sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
await transaction.insert(schema.sectionLayouts).values(sectionLayoutsToInsert);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,18 +1036,17 @@ export const boardRouter = createTRPCRouter({
|
||||
const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections);
|
||||
|
||||
for (const section of updatedSections) {
|
||||
const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
|
||||
await transaction
|
||||
.update(schema.sections)
|
||||
.set({
|
||||
yOffset: prev?.kind !== "dynamic" && "yOffset" in section ? section.yOffset : null,
|
||||
xOffset: prev?.kind !== "dynamic" && "yOffset" in section ? 0 : null,
|
||||
options: section.kind === "dynamic" ? superjson.stringify(section.options) : emptySuperJSON,
|
||||
name: prev?.kind === "category" && "name" in section ? section.name : null,
|
||||
yOffset: section.kind === "empty" ? section.yOffset : null,
|
||||
xOffset: section.kind === "empty" ? section.xOffset : null,
|
||||
options: section.kind === "empty" ? emptySuperJSON : superjson.stringify(section.options),
|
||||
name: null,
|
||||
})
|
||||
.where(eq(schema.sections.id, section.id));
|
||||
|
||||
if (section.kind !== "dynamic") continue;
|
||||
if (section.kind !== "container") continue;
|
||||
|
||||
for (const sectionLayout of section.layouts) {
|
||||
await transaction
|
||||
@@ -1076,36 +1113,33 @@ export const boardRouter = createTRPCRouter({
|
||||
addedSections.map((section) => ({
|
||||
id: section.id,
|
||||
kind: section.kind,
|
||||
yOffset: section.kind !== "dynamic" ? section.yOffset : null,
|
||||
xOffset: section.kind === "dynamic" ? null : 0,
|
||||
options: section.kind === "dynamic" ? superjson.stringify(section.options) : emptySuperJSON,
|
||||
name: "name" in section ? section.name : null,
|
||||
yOffset: section.kind === "empty" ? section.yOffset : null,
|
||||
xOffset: section.kind === "empty" ? section.xOffset : null,
|
||||
options: section.kind === "empty" ? emptySuperJSON : superjson.stringify(section.options),
|
||||
name: null,
|
||||
boardId: dbBoard.id,
|
||||
})),
|
||||
)
|
||||
.run();
|
||||
|
||||
if (addedSections.some((section) => section.kind === "dynamic")) {
|
||||
transaction
|
||||
.insert(sectionLayouts)
|
||||
.values(
|
||||
addedSections
|
||||
.filter((section) => section.kind === "dynamic")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
const sectionLayoutsToInsert = addedSections
|
||||
.filter((section) => section.kind === "container")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
transaction.insert(sectionLayouts).values(sectionLayoutsToInsert).run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1208,19 +1242,18 @@ export const boardRouter = createTRPCRouter({
|
||||
const updatedSections = filterUpdatedItems(input.sections, dbBoard.sections);
|
||||
|
||||
for (const section of updatedSections) {
|
||||
const prev = dbBoard.sections.find((dbSection) => dbSection.id === section.id);
|
||||
transaction
|
||||
.update(sections)
|
||||
.set({
|
||||
yOffset: prev?.kind !== "dynamic" && "yOffset" in section ? section.yOffset : null,
|
||||
xOffset: prev?.kind !== "dynamic" && "yOffset" in section ? 0 : null,
|
||||
options: section.kind === "dynamic" ? superjson.stringify(section.options) : emptySuperJSON,
|
||||
name: prev?.kind === "category" && "name" in section ? section.name : null,
|
||||
yOffset: section.kind === "empty" ? section.yOffset : null,
|
||||
xOffset: section.kind === "empty" ? section.xOffset : null,
|
||||
options: section.kind === "empty" ? emptySuperJSON : superjson.stringify(section.options),
|
||||
name: null,
|
||||
})
|
||||
.where(eq(sections.id, section.id))
|
||||
.run();
|
||||
|
||||
if (section.kind !== "dynamic") continue;
|
||||
if (section.kind !== "container") continue;
|
||||
|
||||
for (const sectionLayout of section.layouts) {
|
||||
transaction
|
||||
@@ -1450,6 +1483,11 @@ export const boardRouter = createTRPCRouter({
|
||||
.output(z.object({ itemId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: ctx.session.user.permissions.includes("admin"),
|
||||
submittedItems: [{ id: "", kind: input.kind, options: input.options }],
|
||||
storedItems: [],
|
||||
});
|
||||
|
||||
if (input.kind === "timetable") {
|
||||
await validateTimetableOptionsChangeAsync(input.options);
|
||||
@@ -1656,77 +1694,98 @@ const noBoardWithSimilarNameAsync = async (db: Database, name: string, ignoredId
|
||||
const getUpdatedBoardLayout = (
|
||||
board: Awaited<ReturnType<typeof getFullBoardWithWhereAsync>>,
|
||||
options: {
|
||||
previous: {
|
||||
layoutId: string;
|
||||
columnCount: number;
|
||||
};
|
||||
current: {
|
||||
layoutId: string;
|
||||
columnCount: number;
|
||||
};
|
||||
previous: BoardLayoutGeometry;
|
||||
current: BoardLayoutGeometry;
|
||||
},
|
||||
) => {
|
||||
const itemSectionLayoutsCollection: InferInsertModel<typeof itemLayouts>[] = [];
|
||||
const sectionLayoutsCollection: InferInsertModel<typeof sectionLayouts>[] = [];
|
||||
|
||||
const elements = getElementsForLayout(board, options.previous.layoutId);
|
||||
const rootSections = board.sections.filter((section) => section.kind !== "dynamic");
|
||||
|
||||
for (const rootSection of rootSections) {
|
||||
const result = generateResponsiveGridFor({
|
||||
items: elements,
|
||||
previousWidth: options.previous.columnCount,
|
||||
width: options.current.columnCount,
|
||||
sectionId: rootSection.id,
|
||||
});
|
||||
|
||||
itemSectionLayoutsCollection.push(
|
||||
...board.items
|
||||
.map((item): InferInsertModel<typeof itemLayouts> | null => {
|
||||
const currentElement = result.items.find((element) => element.type === "item" && element.id === item.id);
|
||||
|
||||
if (!currentElement) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
itemId: item.id,
|
||||
layoutId: options.current.layoutId,
|
||||
sectionId: currentElement.sectionId,
|
||||
height: currentElement.height,
|
||||
width: currentElement.width,
|
||||
xOffset: currentElement.xOffset,
|
||||
yOffset: currentElement.yOffset,
|
||||
};
|
||||
})
|
||||
.filter((item) => item !== null),
|
||||
);
|
||||
|
||||
sectionLayoutsCollection.push(
|
||||
...board.sections
|
||||
.filter((section) => section.kind === "dynamic")
|
||||
.map((section): InferInsertModel<typeof sectionLayouts> | null => {
|
||||
const currentElement = result.items.find(
|
||||
(element) => element.type === "section" && element.id === section.id,
|
||||
);
|
||||
|
||||
if (!currentElement) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
layoutId: options.current.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: currentElement.sectionId,
|
||||
height: currentElement.height,
|
||||
width: currentElement.width,
|
||||
xOffset: currentElement.xOffset,
|
||||
yOffset: currentElement.yOffset,
|
||||
};
|
||||
})
|
||||
.filter((section) => section !== null),
|
||||
);
|
||||
const emptyRoots = board.sections
|
||||
.filter((section) => section.kind === "empty")
|
||||
.toSorted((first, second) => (first.yOffset ?? 0) - (second.yOffset ?? 0) || first.id.localeCompare(second.id));
|
||||
const rootByLane = new Map<BoardLane, (typeof emptyRoots)[number]>();
|
||||
for (const root of emptyRoots) {
|
||||
const lane = getRootSectionLane(root.xOffset);
|
||||
if (!rootByLane.has(lane)) rootByLane.set(lane, root);
|
||||
}
|
||||
const mainRoot = rootByLane.get("main");
|
||||
if (!mainRoot) throw new Error(`Board "${board.id}" has no main canvas root`);
|
||||
|
||||
const sourceRootById = new Map(
|
||||
emptyRoots.map((section) => [section.id, getRootSectionLane(section.xOffset)] as const),
|
||||
);
|
||||
const targetLaneBySourceLane = new Map<BoardLane, BoardLane>(
|
||||
boardLanes.map((lane) => [
|
||||
lane,
|
||||
lane !== "main" && getBoardLaneColumnCount(options.current, lane) === 0 ? "main" : lane,
|
||||
]),
|
||||
);
|
||||
const remappedElements = elements.map((element) => {
|
||||
const sourceLane = sourceRootById.get(element.sectionId);
|
||||
if (!sourceLane) return element;
|
||||
const targetLane = targetLaneBySourceLane.get(sourceLane) ?? "main";
|
||||
const targetRoot = rootByLane.get(targetLane) ?? mainRoot;
|
||||
return {
|
||||
...element,
|
||||
sectionId: targetRoot.id,
|
||||
};
|
||||
});
|
||||
|
||||
const results = boardLanes.flatMap((lane) => {
|
||||
const root = rootByLane.get(lane);
|
||||
const width = getBoardLaneColumnCount(options.current, lane);
|
||||
if (!root || width === 0) return [];
|
||||
const sourceLanes = boardLanes.filter((sourceLane) => targetLaneBySourceLane.get(sourceLane) === lane);
|
||||
const previousWidth =
|
||||
sourceLanes.length === 1
|
||||
? getBoardLaneColumnCount(options.previous, sourceLanes[0] ?? "main")
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
|
||||
return [
|
||||
generateResponsiveGridFor({
|
||||
items: remappedElements,
|
||||
previousWidth,
|
||||
width,
|
||||
sectionId: root.id,
|
||||
}),
|
||||
];
|
||||
});
|
||||
const updatedElements = results.flatMap((result) => result.items);
|
||||
const updatedElementById = new Map(updatedElements.map((element) => [element.id, element]));
|
||||
|
||||
const itemSectionLayoutsCollection = board.items.flatMap((item): InferInsertModel<typeof itemLayouts>[] => {
|
||||
const currentElement = updatedElementById.get(item.id);
|
||||
if (!currentElement || currentElement.type !== "item") return [];
|
||||
|
||||
return [
|
||||
{
|
||||
itemId: item.id,
|
||||
layoutId: options.current.layoutId,
|
||||
sectionId: currentElement.sectionId,
|
||||
height: currentElement.height,
|
||||
width: currentElement.width,
|
||||
xOffset: currentElement.xOffset,
|
||||
yOffset: currentElement.yOffset,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const sectionLayoutsCollection = board.sections.flatMap((section): InferInsertModel<typeof sectionLayouts>[] => {
|
||||
if (section.kind !== "container") return [];
|
||||
const currentElement = updatedElementById.get(section.id);
|
||||
if (!currentElement || currentElement.type !== "section") return [];
|
||||
|
||||
return [
|
||||
{
|
||||
layoutId: options.current.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: currentElement.sectionId,
|
||||
height: currentElement.height,
|
||||
width: currentElement.width,
|
||||
xOffset: currentElement.xOffset,
|
||||
yOffset: currentElement.yOffset,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
return {
|
||||
itemSectionLayouts: itemSectionLayoutsCollection,
|
||||
@@ -1734,9 +1793,89 @@ const getUpdatedBoardLayout = (
|
||||
};
|
||||
};
|
||||
|
||||
interface BoardLayoutGeometry {
|
||||
layoutId: string;
|
||||
columnCount: number;
|
||||
leftGutterColumnCount: number;
|
||||
rightGutterColumnCount: number;
|
||||
}
|
||||
|
||||
type GutterLane = Exclude<BoardLane, "main">;
|
||||
|
||||
const ensureGutterRootSectionsAsync = async (db: Database, boardId: string, lanes: readonly GutterLane[]) => {
|
||||
if (lanes.length === 0) return;
|
||||
|
||||
const getMissingLanes = (existingOffsets: readonly (number | null)[]) =>
|
||||
lanes.filter((lane) => {
|
||||
const rootCount = existingOffsets.filter((offset) => offset === rootSectionOffsets[lane]).length;
|
||||
if (rootCount > 1) throw new Error(`Board "${boardId}" has multiple ${lane} canvas roots`);
|
||||
return rootCount === 0;
|
||||
});
|
||||
const getRows = (missingLanes: readonly GutterLane[]) =>
|
||||
missingLanes.map((lane) => ({
|
||||
id: createId(),
|
||||
boardId,
|
||||
kind: "empty" as const,
|
||||
xOffset: rootSectionOffsets[lane],
|
||||
yOffset: 0,
|
||||
options: emptySuperJSON,
|
||||
}));
|
||||
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.select({ id: schema.boards.id })
|
||||
.from(schema.boards)
|
||||
.where(eq(schema.boards.id, boardId))
|
||||
.for("update");
|
||||
|
||||
const existingRoots = await transaction
|
||||
.select({ xOffset: schema.sections.xOffset })
|
||||
.from(schema.sections)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.sections.boardId, boardId),
|
||||
eq(schema.sections.kind, "empty"),
|
||||
inArray(
|
||||
schema.sections.xOffset,
|
||||
lanes.map((lane) => rootSectionOffsets[lane]),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rows = getRows(getMissingLanes(existingRoots.map(({ xOffset }) => xOffset)));
|
||||
if (rows.length > 0) await transaction.insert(schema.sections).values(rows);
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction(
|
||||
(transaction) => {
|
||||
const existingRoots = transaction
|
||||
.select({ xOffset: sections.xOffset })
|
||||
.from(sections)
|
||||
.where(
|
||||
and(
|
||||
eq(sections.boardId, boardId),
|
||||
eq(sections.kind, "empty"),
|
||||
inArray(
|
||||
sections.xOffset,
|
||||
lanes.map((lane) => rootSectionOffsets[lane]),
|
||||
),
|
||||
),
|
||||
)
|
||||
.all();
|
||||
const rows = getRows(getMissingLanes(existingRoots.map(({ xOffset }) => xOffset)));
|
||||
if (rows.length > 0) transaction.insert(sections).values(rows).run();
|
||||
},
|
||||
{ behavior: "immediate" },
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const getElementsForLayout = (board: Awaited<ReturnType<typeof getFullBoardWithWhereAsync>>, layoutId: string) => {
|
||||
const sectionElements = board.sections
|
||||
.filter((section) => section.kind === "dynamic")
|
||||
.filter((section) => section.kind === "container")
|
||||
.map((section) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const clonedLayout = section.layouts.find((sectionLayout) => sectionLayout.layoutId === layoutId)!;
|
||||
@@ -1771,9 +1910,12 @@ const getElementsForLayout = (board: Awaited<ReturnType<typeof getFullBoardWithW
|
||||
};
|
||||
|
||||
const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, userId: string | null) => {
|
||||
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, userId ?? ""),
|
||||
});
|
||||
const groupPermissionWhere = userId
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
db.select({ groupId: groupMembers.groupId }).from(groupMembers).where(eq(groupMembers.userId, userId)),
|
||||
)
|
||||
: eq(boardGroupPermissions.groupId, "");
|
||||
const board = await db.query.boards.findFirst({
|
||||
where,
|
||||
with: {
|
||||
@@ -1796,8 +1938,8 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
items: {
|
||||
with: {
|
||||
integrations: {
|
||||
with: {
|
||||
integration: true,
|
||||
columns: {
|
||||
integrationId: true,
|
||||
},
|
||||
},
|
||||
layouts: true,
|
||||
@@ -1811,7 +1953,7 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
},
|
||||
},
|
||||
groupPermissions: {
|
||||
where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1859,7 +2001,7 @@ const getFullBoardWithWhereAsync = async (db: Database, where: SQL<unknown>, use
|
||||
layoutId: layout.layoutId,
|
||||
sectionId: layout.sectionId,
|
||||
})),
|
||||
integrationIds: itemIntegrations.map((item) => item.integration.id),
|
||||
integrationIds: itemIntegrations.map((item) => item.integrationId),
|
||||
advancedOptions: superjson.parse<BoardItemAdvancedOptions>(item.advancedOptions),
|
||||
options: superjson.parse<Record<string, unknown>>(item.options),
|
||||
}),
|
||||
|
||||
@@ -19,9 +19,12 @@ export const throwIfActionForbiddenAsync = async (
|
||||
permission: BoardPermission,
|
||||
) => {
|
||||
const { db, session } = ctx;
|
||||
const groupsOfCurrentUser = await db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, session?.user.id ?? ""),
|
||||
});
|
||||
const groupPermissionWhere = session
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
db.select({ groupId: groupMembers.groupId }).from(groupMembers).where(eq(groupMembers.userId, session.user.id)),
|
||||
)
|
||||
: eq(boardGroupPermissions.groupId, "");
|
||||
const board = await db.query.boards.findFirst({
|
||||
where: boardWhere,
|
||||
columns: {
|
||||
@@ -34,7 +37,7 @@ export const throwIfActionForbiddenAsync = async (
|
||||
where: eq(boardUserPermissions.userId, session?.user.id ?? ""),
|
||||
},
|
||||
groupPermissions: {
|
||||
where: inArray(boardGroupPermissions.groupId, groupsOfCurrentUser.map((group) => group.groupId).concat("")),
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
interface BoardPlacement {
|
||||
id: string;
|
||||
kind: string;
|
||||
options: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface CustomWidgetPlacementGuardInput {
|
||||
isAdmin: boolean;
|
||||
submittedItems: readonly BoardPlacement[];
|
||||
storedItems: readonly BoardPlacement[];
|
||||
}
|
||||
|
||||
const throwAdminRequired = () => {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Only administrators can add or configure Custom Widgets",
|
||||
});
|
||||
};
|
||||
|
||||
const assertAuthoringAllowed = (isAdmin: boolean) => {
|
||||
if (!isAdmin) throwAdminRequired();
|
||||
};
|
||||
|
||||
/**
|
||||
* Protects the security-sensitive part of Custom Widget placements while
|
||||
* leaving ordinary board operations (layout, presentation and removal) to the
|
||||
* existing board permission checks.
|
||||
*/
|
||||
export const throwIfCustomWidgetPlacementChangeForbidden = ({
|
||||
isAdmin,
|
||||
submittedItems,
|
||||
storedItems,
|
||||
}: CustomWidgetPlacementGuardInput) => {
|
||||
const storedById = new Map(storedItems.map((item) => [item.id, item]));
|
||||
for (const submitted of submittedItems) {
|
||||
const stored = storedById.get(submitted.id);
|
||||
|
||||
if (!stored) {
|
||||
if (submitted.kind === "customApi") assertAuthoringAllowed(isAdmin);
|
||||
continue;
|
||||
}
|
||||
|
||||
const wasCustomWidget = stored.kind === "customApi";
|
||||
const isCustomWidget = submitted.kind === "customApi";
|
||||
if (wasCustomWidget !== isCustomWidget) {
|
||||
if (isCustomWidget) assertAuthoringAllowed(isAdmin);
|
||||
else if (!isAdmin) throwAdminRequired();
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
wasCustomWidget &&
|
||||
!isDeepStrictEqual(normalizeCustomWidgetOptions(submitted.options), normalizeCustomWidgetOptions(stored.options))
|
||||
) {
|
||||
assertAuthoringAllowed(isAdmin);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const throwIfCustomWidgetBoardDuplicationForbidden = (
|
||||
isAdmin: boolean,
|
||||
items: readonly Pick<BoardPlacement, "kind">[],
|
||||
) => {
|
||||
if (items.some((item) => item.kind === "customApi")) assertAuthoringAllowed(isAdmin);
|
||||
};
|
||||
|
||||
function normalizeCustomWidgetOptions(options: Record<string, unknown>) {
|
||||
return {
|
||||
...options,
|
||||
configuration:
|
||||
options.configuration !== null &&
|
||||
typeof options.configuration === "object" &&
|
||||
!Array.isArray(options.configuration)
|
||||
? options.configuration
|
||||
: {},
|
||||
configurationVersion:
|
||||
typeof options.configurationVersion === "number" && Number.isInteger(options.configurationVersion)
|
||||
? options.configurationVersion
|
||||
: 1,
|
||||
refreshInterval: typeof options.refreshInterval === "number" ? options.refreshInterval : 30,
|
||||
};
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export const generateResponsiveGridFor = ({
|
||||
}: GridAlgorithmInput): GridAlgorithmOutput => {
|
||||
const itemsOfCurrentSection = items
|
||||
.filter((item) => item.sectionId === sectionId)
|
||||
.sort((itemA, itemB) =>
|
||||
.toSorted((itemA, itemB) =>
|
||||
itemA.yOffset === itemB.yOffset ? itemA.xOffset - itemB.xOffset : itemA.yOffset - itemB.yOffset,
|
||||
);
|
||||
const normalizedItems = normalizeItems(itemsOfCurrentSection, width);
|
||||
@@ -42,18 +42,18 @@ export const generateResponsiveGridFor = ({
|
||||
|
||||
const newItems: GridAlgorithmItem[] = [];
|
||||
|
||||
// Fix height of dynamic sections
|
||||
const dynamicSectionHeightMap = new Map<string, number>();
|
||||
const dynamicSectionsOfCurrentSection = normalizedItems.filter((item) => item.type === "section");
|
||||
for (const dynamicSection of dynamicSectionsOfCurrentSection) {
|
||||
// A container must remain tall enough for its recursively reflowed contents.
|
||||
const containerHeightMap = new Map<string, number>();
|
||||
const containersOfCurrentSection = normalizedItems.filter((item) => item.type === "section");
|
||||
for (const container of containersOfCurrentSection) {
|
||||
const result = generateResponsiveGridFor({
|
||||
items,
|
||||
previousWidth: dynamicSection.previousWidth,
|
||||
width: dynamicSection.width,
|
||||
sectionId: dynamicSection.id,
|
||||
previousWidth: container.previousWidth,
|
||||
width: container.width,
|
||||
sectionId: container.id,
|
||||
});
|
||||
newItems.push(...result.items);
|
||||
dynamicSectionHeightMap.set(dynamicSection.id, result.height);
|
||||
containerHeightMap.set(container.id, result.height);
|
||||
}
|
||||
|
||||
// Return same positions for items in the current section
|
||||
@@ -69,7 +69,7 @@ export const generateResponsiveGridFor = ({
|
||||
for (const item of normalizedItems) {
|
||||
const itemWithHeight = {
|
||||
...item,
|
||||
height: item.type === "section" ? Math.max(dynamicSectionHeightMap.get(item.id) ?? 1, item.height) : item.height,
|
||||
height: item.type === "section" ? Math.max(containerHeightMap.get(item.id) ?? 1, item.height) : item.height,
|
||||
};
|
||||
const position = nextFreeSpot(occupied2d, itemWithHeight, width);
|
||||
if (!position) throw new Error("No free spot available");
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
throwIfCustomWidgetBoardDuplicationForbidden,
|
||||
throwIfCustomWidgetPlacementChangeForbidden,
|
||||
} from "../custom-widget-placement-access";
|
||||
|
||||
const placement = {
|
||||
id: "widget-1",
|
||||
kind: "customApi",
|
||||
options: {
|
||||
definitionId: "definition-1",
|
||||
refreshInterval: 30,
|
||||
configuration: { server: "primary" },
|
||||
},
|
||||
};
|
||||
|
||||
describe("Custom Widget placement access", () => {
|
||||
test("non-admins cannot add a Custom Widget placement", () => {
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: false,
|
||||
submittedItems: [{ ...placement, options: { ...placement.options, configurationVersion: 1 } }],
|
||||
storedItems: [],
|
||||
}),
|
||||
).toThrowError("Only administrators can add or configure Custom Widgets");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["definition", { ...placement, options: { ...placement.options, definitionId: "definition-2" } }],
|
||||
["refresh interval", { ...placement, options: { ...placement.options, refreshInterval: 60 } }],
|
||||
[
|
||||
"option configuration",
|
||||
{ ...placement, options: { ...placement.options, configuration: { server: "secondary" } } },
|
||||
],
|
||||
["widget kind", { ...placement, kind: "weather" }],
|
||||
])("non-admins cannot change an existing Custom Widget %s", (_label, submitted) => {
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: false,
|
||||
submittedItems: [submitted],
|
||||
storedItems: [placement],
|
||||
}),
|
||||
).toThrowError("Only administrators can add or configure Custom Widgets");
|
||||
});
|
||||
|
||||
test("non-admins may move, resize and change presentation for an existing placement", () => {
|
||||
const submitted = {
|
||||
...placement,
|
||||
layouts: [{ xOffset: 2, yOffset: 4, width: 6, height: 3 }],
|
||||
advancedOptions: { title: "Status", customCssClasses: ["wide"], borderColor: "#fff" },
|
||||
};
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: false,
|
||||
submittedItems: [submitted],
|
||||
storedItems: [placement],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test("non-admins may remove an existing placement", () => {
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: false,
|
||||
submittedItems: [],
|
||||
storedItems: [placement],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test("admins may create and reconfigure placements", () => {
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: true,
|
||||
submittedItems: [{ ...placement, options: { definitionId: "definition-2" } }],
|
||||
storedItems: [],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
test("duplicating a board with Custom Widgets requires admin", () => {
|
||||
expect(() => throwIfCustomWidgetBoardDuplicationForbidden(false, [placement])).toThrowError(
|
||||
"Only administrators can add or configure Custom Widgets",
|
||||
);
|
||||
expect(() => throwIfCustomWidgetBoardDuplicationForbidden(true, [placement])).not.toThrow();
|
||||
expect(() => throwIfCustomWidgetBoardDuplicationForbidden(false, [{ kind: "weather" }])).not.toThrow();
|
||||
});
|
||||
|
||||
test("treats missing persisted v2 defaults as equivalent during presentation-only edits", () => {
|
||||
expect(() =>
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: false,
|
||||
submittedItems: [placement],
|
||||
storedItems: [
|
||||
{
|
||||
id: placement.id,
|
||||
kind: placement.kind,
|
||||
options: {
|
||||
definitionId: placement.options.definitionId,
|
||||
refreshInterval: placement.options.refreshInterval,
|
||||
configuration: placement.options.configuration,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -25,34 +25,34 @@ describe("Grid Algorithm", () => {
|
||||
|
||||
expect(output).toBe(item.output);
|
||||
});
|
||||
test.each(dynamicSectionTests)(
|
||||
"should convert a grid with dynamic sections from 16 columns to %i columns",
|
||||
test.each(containerTests)(
|
||||
"should convert a grid with nested containers from 16 columns to %i columns",
|
||||
(_, testInput) => {
|
||||
const outerDynamicSectionId = "b";
|
||||
const innerDynamicSectionId = "f";
|
||||
const outerContainerId = "b";
|
||||
const innerContainerId = "f";
|
||||
const items = [
|
||||
algoItem({ id: "a", width: 2, height: 2 }),
|
||||
algoItem({ id: outerDynamicSectionId, type: "section", width: 12, height: 3, yOffset: 2 }),
|
||||
algoItem({ id: "a", width: 2, sectionId: outerDynamicSectionId }),
|
||||
algoItem({ id: "b", width: 4, sectionId: outerDynamicSectionId, xOffset: 2 }),
|
||||
algoItem({ id: "c", width: 2, sectionId: outerDynamicSectionId, xOffset: 6 }),
|
||||
algoItem({ id: "d", width: 1, sectionId: outerDynamicSectionId, xOffset: 8 }),
|
||||
algoItem({ id: "e", width: 3, sectionId: outerDynamicSectionId, xOffset: 9 }),
|
||||
algoItem({ id: outerContainerId, type: "section", width: 12, height: 3, yOffset: 2 }),
|
||||
algoItem({ id: "a", width: 2, sectionId: outerContainerId }),
|
||||
algoItem({ id: "b", width: 4, sectionId: outerContainerId, xOffset: 2 }),
|
||||
algoItem({ id: "c", width: 2, sectionId: outerContainerId, xOffset: 6 }),
|
||||
algoItem({ id: "d", width: 1, sectionId: outerContainerId, xOffset: 8 }),
|
||||
algoItem({ id: "e", width: 3, sectionId: outerContainerId, xOffset: 9 }),
|
||||
algoItem({
|
||||
id: innerDynamicSectionId,
|
||||
id: innerContainerId,
|
||||
type: "section",
|
||||
width: 8,
|
||||
height: 2,
|
||||
yOffset: 1,
|
||||
sectionId: outerDynamicSectionId,
|
||||
sectionId: outerContainerId,
|
||||
}),
|
||||
algoItem({ id: "a", width: 2, sectionId: innerDynamicSectionId }),
|
||||
algoItem({ id: "b", width: 5, xOffset: 2, sectionId: innerDynamicSectionId }),
|
||||
algoItem({ id: "c", width: 1, height: 2, xOffset: 7, sectionId: innerDynamicSectionId }),
|
||||
algoItem({ id: "d", width: 7, yOffset: 1, sectionId: innerDynamicSectionId }),
|
||||
algoItem({ id: "g", width: 4, yOffset: 1, sectionId: outerDynamicSectionId, xOffset: 8 }),
|
||||
algoItem({ id: "h", width: 3, yOffset: 2, sectionId: outerDynamicSectionId, xOffset: 8 }),
|
||||
algoItem({ id: "i", width: 1, yOffset: 2, sectionId: outerDynamicSectionId, xOffset: 11 }),
|
||||
algoItem({ id: "a", width: 2, sectionId: innerContainerId }),
|
||||
algoItem({ id: "b", width: 5, xOffset: 2, sectionId: innerContainerId }),
|
||||
algoItem({ id: "c", width: 1, height: 2, xOffset: 7, sectionId: innerContainerId }),
|
||||
algoItem({ id: "d", width: 7, yOffset: 1, sectionId: innerContainerId }),
|
||||
algoItem({ id: "g", width: 4, yOffset: 1, sectionId: outerContainerId, xOffset: 8 }),
|
||||
algoItem({ id: "h", width: 3, yOffset: 2, sectionId: outerContainerId, xOffset: 8 }),
|
||||
algoItem({ id: "i", width: 1, yOffset: 2, sectionId: outerContainerId, xOffset: 11 }),
|
||||
algoItem({ id: "c", width: 5, yOffset: 5 }),
|
||||
];
|
||||
|
||||
@@ -64,10 +64,10 @@ describe("Grid Algorithm", () => {
|
||||
});
|
||||
|
||||
const rootItems = newItems.items.filter((item) => item.sectionId === ROOT_SECTION_ID);
|
||||
const outerSection = items.find((item) => item.id === outerDynamicSectionId);
|
||||
const outerItems = newItems.items.filter((item) => item.sectionId === outerDynamicSectionId);
|
||||
const innerSection = items.find((item) => item.id === innerDynamicSectionId);
|
||||
const innerItems = newItems.items.filter((item) => item.sectionId === innerDynamicSectionId);
|
||||
const outerSection = items.find((item) => item.id === outerContainerId);
|
||||
const outerItems = newItems.items.filter((item) => item.sectionId === outerContainerId);
|
||||
const innerSection = items.find((item) => item.id === innerContainerId);
|
||||
const innerItems = newItems.items.filter((item) => item.sectionId === innerContainerId);
|
||||
|
||||
expect(generateOutputText(rootItems, testInput.outputColumns)).toBe(testInput.root);
|
||||
expect(generateOutputText(outerItems, Math.min(testInput.outputColumns, outerSection?.width ?? 999))).toBe(
|
||||
@@ -192,7 +192,7 @@ const itemTests = [
|
||||
},
|
||||
].map((item) => [item.inputColumnCount, item.outputColumnCount, item] as const);
|
||||
|
||||
const dynamicSectionTests = [
|
||||
const containerTests = [
|
||||
{
|
||||
outputColumns: 16,
|
||||
root: `
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
export const AUTH_HANDLERS: Record<string, (headers: Headers, url: URL, apiKey: string, headerName?: string) => void> =
|
||||
{
|
||||
bearer: (headers, _url, apiKey) => {
|
||||
headers.set("Authorization", `Bearer ${apiKey}`);
|
||||
},
|
||||
apiKeyHeader: (headers, _url, apiKey, headerName) => {
|
||||
headers.set(headerName ?? "X-API-Key", apiKey);
|
||||
},
|
||||
apiKeyQuery: (_headers, url, apiKey, headerName) => {
|
||||
url.searchParams.set(headerName ?? "api_key", apiKey);
|
||||
},
|
||||
};
|
||||
type HeaderSetter = Pick<Headers, "set">;
|
||||
|
||||
export const AUTH_HANDLERS: Record<
|
||||
string,
|
||||
(headers: HeaderSetter, url: URL, apiKey: string, headerName?: string) => void
|
||||
> = {
|
||||
bearer: (headers, _url, apiKey) => {
|
||||
headers.set("Authorization", `Bearer ${apiKey}`);
|
||||
},
|
||||
apiKeyHeader: (headers, _url, apiKey, headerName) => {
|
||||
headers.set(headerName ?? "X-API-Key", apiKey);
|
||||
},
|
||||
apiKeyQuery: (_headers, url, apiKey, headerName) => {
|
||||
url.searchParams.set(headerName ?? "api_key", apiKey);
|
||||
},
|
||||
};
|
||||
|
||||
export function buildSecretMap(secrets: Array<{ kind: string; value: string }>): Record<string, string> {
|
||||
const map: Record<string, string> = {};
|
||||
@@ -20,7 +24,7 @@ export function buildSecretMap(secrets: Array<{ kind: string; value: string }>):
|
||||
}
|
||||
|
||||
export function applyAuth(
|
||||
headers: Headers,
|
||||
headers: HeaderSetter,
|
||||
url: URL,
|
||||
authType: string,
|
||||
secrets: Array<{ kind: string; value: string }>,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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";
|
||||
import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
|
||||
const CONFIGURATION_REQUEST_TTL_MS = 10 * 60_000;
|
||||
const CONFIGURATION_REQUEST_PREFIX = "custom-widget:configuration-request:";
|
||||
const CONFIGURATION_REQUEST_LOCK_PREFIX = "custom-widget:configuration-request-lock:";
|
||||
|
||||
export interface CustomWidgetConfigurationRequest {
|
||||
id: string;
|
||||
userId: string;
|
||||
target: { type: "definition"; id: string } | { type: "preview"; id: string };
|
||||
widgetName: string;
|
||||
sourceId: string;
|
||||
sourceName: string;
|
||||
source: CustomWidgetSource;
|
||||
kinds: CustomWidgetSecretKind[];
|
||||
expiresAt: number;
|
||||
status: "pending" | "completed";
|
||||
}
|
||||
|
||||
const localRequests = new Map<string, CustomWidgetConfigurationRequest>();
|
||||
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: CustomWidgetConfigurationRequest) {
|
||||
const ttl = Math.max(1, request.expiresAt - Date.now());
|
||||
const client = getRedis();
|
||||
if (client) await client.set(`${CONFIGURATION_REQUEST_PREFIX}${request.id}`, JSON.stringify(request), "PX", ttl);
|
||||
else localRequests.set(request.id, request);
|
||||
}
|
||||
|
||||
export async function createCustomWidgetConfigurationRequest(
|
||||
input: Omit<CustomWidgetConfigurationRequest, "id" | "expiresAt" | "status">,
|
||||
) {
|
||||
const request: CustomWidgetConfigurationRequest = {
|
||||
...input,
|
||||
id: createId(),
|
||||
expiresAt: Date.now() + CONFIGURATION_REQUEST_TTL_MS,
|
||||
status: "pending",
|
||||
};
|
||||
await save(request);
|
||||
return request;
|
||||
}
|
||||
|
||||
export async function getCustomWidgetConfigurationRequest(id: string) {
|
||||
const client = getRedis();
|
||||
const candidate = client ? await client.get(`${CONFIGURATION_REQUEST_PREFIX}${id}`) : localRequests.get(id);
|
||||
if (!candidate) return null;
|
||||
try {
|
||||
const request = (
|
||||
typeof candidate === "string" ? JSON.parse(candidate) : candidate
|
||||
) as CustomWidgetConfigurationRequest;
|
||||
if (request.expiresAt <= Date.now()) {
|
||||
if (client) await client.del(`${CONFIGURATION_REQUEST_PREFIX}${id}`);
|
||||
else localRequests.delete(id);
|
||||
return null;
|
||||
}
|
||||
return request;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCustomWidgetConfigurationRequestForUser(id: string, userId: string) {
|
||||
const request = await getCustomWidgetConfigurationRequest(id);
|
||||
return request?.userId === userId ? request : null;
|
||||
}
|
||||
|
||||
export async function completeCustomWidgetConfigurationRequest(id: string) {
|
||||
const request = await getCustomWidgetConfigurationRequest(id);
|
||||
if (!request || request.status !== "pending") return null;
|
||||
const completed = { ...request, status: "completed" as const };
|
||||
await save(completed);
|
||||
await releaseCustomWidgetConfigurationRequest(id);
|
||||
return completed;
|
||||
}
|
||||
|
||||
export async function claimCustomWidgetConfigurationRequest(id: string) {
|
||||
const request = await getCustomWidgetConfigurationRequest(id);
|
||||
if (!request || request.status !== "pending") return null;
|
||||
const client = getRedis();
|
||||
if (client) {
|
||||
const claimed = await client.set(`${CONFIGURATION_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 releaseCustomWidgetConfigurationRequest(id: string) {
|
||||
const client = getRedis();
|
||||
if (client) await client.del(`${CONFIGURATION_REQUEST_LOCK_PREFIX}${id}`);
|
||||
else localLocks.delete(id);
|
||||
}
|
||||
|
||||
export { setPreviewSessionSecrets } from "./preview-sessions";
|
||||
@@ -1,216 +1,203 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecret, encryptSecret } from "@homarr/common/server";
|
||||
import { boards, customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import { eq } from "@homarr/db";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { and, eq, handleTransactionsAsync, notInArray } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import {
|
||||
customWidgetAuthTypes,
|
||||
customWidgetCreateSchema,
|
||||
customWidgetDisplayTypes,
|
||||
customWidgetImportSchema,
|
||||
customWidgetMethods,
|
||||
customWidgetSecretKinds,
|
||||
customWidgetDefinitionSchema,
|
||||
customWidgetUpdateSchema,
|
||||
displayConfigSchema,
|
||||
} from "@homarr/validation/custom-widget";
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { assertCustomApiItemBindingAsync, customApiItemInputSchema } from "./custom-widget-access";
|
||||
import { applyAuth } from "./auth";
|
||||
import { extractDisplayDataWithFallback } from "./display-data";
|
||||
import { parseDisplayConfig } from "./parse-display-config";
|
||||
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
|
||||
import { insertCustomWidgetDefinition } from "./definition-insert";
|
||||
import { managementQueryProcedures } from "./management-queries";
|
||||
import { metadataProcedures } from "./metadata-procedures";
|
||||
import { previewActionProcedures } from "./preview-action-procedures";
|
||||
import { previewBaseProcedures } from "./preview-base-procedures";
|
||||
import { previewQueryProcedures } from "./preview-query-procedures";
|
||||
import {
|
||||
consumeBoundedResponseAsync,
|
||||
readBoundedJsonResponseAsync,
|
||||
validateCustomApiUrl,
|
||||
withCustomApiResponseAsync,
|
||||
} from "../widgets/custom-api-security";
|
||||
|
||||
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
|
||||
parseStoredCustomWidgetDefinition,
|
||||
safeParseStoredCustomWidgetDefinition,
|
||||
serializeCustomWidgetDefinition,
|
||||
} from "./stored-definition";
|
||||
import { templateProcedures } from "./template-procedures";
|
||||
import { transferProcedures } from "./transfer-procedures";
|
||||
import { assertSecretSources, hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
|
||||
import { secretProcedures } from "./secret-procedures";
|
||||
import { workshopProcedures } from "./workshop-procedures";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
const PUBLIC_PREVIEW_ERROR = "Custom API preview failed";
|
||||
|
||||
const updateFieldSerializers: Record<string, (value: unknown) => unknown> = {
|
||||
displayConfig: (value) => superjson.stringify(value),
|
||||
};
|
||||
|
||||
let _importJsonSchema: Record<string, unknown> | null = null;
|
||||
function getImportJsonSchema() {
|
||||
if (!_importJsonSchema) {
|
||||
_importJsonSchema = {
|
||||
...z.toJSONSchema(customWidgetImportSchema),
|
||||
title: "Homarr Custom Widget",
|
||||
description:
|
||||
"Schema for importing/exporting custom widget definitions in Homarr. " +
|
||||
"All jsonPath fields use JSONPath syntax (e.g. $.data.count, $.items[0].name). " +
|
||||
"The displayConfig must match the chosen displayType. " +
|
||||
"Secrets (API keys, passwords) are not included in exports and must be configured separately after import.",
|
||||
};
|
||||
}
|
||||
return _importJsonSchema;
|
||||
}
|
||||
|
||||
export const customWidgetRouter = createTRPCRouter({
|
||||
schema: publicProcedure.query(() => getImportJsonSchema()),
|
||||
...metadataProcedures,
|
||||
...managementQueryProcedures,
|
||||
|
||||
all: adminProcedure.query(async ({ ctx }) => {
|
||||
const definitions = await ctx.db.query.customWidgetDefinitions.findMany({
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
});
|
||||
|
||||
return definitions.map((def) => ({
|
||||
id: def.id,
|
||||
name: def.name,
|
||||
description: def.description,
|
||||
iconUrl: def.iconUrl,
|
||||
url: def.url,
|
||||
method: def.method,
|
||||
displayType: def.displayType,
|
||||
authType: def.authType,
|
||||
enabled: def.enabled,
|
||||
}));
|
||||
}),
|
||||
|
||||
available: protectedProcedure
|
||||
.input(z.object({ boardId: z.string().min(1).max(100) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
|
||||
return await ctx.db.query.customWidgetDefinitions.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
iconUrl: true,
|
||||
displayType: true,
|
||||
enabled: true,
|
||||
},
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
});
|
||||
create: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Create one validated Custom JSX widget." } })
|
||||
.input(customWidgetCreateSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { secrets, ...candidate } = input;
|
||||
const definition = customWidgetDefinitionSchema.parse(candidate);
|
||||
assertSecretSources(definition.sources, secrets);
|
||||
const id = await insertCustomWidgetDefinition(ctx.db, definition, ctx.session.user.id, secrets);
|
||||
logger.info("Created custom widget definition", { id, name: definition.name });
|
||||
return { id };
|
||||
}),
|
||||
|
||||
byId: adminProcedure.input(z.object({ id: z.string() })).query(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", message: "Custom widget definition not found" });
|
||||
}
|
||||
|
||||
const displayConfig = parseDisplayConfig(
|
||||
definition.displayConfig,
|
||||
input.id,
|
||||
logger,
|
||||
"Corrupt displayConfig in custom widget",
|
||||
);
|
||||
|
||||
return {
|
||||
...definition,
|
||||
enabled: definition.enabled,
|
||||
displayConfig,
|
||||
secrets: definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
hasValue: true,
|
||||
updatedAt: s.updatedAt,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
create: adminProcedure.input(customWidgetCreateSchema).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: superjson.stringify(input.displayConfig),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
|
||||
if (input.secrets.length > 0) {
|
||||
await ctx.db.insert(customWidgetSecrets).values(
|
||||
input.secrets.map((secret) => ({
|
||||
kind: secret.kind,
|
||||
value: encryptSecret(secret.value),
|
||||
definitionId: id,
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
logger.info("Created custom widget definition", { id, name: input.name });
|
||||
return { id };
|
||||
}),
|
||||
|
||||
update: adminProcedure.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" });
|
||||
}
|
||||
|
||||
const { id, secrets, ...updateFields } = input;
|
||||
const updateValues: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
||||
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.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") {
|
||||
await ctx.db.delete(customWidgetSecrets).where(eq(customWidgetSecrets.definitionId, id));
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("Updated custom widget definition", { id });
|
||||
}),
|
||||
|
||||
toggleEnabled: adminProcedure
|
||||
.input(z.object({ id: z.string(), enabled: z.boolean() }))
|
||||
update: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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 current = parseStoredCustomWidgetDefinition(existing);
|
||||
const { id, secrets, ...changes } = input;
|
||||
const definition = customWidgetDefinitionSchema.parse({ ...current, ...changes });
|
||||
if (secrets) assertSecretSources(definition.sources, secrets);
|
||||
const definitionChanges = { ...serializeCustomWidgetDefinition(definition), updatedAt: new Date() };
|
||||
const secretRows = secrets?.map((secret) => ({
|
||||
definitionId: id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
}));
|
||||
const sourceIds = Object.keys(definition.sources);
|
||||
const changedSecretBindings = new Set(
|
||||
Object.entries(definition.sources).flatMap(([sourceId, source]) => {
|
||||
const previous = current.sources[sourceId];
|
||||
return previous && !hasSameSecretBinding(previous, source) ? [sourceId] : [];
|
||||
}),
|
||||
);
|
||||
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(db, schema) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set(definitionChanges)
|
||||
.where(eq(schema.customWidgetDefinitions.id, id));
|
||||
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, id),
|
||||
notInArray(schema.customWidgetSecrets.sourceId, sourceIds),
|
||||
),
|
||||
);
|
||||
|
||||
for (const sourceId of changedSecretBindings) {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, id),
|
||||
eq(schema.customWidgetSecrets.sourceId, sourceId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const [sourceId, source] of Object.entries(definition.sources)) {
|
||||
const kinds = [...requiredSecretKinds(typeof source.auth === "string" ? source.auth : source.auth.type)];
|
||||
const where = and(
|
||||
eq(schema.customWidgetSecrets.definitionId, id),
|
||||
eq(schema.customWidgetSecrets.sourceId, sourceId),
|
||||
);
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(kinds.length > 0 ? and(where, notInArray(schema.customWidgetSecrets.kind, kinds)) : where);
|
||||
}
|
||||
|
||||
for (const secret of secretRows ?? []) {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, id),
|
||||
eq(schema.customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await transaction.insert(schema.customWidgetSecrets).values(secret);
|
||||
}
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set(definitionChanges)
|
||||
.where(eq(customWidgetDefinitions.id, id))
|
||||
.run();
|
||||
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(and(eq(customWidgetSecrets.definitionId, id), notInArray(customWidgetSecrets.sourceId, sourceIds)))
|
||||
.run();
|
||||
|
||||
for (const sourceId of changedSecretBindings) {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(and(eq(customWidgetSecrets.definitionId, id), eq(customWidgetSecrets.sourceId, sourceId)))
|
||||
.run();
|
||||
}
|
||||
|
||||
for (const [sourceId, source] of Object.entries(definition.sources)) {
|
||||
const kinds = [...requiredSecretKinds(typeof source.auth === "string" ? source.auth : source.auth.type)];
|
||||
const where = and(eq(customWidgetSecrets.definitionId, id), eq(customWidgetSecrets.sourceId, sourceId));
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(kinds.length > 0 ? and(where, notInArray(customWidgetSecrets.kind, kinds)) : where)
|
||||
.run();
|
||||
}
|
||||
|
||||
for (const secret of secretRows ?? []) {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, id),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
transaction.insert(customWidgetSecrets).values(secret).run();
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
logger.info("Updated custom widget definition", { id });
|
||||
}),
|
||||
|
||||
...secretProcedures,
|
||||
...workshopProcedures,
|
||||
|
||||
toggleEnabled: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(z.object({ id: z.string(), enabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.enabled) {
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
if (!safeParseStoredCustomWidgetDefinition(definition).success) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Invalid custom widget definition cannot be enabled",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
@@ -219,243 +206,36 @@ export const customWidgetRouter = createTRPCRouter({
|
||||
.where(eq(customWidgetDefinitions.id, input.id));
|
||||
}),
|
||||
|
||||
delete: adminProcedure.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 });
|
||||
}),
|
||||
|
||||
export: adminProcedure.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-v2" 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",
|
||||
),
|
||||
};
|
||||
}),
|
||||
|
||||
import: adminProcedure.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: superjson.stringify(input.displayConfig),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
|
||||
logger.info("Imported custom widget definition", { id, name: input.name });
|
||||
return { id };
|
||||
}),
|
||||
|
||||
preview: adminProcedure
|
||||
.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() })),
|
||||
definitionId: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
delete: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Delete one Custom JSX widget." } })
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
try {
|
||||
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 url = validateCustomApiUrl(input.url);
|
||||
const headers = new Headers({ Accept: "application/json" });
|
||||
if (input.method !== "GET" && input.requestBody) headers.set("Content-Type", "application/json");
|
||||
applyAuth(headers, url, input.authType, secrets, input.headerName);
|
||||
|
||||
return await withCustomApiResponseAsync(
|
||||
url,
|
||||
{
|
||||
method: input.method,
|
||||
headers,
|
||||
body: input.method !== "GET" ? input.requestBody : undefined,
|
||||
},
|
||||
async (response) => {
|
||||
const responseInfo = { status: response.status };
|
||||
if (!response.ok) {
|
||||
await consumeBoundedResponseAsync(response);
|
||||
return {
|
||||
success: false as const,
|
||||
error: PUBLIC_PREVIEW_ERROR,
|
||||
responseInfo,
|
||||
rawResponse: null,
|
||||
};
|
||||
}
|
||||
|
||||
const json = await readBoundedJsonResponseAsync(response);
|
||||
const displayData = extractDisplayDataWithFallback(json, input.displayType, input.displayConfig);
|
||||
return {
|
||||
success: true as const,
|
||||
responseInfo,
|
||||
rawResponse: JSON.stringify(json, null, 2),
|
||||
displayData,
|
||||
};
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
const errorId = createId();
|
||||
logger.error("Custom widget preview failed", { errorId, error });
|
||||
return {
|
||||
success: false as const,
|
||||
error: PUBLIC_PREVIEW_ERROR,
|
||||
responseInfo: null,
|
||||
rawResponse: null,
|
||||
};
|
||||
}
|
||||
await ctx.db.delete(customWidgetDefinitions).where(eq(customWidgetDefinitions.id, input.id));
|
||||
logger.info("Deleted custom widget definition", { id: input.id });
|
||||
}),
|
||||
|
||||
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 },
|
||||
});
|
||||
duplicate: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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" });
|
||||
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)` };
|
||||
}),
|
||||
|
||||
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)` };
|
||||
}),
|
||||
|
||||
execute: adminProcedure.input(customApiItemInputSchema).mutation(async ({ ctx, input }) => {
|
||||
await assertCustomApiItemBindingAsync(ctx, input);
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.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 (definition.displayType !== "actionButton") {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Only actionButton widgets can be executed" });
|
||||
}
|
||||
|
||||
try {
|
||||
const decryptedSecrets = definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
value: decryptSecret(s.value),
|
||||
}));
|
||||
const url = validateCustomApiUrl(definition.url);
|
||||
const headers = new Headers({ Accept: "application/json" });
|
||||
if (definition.method !== "GET" && definition.requestBody) headers.set("Content-Type", "application/json");
|
||||
applyAuth(headers, url, definition.authType, decryptedSecrets, definition.headerName);
|
||||
|
||||
return await withCustomApiResponseAsync(
|
||||
url,
|
||||
{
|
||||
method: definition.method,
|
||||
headers,
|
||||
body: definition.method !== "GET" ? definition.requestBody : undefined,
|
||||
},
|
||||
async (response) => {
|
||||
await consumeBoundedResponseAsync(response);
|
||||
const responseInfo = { status: response.status };
|
||||
if (!response.ok) {
|
||||
return { success: false as const, errorCode: "UPSTREAM_REJECTED" as const, responseInfo };
|
||||
}
|
||||
logger.info("Executed custom widget action", { definitionId: input.definitionId, status: response.status });
|
||||
return { success: true as const, responseInfo };
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
const errorId = createId();
|
||||
logger.error("Custom widget execute failed", { errorId, definitionId: input.definitionId, error });
|
||||
return {
|
||||
success: false as const,
|
||||
errorCode: "REQUEST_FAILED" as const,
|
||||
responseInfo: null,
|
||||
};
|
||||
}
|
||||
}),
|
||||
...templateProcedures,
|
||||
...transferProcedures,
|
||||
...previewBaseProcedures,
|
||||
...previewQueryProcedures,
|
||||
...previewActionProcedures,
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { handleTransactionsAsync } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import type { CustomWidgetCreateInput, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
export async function insertCustomWidgetDefinition(
|
||||
db: Database,
|
||||
definition: HomarrCustomWidgetV2,
|
||||
creatorId: string,
|
||||
secrets: CustomWidgetCreateInput["secrets"],
|
||||
) {
|
||||
const id = createId();
|
||||
const definitionRow = { id, ...serializeCustomWidgetDefinition(definition), creatorId };
|
||||
const updatedAt = new Date();
|
||||
const secretRows = secrets.map((secret) => ({
|
||||
definitionId: id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt,
|
||||
}));
|
||||
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction.insert(schema.customWidgetDefinitions).values(definitionRow);
|
||||
if (secretRows.length > 0) await transaction.insert(schema.customWidgetSecrets).values(secretRows);
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction.insert(customWidgetDefinitions).values(definitionRow).run();
|
||||
if (secretRows.length > 0) transaction.insert(customWidgetSecrets).values(secretRows).run();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
import { JSONPath } from "jsonpath-plus";
|
||||
|
||||
type Config = Record<string, unknown>;
|
||||
type Extractor = (json: unknown, config: Config) => unknown;
|
||||
|
||||
const query = (json: unknown, path: string) => JSONPath({ path, json: json as object, wrap: false });
|
||||
|
||||
const queryRows = (json: unknown, path: string): unknown[] => {
|
||||
const rows = JSONPath({ path, json: json as object, wrap: true }) as unknown[];
|
||||
const first = rows[0];
|
||||
if (Array.isArray(first)) return first as unknown[];
|
||||
return rows;
|
||||
};
|
||||
|
||||
const toNumber = (value: unknown, fallback: number): number => {
|
||||
const num = Number(value);
|
||||
if (num) return num;
|
||||
return fallback;
|
||||
};
|
||||
|
||||
const optionalMax = (max: unknown): number | undefined => {
|
||||
if (max === undefined) return undefined;
|
||||
return toNumber(max, 100);
|
||||
};
|
||||
|
||||
const isGoodValue = (value: unknown, goodValues: string[]): boolean =>
|
||||
goodValues.some((gv) => String(value).toLowerCase() === gv.toLowerCase());
|
||||
|
||||
const extractors: Record<string, Extractor> = {
|
||||
singleValue: (json, c) => ({
|
||||
type: "singleValue",
|
||||
label: (c.label as string) ?? "",
|
||||
unit: (c.unit as string) ?? "",
|
||||
value: query(json, (c.jsonPath as string) ?? "$"),
|
||||
valueSize: c.valueSize ?? "lg",
|
||||
labelPosition: c.labelPosition ?? "below",
|
||||
}),
|
||||
keyValue: (json, c) => ({
|
||||
type: "keyValue",
|
||||
entries: ((c.mappings as Array<{ label: string; jsonPath: string; unit: string }>) ?? []).map((m) => ({
|
||||
label: m.label,
|
||||
unit: m.unit,
|
||||
value: query(json, m.jsonPath),
|
||||
})),
|
||||
layout: c.layout ?? "list",
|
||||
columns: c.columns ?? 2,
|
||||
}),
|
||||
table: (json, c) => {
|
||||
const columns = (c.columns as Array<{ header: string; jsonPath: string }>) ?? [];
|
||||
const flatRows = queryRows(json, (c.tablePath as string) ?? "$");
|
||||
return {
|
||||
type: "table",
|
||||
columns: columns.map((col) => col.header),
|
||||
rows: flatRows.map((row) => columns.map((col) => query(row, col.jsonPath))),
|
||||
striped: c.striped ?? true,
|
||||
compact: c.compact ?? false,
|
||||
};
|
||||
},
|
||||
statGrid: (json, c) => ({
|
||||
type: "statGrid",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; unit: string; color?: string }>) ?? []).map(
|
||||
(item) => ({
|
||||
label: item.label,
|
||||
unit: item.unit,
|
||||
color: item.color ?? "blue",
|
||||
value: query(json, item.jsonPath),
|
||||
}),
|
||||
),
|
||||
columns: c.columns ?? 2,
|
||||
cardStyle: c.cardStyle ?? "filled",
|
||||
}),
|
||||
progressBars: (json, c) => ({
|
||||
type: "progressBars",
|
||||
bars: (
|
||||
(c.bars as Array<{ label: string; valuePath: string; maxPath?: string; unit: string; color?: string }>) ?? []
|
||||
).map((bar) => {
|
||||
const value = query(json, bar.valuePath);
|
||||
const max = bar.maxPath ? query(json, bar.maxPath) : undefined;
|
||||
return {
|
||||
label: bar.label,
|
||||
unit: bar.unit,
|
||||
color: bar.color ?? "blue",
|
||||
value: toNumber(value, 0),
|
||||
max: optionalMax(max),
|
||||
};
|
||||
}),
|
||||
showPercentage: c.showPercentage ?? true,
|
||||
barSize: c.barSize ?? "md",
|
||||
}),
|
||||
statusIndicator: (json, c) => ({
|
||||
type: "statusIndicator",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; goodValues: string[] }>) ?? []).map((item) => {
|
||||
const value = query(json, item.jsonPath);
|
||||
return { label: item.label, value: String(value ?? "unknown"), isGood: isGoodValue(value, item.goodValues) };
|
||||
}),
|
||||
layout: c.layout ?? "list",
|
||||
dotSize: c.dotSize ?? "md",
|
||||
}),
|
||||
countGrid: (json, c) => ({
|
||||
type: "countGrid",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; unit: string }>) ?? []).map((item) => ({
|
||||
label: item.label,
|
||||
unit: item.unit,
|
||||
value: query(json, item.jsonPath),
|
||||
})),
|
||||
columns: c.columns ?? 2,
|
||||
valueSize: c.valueSize ?? "md",
|
||||
}),
|
||||
raw: (json, c) => ({
|
||||
type: "raw",
|
||||
data: query(json, (c.jsonPath as string) ?? "$"),
|
||||
maxHeight: c.maxHeight ?? 300,
|
||||
}),
|
||||
actionButton: (_json, c) => extractActionButtonDisplay(c),
|
||||
customJsx: (json, config) => ({
|
||||
type: "customJsx" as const,
|
||||
template: config.template as string,
|
||||
data: json,
|
||||
}),
|
||||
};
|
||||
|
||||
export function extractDisplayData(json: unknown, displayType: string, displayConfig: Config): unknown {
|
||||
const type = (displayConfig.type as string) ?? displayType;
|
||||
const extractor = extractors[type];
|
||||
if (!extractor) {
|
||||
throw new Error(`Unknown display type: ${type}`);
|
||||
}
|
||||
return extractor(json, displayConfig);
|
||||
}
|
||||
|
||||
export function extractDisplayDataWithFallback(json: unknown, displayType: string, displayConfig: Config): unknown {
|
||||
const type = (displayConfig.type as string) ?? displayType;
|
||||
const extractor = extractors[type] ?? extractors.singleValue;
|
||||
return extractor?.(json, displayConfig);
|
||||
}
|
||||
|
||||
export interface ActionButtonDisplayData {
|
||||
type: "actionButton";
|
||||
buttonLabel: string;
|
||||
buttonColor: string;
|
||||
confirmText: string;
|
||||
successMessage: string;
|
||||
}
|
||||
|
||||
export function extractActionButtonDisplay(displayConfig: Config): ActionButtonDisplayData {
|
||||
return {
|
||||
type: "actionButton",
|
||||
buttonLabel: typeof displayConfig.buttonLabel === "string" ? displayConfig.buttonLabel : "Execute",
|
||||
buttonColor: typeof displayConfig.buttonColor === "string" ? displayConfig.buttonColor : "blue",
|
||||
confirmText: typeof displayConfig.confirmText === "string" ? displayConfig.confirmText : "",
|
||||
successMessage: typeof displayConfig.successMessage === "string" ? displayConfig.successMessage : "",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { FlattenError } from "@homarr/common";
|
||||
import { CustomWidgetDomainError } from "@homarr/custom-widgets/server";
|
||||
|
||||
class RequestLimitTransportError extends FlattenError {}
|
||||
|
||||
export function toTrpcError(error: unknown): never {
|
||||
if (error instanceof CustomWidgetDomainError) {
|
||||
const cause = error.retryAfterMs
|
||||
? new RequestLimitTransportError(error.message, { retryAfterMs: error.retryAfterMs })
|
||||
: error;
|
||||
throw new TRPCError({ code: error.code, message: error.message, cause });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { legacyCustomWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { buildCustomWidgetAiPrompt } from "@homarr/custom-widgets/authoring-prompt";
|
||||
|
||||
type LegacyCustomWidgetDefinition = typeof legacyCustomWidgetDefinitions.$inferSelect;
|
||||
|
||||
export function buildLegacyCustomWidgetMigrationPrompt(
|
||||
definition: LegacyCustomWidgetDefinition,
|
||||
configuredSecretKinds: readonly string[],
|
||||
) {
|
||||
const legacyDefinition = {
|
||||
$schema: "homarr-custom-widget-v1",
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl ? redactLegacyUrl(definition.iconUrl) : null,
|
||||
url: redactLegacyUrl(definition.url),
|
||||
authType: definition.authType,
|
||||
headerName: definition.headerName,
|
||||
method: definition.method,
|
||||
requestBody: redactLegacyRequestBody(definition.requestBody),
|
||||
displayType: definition.displayType,
|
||||
displayConfig: {
|
||||
migrationNote:
|
||||
"The preserved v1 display configuration was intentionally omitted because legacy free-text fields may contain credentials. Reconstruct it from the display type and visible behavior.",
|
||||
},
|
||||
configuredSecretKinds,
|
||||
};
|
||||
return buildCustomWidgetAiPrompt(
|
||||
undefined,
|
||||
undefined,
|
||||
legacyDefinition,
|
||||
[
|
||||
"Migrate this preserved Homarr v1 Custom Widget to Custom JSX v2.",
|
||||
"Preserve its visible behavior and API intent, use a source named default, and return importable v2 JSON plus JSX.",
|
||||
"The URL and request-body values may be redacted; keep placeholders and never invent or include credentials.",
|
||||
"Credential kinds are informational only and must be configured separately in Homarr.",
|
||||
].join(" "),
|
||||
);
|
||||
}
|
||||
|
||||
function redactLegacyUrl(value: string) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
url.username = "";
|
||||
url.password = "";
|
||||
url.hash = "";
|
||||
url.pathname = url.pathname
|
||||
.split("/")
|
||||
.map((segment) => (segment ? "[REDACTED]" : segment))
|
||||
.join("/");
|
||||
for (const key of url.searchParams.keys()) url.searchParams.set(key, "[REDACTED]");
|
||||
return url.toString();
|
||||
} catch {
|
||||
return "[INVALID LEGACY URL — enter the API URL in Homarr]";
|
||||
}
|
||||
}
|
||||
|
||||
function redactLegacyRequestBody(value: string | null) {
|
||||
if (!value) return value;
|
||||
try {
|
||||
return JSON.stringify(redactAllValues(JSON.parse(value) as unknown));
|
||||
} catch {
|
||||
return "[REDACTED LEGACY REQUEST BODY]";
|
||||
}
|
||||
}
|
||||
|
||||
function redactAllValues(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(redactAllValues);
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, redactAllValues(child)]));
|
||||
if (value === null) return null;
|
||||
return "[REDACTED VALUE]";
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { eq, or } from "@homarr/db";
|
||||
import { boards, customWidgetDefinitions, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { collectCustomWidgetRequestReferences } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
import { executeCustomWidgetRequest } from "./request-executor";
|
||||
import {
|
||||
hashRuntimeParams,
|
||||
renderRequestBody,
|
||||
renderRequestTarget,
|
||||
resolveCustomWidgetRequestValues,
|
||||
} from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { getCustomWidgetCacheVersion } from "./cache-version";
|
||||
import { buildLegacyCustomWidgetMigrationPrompt } from "./legacy-migration";
|
||||
import {
|
||||
mapAvailableCustomWidget,
|
||||
mapCustomWidgetListItem,
|
||||
mapLegacyAvailableCustomWidget,
|
||||
mapLegacyCustomWidgetListItem,
|
||||
} from "./management-query-mappers";
|
||||
|
||||
export const managementQueryProcedures = {
|
||||
list: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "List all Custom JSX widgets." } })
|
||||
.query(async ({ ctx }) => {
|
||||
const [definitions, legacyDefinitions] = await Promise.all([
|
||||
ctx.db.query.customWidgetDefinitions.findMany({
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
with: { secrets: true },
|
||||
}),
|
||||
ctx.db.query.legacyCustomWidgetDefinitions.findMany({
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
with: { secrets: true },
|
||||
}),
|
||||
]);
|
||||
const current = definitions.map(mapCustomWidgetListItem);
|
||||
const currentIds = new Set(definitions.map(({ id }) => id));
|
||||
const legacy = legacyDefinitions.filter(({ id }) => !currentIds.has(id)).map(mapLegacyCustomWidgetListItem);
|
||||
return [...current, ...legacy].toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}),
|
||||
|
||||
legacyMigrationPrompt: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get a redacted AI migration prompt for one preserved legacy Custom Widget. Credentials must be configured separately.",
|
||||
},
|
||||
})
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const definition = await ctx.db.query.legacyCustomWidgetDefinitions.findFirst({
|
||||
where: eq(legacyCustomWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Legacy custom widget not found" });
|
||||
return {
|
||||
id: definition.id,
|
||||
version: 1 as const,
|
||||
prompt: buildLegacyCustomWidgetMigrationPrompt(
|
||||
definition,
|
||||
definition.secrets.map(({ kind }) => kind),
|
||||
),
|
||||
};
|
||||
}),
|
||||
|
||||
get: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!definition) throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
return {
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
available: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(z.object({ boardId: z.string(), currentId: z.string().optional() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
|
||||
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),
|
||||
});
|
||||
const available = definitions.flatMap(mapAvailableCustomWidget);
|
||||
if (!input.currentId || available.some(({ id }) => id === input.currentId)) return available;
|
||||
const legacy = await ctx.db.query.legacyCustomWidgetDefinitions.findFirst({
|
||||
where: eq(legacyCustomWidgetDefinitions.id, input.currentId),
|
||||
});
|
||||
if (!legacy) return available;
|
||||
return [...available, mapLegacyAvailableCustomWidget(legacy)];
|
||||
}),
|
||||
|
||||
optionRequest: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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 requestDefinition = definition.requests[input.requestId];
|
||||
if (requestDefinition?.kind !== "query")
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Option query not found" });
|
||||
const request = { id: input.requestId, ...requestDefinition };
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), request.permission);
|
||||
const source = definition.sources[request.source];
|
||||
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 values = resolveOptionRequestValues(request, input.params);
|
||||
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: source.baseUrl,
|
||||
targetUrl: renderRequestTarget(source.baseUrl, request, values),
|
||||
method: request.method,
|
||||
body: renderRequestBody(request, values),
|
||||
staticHeaders: request.headers,
|
||||
auth:
|
||||
request.auth === "none" || authType === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: authType,
|
||||
secrets: stored.secrets
|
||||
.filter((secret) => secret.sourceId === request.source)
|
||||
.map((secret) => ({ kind: secret.kind, value: decryptSecret(secret.encryptedValue) })),
|
||||
headerName:
|
||||
typeof source.auth === "object" && source.auth.type === "apiKeyHeader"
|
||||
? source.auth.name
|
||||
: typeof source.auth === "object" && source.auth.type === "apiKeyQuery"
|
||||
? source.auth.name
|
||||
: undefined,
|
||||
},
|
||||
networkScope: source.networkScope,
|
||||
kind: "query",
|
||||
cacheKey: `custom-widget:options:${input.definitionId}:${getCustomWidgetCacheVersion(stored)}:${request.id}:${hashRuntimeParams(values)}`,
|
||||
cacheTtlSeconds: request.cacheSeconds ?? 30,
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}),
|
||||
};
|
||||
|
||||
export function resolveOptionRequestValues(
|
||||
request: Parameters<typeof resolveCustomWidgetRequestValues>[0],
|
||||
configuration: NonNullable<Parameters<typeof resolveCustomWidgetRequestValues>[2]>,
|
||||
) {
|
||||
const references = collectCustomWidgetRequestReferences(request);
|
||||
const options: Record<string, unknown> = {};
|
||||
const params: typeof configuration = {};
|
||||
for (const name of references.options) {
|
||||
const value = configuration[name];
|
||||
if (value !== undefined) options[name] = value;
|
||||
}
|
||||
for (const name of references.params) {
|
||||
const value = configuration[name];
|
||||
if (value !== undefined) params[name] = value;
|
||||
}
|
||||
return resolveCustomWidgetRequestValues(request, options, params);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { InferSelectModel } from "drizzle-orm";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { customWidgetDefinitions, customWidgetSecrets, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
|
||||
import {
|
||||
getCustomWidgetConfirmation,
|
||||
getCustomWidgetDefaultOptions,
|
||||
getCustomWidgetSecretRequirements,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import { safeParseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget:management" });
|
||||
|
||||
type StoredDefinition = InferSelectModel<typeof customWidgetDefinitions>;
|
||||
type StoredSecret = InferSelectModel<typeof customWidgetSecrets>;
|
||||
type LegacyDefinition = InferSelectModel<typeof legacyCustomWidgetDefinitions>;
|
||||
|
||||
export function mapCustomWidgetListItem(definition: StoredDefinition & { secrets: readonly StoredSecret[] }) {
|
||||
const result = safeParseStoredCustomWidgetDefinition(definition);
|
||||
if (!result.success) {
|
||||
logger.warn("Skipped parsing invalid custom widget definition", {
|
||||
event: "custom_widget_definition_invalid",
|
||||
id: definition.id,
|
||||
issueCount: result.issues.length,
|
||||
});
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description ?? undefined,
|
||||
iconUrl: definition.iconUrl ?? undefined,
|
||||
sources: [],
|
||||
requestCount: 0,
|
||||
missingSecrets: [],
|
||||
options: {},
|
||||
updatedAt: definition.updatedAt,
|
||||
enabled: definition.enabled,
|
||||
valid: false as const,
|
||||
migrationRequired: false as const,
|
||||
validationIssues: result.issues,
|
||||
};
|
||||
}
|
||||
|
||||
const widget = result.widget;
|
||||
const configuredSecrets = new Set(definition.secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
||||
return {
|
||||
id: definition.id,
|
||||
name: widget.name,
|
||||
description: widget.description,
|
||||
iconUrl: widget.iconUrl,
|
||||
sources: Object.entries(widget.sources).map(([id, { name, baseUrl, networkScope, auth }]) => ({
|
||||
id,
|
||||
name,
|
||||
origin: new URL(baseUrl).origin,
|
||||
networkScope,
|
||||
authType: typeof auth === "string" ? auth : auth.type,
|
||||
})),
|
||||
requestCount: Object.keys(widget.requests).length,
|
||||
missingSecrets: getCustomWidgetSecretRequirements(widget.sources).filter(
|
||||
(requirement) => !configuredSecrets.has(`${requirement.sourceId}:${requirement.kind}`),
|
||||
),
|
||||
options: widget.options,
|
||||
updatedAt: definition.updatedAt,
|
||||
enabled: definition.enabled,
|
||||
valid: true as const,
|
||||
migrationRequired: false as const,
|
||||
validationIssues: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function mapLegacyCustomWidgetListItem(definition: LegacyDefinition) {
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description ?? undefined,
|
||||
iconUrl: definition.iconUrl ?? undefined,
|
||||
sources: [{ id: "default", name: "Legacy API", origin: safeOrigin(definition.url), authType: definition.authType }],
|
||||
requestCount: 1,
|
||||
missingSecrets: [],
|
||||
options: {},
|
||||
updatedAt: definition.updatedAt,
|
||||
enabled: false,
|
||||
valid: false as const,
|
||||
migrationRequired: true as const,
|
||||
validationIssues: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function mapAvailableCustomWidget(definition: StoredDefinition) {
|
||||
const result = safeParseStoredCustomWidgetDefinition(definition);
|
||||
if (!result.success) {
|
||||
logger.warn("Excluded invalid custom widget definition from board picker", {
|
||||
event: "custom_widget_definition_invalid",
|
||||
id: definition.id,
|
||||
surface: "board-picker",
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
const widget = result.widget;
|
||||
return [
|
||||
{
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
options: widget.options,
|
||||
defaultOptions: getCustomWidgetDefaultOptions(widget.options),
|
||||
template: widget.template,
|
||||
sources: Object.entries(widget.sources).map(([id, { name, networkScope, auth }]) => ({
|
||||
id,
|
||||
name,
|
||||
networkScope,
|
||||
authType: typeof auth === "string" ? auth : auth.type,
|
||||
})),
|
||||
requestCapabilities: Object.entries(widget.requests).map(
|
||||
([id, { kind, method, trigger, permission, confirmation, invalidates }]) => ({
|
||||
id,
|
||||
kind,
|
||||
method,
|
||||
trigger,
|
||||
minimumBoardPermission: permission,
|
||||
confirmation: getCustomWidgetConfirmation({ method, confirmation }),
|
||||
invalidates,
|
||||
}),
|
||||
),
|
||||
optionRequests: Object.entries(widget.requests).flatMap(([id, request]) =>
|
||||
request.kind === "query" ? [{ id }] : [],
|
||||
),
|
||||
updatedAt: definition.updatedAt,
|
||||
migrationRequired: false as const,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function mapLegacyAvailableCustomWidget(definition: LegacyDefinition) {
|
||||
return {
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
iconUrl: definition.iconUrl,
|
||||
options: {},
|
||||
defaultOptions: {},
|
||||
template: "",
|
||||
sources: [],
|
||||
requestCapabilities: [],
|
||||
optionRequests: [],
|
||||
updatedAt: definition.updatedAt,
|
||||
migrationRequired: true as const,
|
||||
};
|
||||
}
|
||||
|
||||
function safeOrigin(value: string) {
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return "Invalid legacy URL";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
|
||||
import { getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
|
||||
import { customWidgetImportSchema, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
|
||||
export const metadataProcedures = {
|
||||
schema: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Get the current Custom JSX widget JSON Schema." } })
|
||||
.query(() => getCustomWidgetJsonSchema()),
|
||||
|
||||
getAuthoringPrompt: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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",
|
||||
],
|
||||
httpResources: ["/api/custom-widgets/schema", "/api/custom-widgets/components", "/api/custom-widgets/skill"],
|
||||
})),
|
||||
|
||||
getSkill: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Get the portable Homarr Custom Widget skill." } })
|
||||
.query(() => getCustomWidgetSkill()),
|
||||
|
||||
validate: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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);
|
||||
if (!result.success) {
|
||||
return {
|
||||
valid: false as const,
|
||||
issues: result.error.issues.map((issue) => ({
|
||||
path: issue.path.map(String).join("."),
|
||||
code: issue.code,
|
||||
message: issue.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
return { valid: true as const, issues: [], widget: result.data };
|
||||
}),
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
|
||||
import type { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
|
||||
type Logger = ReturnType<typeof createLogger>;
|
||||
|
||||
export function parseDisplayConfig(raw: string, id: string, logger: Logger, context: string): Record<string, unknown> {
|
||||
try {
|
||||
return superjson.parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
logger.error(context, { id });
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Widget has corrupt display configuration" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import {
|
||||
getPreviewRequestSource,
|
||||
previewSessionRequestSchema,
|
||||
recordPreviewJournal,
|
||||
} from "./preview-procedure-helpers";
|
||||
import { executeCustomWidgetRequest, invalidateCustomWidgetResponseCache } from "./request-executor";
|
||||
import { renderRequestBody, renderRequestTarget, resolveCustomWidgetRequestValues } from "./request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "./request-limits";
|
||||
import { getPreviewSession } from "./preview-sessions";
|
||||
|
||||
export const previewActionProcedures = {
|
||||
previewAction: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: { enabled: true, description: "Simulate or run one named action in a custom widget preview session." },
|
||||
})
|
||||
.input(previewSessionRequestSchema.extend({ confirmed: z.boolean().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
|
||||
const definition = session.requests[input.requestId];
|
||||
if (definition?.kind !== "action")
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Preview action was not found" });
|
||||
const request = { id: input.requestId, ...definition };
|
||||
const resolved = getPreviewRequestSource(session, request.source);
|
||||
if (!resolved) throw new TRPCError({ code: "NOT_FOUND", message: "Preview source was not found" });
|
||||
const params = resolveCustomWidgetRequestValues(request, session.options, input.params);
|
||||
const targetUrl = renderRequestTarget(resolved.source.baseUrl, request, params);
|
||||
const body = renderRequestBody(request, params);
|
||||
if (!session.liveActions) {
|
||||
await recordPreviewJournal(session, {
|
||||
requestId: request.id,
|
||||
kind: "action",
|
||||
method: request.method,
|
||||
path: request.path,
|
||||
status: null,
|
||||
durationMs: 0,
|
||||
simulated: true,
|
||||
});
|
||||
return { ok: true, status: 0, statusText: "Simulated", data: null, simulated: true as const };
|
||||
}
|
||||
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",
|
||||
userId: ctx.session.user.id,
|
||||
itemId: `preview:${session.id}`,
|
||||
definitionId: session.definitionId ?? `preview:${session.id}`,
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: resolved.source.baseUrl,
|
||||
targetUrl,
|
||||
method: request.method,
|
||||
body,
|
||||
staticHeaders: request.headers,
|
||||
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",
|
||||
method: request.method,
|
||||
path: request.path,
|
||||
status: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
simulated: false,
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
simulated: false as const,
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import {
|
||||
customWidgetDefinitionSchema,
|
||||
customWidgetSecretsInputSchema,
|
||||
getCustomWidgetConfirmation,
|
||||
getCustomWidgetDefaultOptions,
|
||||
validateCustomWidgetOptions,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import { eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { createPreviewSession, getPreviewSession } from "./preview-sessions";
|
||||
import { hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const previewCreateInputSchema = z.object({
|
||||
definition: customWidgetDefinitionSchema,
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
definitionId: z.string().optional(),
|
||||
options: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
|
||||
const previewCreateProcedure = permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Create a short-lived preview session for one unsaved custom widget." } })
|
||||
.input(previewCreateInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const options = input.options ?? getCustomWidgetDefaultOptions(input.definition.options);
|
||||
const optionIssues = validateCustomWidgetOptions(input.definition.options, options);
|
||||
if (optionIssues.length > 0) {
|
||||
const issue = optionIssues[0];
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: issue ? `${issue.path}: ${issue.message}` : "Preview options are invalid",
|
||||
});
|
||||
}
|
||||
|
||||
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" });
|
||||
const existingDefinition = parseStoredCustomWidgetDefinition(existing);
|
||||
for (const [sourceId, existingSource] of Object.entries(existingDefinition.sources)) {
|
||||
const submittedSource = input.definition.sources[sourceId];
|
||||
const hasStoredSecrets = existing.secrets.some((secret) => secret.sourceId === sourceId);
|
||||
if (!submittedSource || !hasStoredSecrets || hasSameSecretBinding(existingSource, submittedSource)) continue;
|
||||
|
||||
const authType = typeof submittedSource.auth === "string" ? submittedSource.auth : submittedSource.auth.type;
|
||||
const missingReplacement = requiredSecretKinds(authType).some(
|
||||
(kind) => !secrets.some((secret) => secret.sourceId === sourceId && secret.kind === kind),
|
||||
);
|
||||
if (missingReplacement) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Source security settings changed; re-enter its credentials to preview this definition",
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const secret of existing.secrets) {
|
||||
const existingSource = existingDefinition.sources[secret.sourceId];
|
||||
const submittedSource = input.definition.sources[secret.sourceId];
|
||||
if (
|
||||
existingSource &&
|
||||
submittedSource &&
|
||||
hasSameSecretBinding(existingSource, submittedSource) &&
|
||||
!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[secret.sourceId];
|
||||
const authType = typeof source?.auth === "string" ? source.auth : source?.auth.type;
|
||||
const kinds =
|
||||
authType === "basic"
|
||||
? ["username", "password"]
|
||||
: source && authType && ["bearer", "apiKeyHeader", "apiKeyQuery"].includes(authType)
|
||||
? ["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,
|
||||
optionDefinitions: input.definition.options,
|
||||
options,
|
||||
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: getCustomWidgetDefaultOptions(input.definition.options),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const previewBaseProcedures = {
|
||||
previewCreate: previewCreateProcedure,
|
||||
previewGet: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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,
|
||||
optionDefinitions: session.optionDefinitions,
|
||||
options: session.options,
|
||||
requests: Object.entries(session.requests).map(([id, request]) => ({
|
||||
id,
|
||||
kind: request.kind,
|
||||
method: request.method,
|
||||
minimumBoardPermission: request.permission,
|
||||
trigger: request.trigger,
|
||||
confirmation: getCustomWidgetConfirmation(request),
|
||||
invalidates: request.invalidates,
|
||||
})),
|
||||
liveActions: session.liveActions,
|
||||
};
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { CustomJsxRequest } from "@homarr/custom-widgets/core";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { appendPreviewJournal } from "./preview-sessions";
|
||||
import { getPreviewSessionSecrets } from "./preview-sessions";
|
||||
import type { CustomWidgetPreviewSession } from "./preview-sessions";
|
||||
import { resolveCustomWidgetRequestValues } from "./request-manifest";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget-preview" });
|
||||
|
||||
export const previewSessionRequestSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1).max(64),
|
||||
params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
|
||||
});
|
||||
|
||||
export const recordPreviewJournal = async (...args: Parameters<typeof appendPreviewJournal>) => {
|
||||
try {
|
||||
await appendPreviewJournal(...args);
|
||||
} catch (error) {
|
||||
logger.warn("Failed to append custom widget preview journal", {
|
||||
sessionId: args[0].id,
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getPreviewRequestSource = (session: CustomWidgetPreviewSession, sourceId: string) => {
|
||||
const source = session.sources[sourceId];
|
||||
if (!source) return null;
|
||||
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
const auth =
|
||||
authType === "none"
|
||||
? undefined
|
||||
: {
|
||||
type: authType,
|
||||
secrets: getPreviewSessionSecrets(session, sourceId),
|
||||
headerName:
|
||||
typeof source.auth === "object" && source.auth.type === "apiKeyHeader"
|
||||
? source.auth.name
|
||||
: typeof source.auth === "object" && source.auth.type === "apiKeyQuery"
|
||||
? source.auth.name
|
||||
: undefined,
|
||||
};
|
||||
return { source, auth };
|
||||
};
|
||||
|
||||
export function resolvePreviewRequestParams(
|
||||
request: CustomJsxRequest,
|
||||
options: Record<string, unknown>,
|
||||
suppliedParams: Record<string, string | number | boolean>,
|
||||
) {
|
||||
return resolveCustomWidgetRequestValues(request, options, suppliedParams);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import {
|
||||
getPreviewRequestSource,
|
||||
previewSessionRequestSchema,
|
||||
recordPreviewJournal,
|
||||
resolvePreviewRequestParams,
|
||||
} 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";
|
||||
|
||||
export const previewQueryProcedures = {
|
||||
previewQuery: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description: "Run one named query from a short-lived custom widget preview session.",
|
||||
},
|
||||
})
|
||||
.input(previewSessionRequestSchema)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
|
||||
const definition = session.requests[input.requestId];
|
||||
if (definition?.kind !== "query")
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Preview query was not found" });
|
||||
const request = { id: input.requestId, ...definition };
|
||||
const resolved = getPreviewRequestSource(session, request.source);
|
||||
if (!resolved) throw new TRPCError({ code: "NOT_FOUND", message: "Preview source was not found" });
|
||||
const params = resolvePreviewRequestParams(request, session.options, input.params);
|
||||
const targetUrl = renderRequestTarget(resolved.source.baseUrl, request, params);
|
||||
const body = renderRequestBody(request, params);
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: "query",
|
||||
userId: ctx.session.user.id,
|
||||
itemId: `preview:${session.id}`,
|
||||
definitionId: session.definitionId ?? `preview:${session.id}`,
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const response = await executeCustomWidgetRequest({
|
||||
baseUrl: resolved.source.baseUrl,
|
||||
targetUrl,
|
||||
method: request.method,
|
||||
body,
|
||||
staticHeaders: request.headers,
|
||||
auth: request.auth === "none" ? undefined : resolved.auth,
|
||||
networkScope: resolved.source.networkScope,
|
||||
kind: "query",
|
||||
cacheKey: `custom-jsx:preview:${session.id}:${request.id}:${hashRuntimeParams(params)}`,
|
||||
cacheTtlSeconds: request.cacheSeconds,
|
||||
});
|
||||
await recordPreviewJournal(session, {
|
||||
requestId: request.id,
|
||||
kind: "query",
|
||||
method: request.method,
|
||||
path: request.path,
|
||||
status: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
simulated: false,
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}),
|
||||
|
||||
setPreviewLiveActions: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description: "Read the redacted request journal for a custom widget preview session.",
|
||||
},
|
||||
})
|
||||
.input(z.object({ sessionId: z.string().min(1) }))
|
||||
.query(async ({ ctx, input }) => getPreviewJournal(input.sessionId, ctx.session.user.id)),
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecret, encryptSecret } from "@homarr/common/server";
|
||||
import { createRedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import type { RedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import { CustomWidgetPreviewSessionService } from "@homarr/custom-widgets/server";
|
||||
import type {
|
||||
CreatePreviewSessionInput,
|
||||
CustomWidgetPreviewJournalEntry,
|
||||
CustomWidgetPreviewSession,
|
||||
PreviewSessionStore,
|
||||
} from "@homarr/custom-widgets/server";
|
||||
|
||||
import { toTrpcError } from "./domain-error";
|
||||
|
||||
const SESSION_PREFIX = "custom-widget:preview-session:";
|
||||
const JOURNAL_PREFIX = "custom-widget:preview-journal:";
|
||||
const COMPARE_AND_SWAP_SESSION_SCRIPT = `
|
||||
local current = redis.call('GET', KEYS[1])
|
||||
if not current then return 0 end
|
||||
local ok, parsed = pcall(cjson.decode, current)
|
||||
if not ok or type(parsed) ~= 'table' or tonumber(parsed.revision) ~= tonumber(ARGV[1]) then return 0 end
|
||||
redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[3])
|
||||
return 1
|
||||
`;
|
||||
|
||||
class RedisPreviewSessionStore implements PreviewSessionStore {
|
||||
public constructor(private readonly redis: RedisClient) {}
|
||||
|
||||
public async saveSession(id: string, value: unknown, ttlMs: number) {
|
||||
await this.redis.set(`${SESSION_PREFIX}${id}`, JSON.stringify(value), "PX", ttlMs);
|
||||
}
|
||||
|
||||
public getSession(id: string) {
|
||||
return this.redis.get(`${SESSION_PREFIX}${id}`);
|
||||
}
|
||||
public async compareAndSwapSession(id: string, expectedRevision: number, value: unknown, ttlMs: number) {
|
||||
return (
|
||||
Number(
|
||||
await this.redis.eval(
|
||||
COMPARE_AND_SWAP_SESSION_SCRIPT,
|
||||
1,
|
||||
`${SESSION_PREFIX}${id}`,
|
||||
expectedRevision,
|
||||
JSON.stringify(value),
|
||||
ttlMs,
|
||||
),
|
||||
) === 1
|
||||
);
|
||||
}
|
||||
public async deleteSession(id: string) {
|
||||
await this.redis.del(`${SESSION_PREFIX}${id}`);
|
||||
}
|
||||
|
||||
public async appendJournal(id: string, value: unknown, maxEntries: number, ttlMs: number) {
|
||||
const key = `${JOURNAL_PREFIX}${id}`;
|
||||
await this.redis
|
||||
.multi()
|
||||
.lpush(key, JSON.stringify(value))
|
||||
.ltrim(key, 0, maxEntries - 1)
|
||||
.pexpire(key, ttlMs)
|
||||
.exec();
|
||||
}
|
||||
|
||||
public getJournal(id: string, maxEntries: number) {
|
||||
return this.redis.lrange(`${JOURNAL_PREFIX}${id}`, 0, maxEntries - 1);
|
||||
}
|
||||
}
|
||||
|
||||
let service: CustomWidgetPreviewSessionService | undefined;
|
||||
function getService() {
|
||||
if (service) return service;
|
||||
const useLocal = process.env.CI !== undefined || process.env.NODE_ENV === "test";
|
||||
service = new CustomWidgetPreviewSessionService({
|
||||
createId,
|
||||
encrypt: encryptSecret,
|
||||
decrypt: (value) => decryptSecret(value as `${string}.${string}`),
|
||||
store: useLocal ? undefined : new RedisPreviewSessionStore(createRedisClient()),
|
||||
});
|
||||
return service;
|
||||
}
|
||||
|
||||
async function call<T>(operation: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export type { CreatePreviewSessionInput, CustomWidgetPreviewJournalEntry, CustomWidgetPreviewSession };
|
||||
|
||||
export const createPreviewSession = (input: CreatePreviewSessionInput) => call(() => getService().create(input));
|
||||
export const getPreviewSession = (id: string, userId: string) => call(() => getService().get(id, userId));
|
||||
export const setPreviewSessionLiveActions = (id: string, userId: string, enabled: boolean) =>
|
||||
call(() => getService().setLiveActions(id, userId, enabled));
|
||||
export const appendPreviewJournal = (
|
||||
session: CustomWidgetPreviewSession,
|
||||
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, sourceId: string) =>
|
||||
getService().getSecrets(session, sourceId);
|
||||
export const setPreviewSessionSecrets = (id: string, userId: string, secrets: CreatePreviewSessionInput["secrets"]) =>
|
||||
call(() => getService().setSecrets(id, userId, secrets));
|
||||
export const configurePreviewSessionSource = (
|
||||
id: string,
|
||||
userId: string,
|
||||
sourceId: string,
|
||||
source: CreatePreviewSessionInput["sources"][string],
|
||||
secrets: CreatePreviewSessionInput["secrets"],
|
||||
) => call(() => getService().configureSource(id, userId, sourceId, source, secrets));
|
||||
@@ -0,0 +1,87 @@
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import {
|
||||
assertJsonBudget as assertDomainJsonBudget,
|
||||
assertSafeStaticHeaders as assertDomainSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
executeCustomWidgetRequest as executeDomainRequest,
|
||||
invalidateCustomWidgetResponseCache as invalidateDomainResponseCache,
|
||||
MAX_REQUEST_BODY_BYTES,
|
||||
MAX_RESPONSE_BODY_BYTES,
|
||||
MAX_RESPONSE_JSON_DEPTH,
|
||||
MAX_RESPONSE_JSON_NODES,
|
||||
resolveAndValidateHost as resolveDomainHost,
|
||||
resolveSameOriginTarget as resolveDomainTarget,
|
||||
validateCustomWidgetUrl as validateDomainUrl,
|
||||
} from "@homarr/custom-widgets/server";
|
||||
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "@homarr/custom-widgets/server";
|
||||
|
||||
import { toTrpcError } from "./domain-error";
|
||||
|
||||
export type {
|
||||
CustomWidgetAuthConfig,
|
||||
CustomWidgetHttpRequest,
|
||||
CustomWidgetHttpResponse,
|
||||
} from "@homarr/custom-widgets/server";
|
||||
export {
|
||||
classifyAddress,
|
||||
MAX_REQUEST_BODY_BYTES,
|
||||
MAX_RESPONSE_BODY_BYTES,
|
||||
MAX_RESPONSE_JSON_DEPTH,
|
||||
MAX_RESPONSE_JSON_NODES,
|
||||
};
|
||||
|
||||
const logger = createLogger({ module: "custom-widget:http" });
|
||||
|
||||
export function assertJsonBudget(value: unknown): void {
|
||||
try {
|
||||
assertDomainJsonBudget(value);
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSafeStaticHeaders(headers: Record<string, string> | undefined): void {
|
||||
try {
|
||||
assertDomainSafeStaticHeaders(headers);
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export function validateCustomWidgetUrl(value: string | URL): URL {
|
||||
try {
|
||||
return validateDomainUrl(value);
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveSameOriginTarget(baseUrl: string, target?: string | URL): URL {
|
||||
try {
|
||||
return resolveDomainTarget(baseUrl, target);
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveAndValidateHost(hostname: string, scope: CustomWidgetHttpRequest["networkScope"]) {
|
||||
try {
|
||||
return await resolveDomainHost(hostname, scope);
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
|
||||
try {
|
||||
return await executeDomainRequest({
|
||||
...input,
|
||||
logError: (event) => logger.error("Custom widget request failed", event),
|
||||
});
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const invalidateCustomWidgetResponseCache = (prefixes: readonly string[]) =>
|
||||
invalidateDomainResponseCache(prefixes);
|
||||
@@ -0,0 +1,75 @@
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createRedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import type { RedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import { CustomWidgetRequestLimiter } from "@homarr/custom-widgets/server";
|
||||
import type { RequestLimitInput, RequestLimitStore } from "@homarr/custom-widgets/server";
|
||||
|
||||
import { toTrpcError } from "./domain-error";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget:limits" });
|
||||
const RATE_SCRIPT = `
|
||||
local count = redis.call('INCR', KEYS[1])
|
||||
if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
|
||||
return { count, redis.call('PTTL', KEYS[1]) }
|
||||
`;
|
||||
const ACQUIRE_SCRIPT = `
|
||||
local time = redis.call('TIME')
|
||||
local now = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
|
||||
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
|
||||
if redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[2]) then return 0 end
|
||||
redis.call('ZADD', KEYS[1], now + tonumber(ARGV[3]), ARGV[1])
|
||||
redis.call('PEXPIRE', KEYS[1], ARGV[3])
|
||||
return 1
|
||||
`;
|
||||
const RELEASE_SCRIPT = `
|
||||
return redis.call('ZREM', KEYS[1], ARGV[1])
|
||||
`;
|
||||
|
||||
class RedisRequestLimitStore implements RequestLimitStore {
|
||||
public constructor(private readonly redis: RedisClient) {}
|
||||
|
||||
public async incrementRate(key: string, windowMs: number) {
|
||||
const [count, retryAfterMs] = (await this.redis.eval(RATE_SCRIPT, 1, key, windowMs)) as [number, number];
|
||||
return { count: Number(count), retryAfterMs: Number(retryAfterMs) || windowMs };
|
||||
}
|
||||
|
||||
public async acquireConcurrency(key: string, ownerId: string, limit: number, ttlMs: number) {
|
||||
return Number(await this.redis.eval(ACQUIRE_SCRIPT, 1, key, ownerId, limit, ttlMs)) > 0;
|
||||
}
|
||||
|
||||
public async releaseConcurrency(key: string, ownerId: string) {
|
||||
await this.redis.eval(RELEASE_SCRIPT, 1, key, ownerId);
|
||||
}
|
||||
}
|
||||
|
||||
let limiter: CustomWidgetRequestLimiter | undefined;
|
||||
function getLimiter() {
|
||||
if (limiter) return limiter;
|
||||
const useLocal = process.env.CI !== undefined || process.env.NODE_ENV === "test";
|
||||
const store = useLocal ? undefined : new RedisRequestLimitStore(createRedisClient());
|
||||
limiter = new CustomWidgetRequestLimiter({
|
||||
store,
|
||||
onStoreError: (error) =>
|
||||
logger.error("Custom widget rate limiter is unavailable", {
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
}),
|
||||
});
|
||||
return limiter;
|
||||
}
|
||||
|
||||
export async function acquireCustomWidgetRequestLimit(input: RequestLimitInput): Promise<() => Promise<void>> {
|
||||
try {
|
||||
const release = await getLimiter().acquire(input);
|
||||
return async () => {
|
||||
try {
|
||||
await release();
|
||||
} catch (error) {
|
||||
logger.error("Failed to release custom widget request capacity", {
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
});
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
toTrpcError(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { CustomJsxRequest } from "@homarr/custom-widgets/core";
|
||||
import {
|
||||
hashRuntimeParams,
|
||||
renderRequestBody as renderDomainBody,
|
||||
renderRequestTarget as renderDomainTarget,
|
||||
resolveCustomWidgetRequestValues as resolveDomainValues,
|
||||
} from "@homarr/custom-widgets/server";
|
||||
import type { CustomJsxRuntimeParams } from "@homarr/custom-widgets/server";
|
||||
|
||||
import { toTrpcError } from "./domain-error";
|
||||
|
||||
export type { CustomJsxRuntimeParams } from "@homarr/custom-widgets/server";
|
||||
export { hashRuntimeParams };
|
||||
|
||||
type CustomJsxResolvedValues = ReturnType<typeof resolveDomainValues>;
|
||||
|
||||
export function resolveCustomWidgetRequestValues(
|
||||
request: CustomJsxRequest,
|
||||
options: Record<string, unknown>,
|
||||
params: CustomJsxRuntimeParams = {},
|
||||
) {
|
||||
try {
|
||||
return resolveDomainValues(request, options, params);
|
||||
} catch (error) {
|
||||
return toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export function renderRequestBody(request: CustomJsxRequest, params: CustomJsxResolvedValues) {
|
||||
try {
|
||||
return renderDomainBody(request, params);
|
||||
} catch (error) {
|
||||
return toTrpcError(error);
|
||||
}
|
||||
}
|
||||
|
||||
export function renderRequestTarget(baseUrl: string, request: CustomJsxRequest, params: CustomJsxResolvedValues) {
|
||||
try {
|
||||
return renderDomainTarget(baseUrl, request, params);
|
||||
} catch (error) {
|
||||
return toTrpcError(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { and, eq, handleTransactionsAsync } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import type { CustomWidgetCreateInput, CustomWidgetSecretKind, CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { assertSecretSources, hasSameSecretBinding } from "./secret-policy";
|
||||
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
type CustomWidgetSecretInput = CustomWidgetCreateInput["secrets"][number];
|
||||
|
||||
type ConfigureCustomWidgetSourceInput = {
|
||||
definitionId: string;
|
||||
sourceId: string;
|
||||
baseUrl: string;
|
||||
networkScope?: CustomWidgetSource["networkScope"];
|
||||
secrets: CustomWidgetCreateInput["secrets"];
|
||||
expectedSource?: CustomWidgetSource;
|
||||
};
|
||||
|
||||
type SourceConfigurationIssue = "definition-not-found" | "source-not-found" | "binding-changed";
|
||||
|
||||
class SourceConfigurationError extends Error {
|
||||
constructor(readonly issue: SourceConfigurationIssue) {
|
||||
super(`Custom widget source configuration failed: ${issue}`);
|
||||
this.name = "SourceConfigurationError";
|
||||
}
|
||||
}
|
||||
|
||||
export async function setCustomWidgetSecret(db: Database, definitionId: string, secret: CustomWidgetSecretInput) {
|
||||
const updatedAt = new Date();
|
||||
const secretRow = {
|
||||
definitionId,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt,
|
||||
};
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, definitionId),
|
||||
eq(schema.customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await transaction.insert(schema.customWidgetSecrets).values(secretRow);
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set({ updatedAt })
|
||||
.where(eq(schema.customWidgetDefinitions.id, definitionId));
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, definitionId),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
transaction.insert(customWidgetSecrets).values(secretRow).run();
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ updatedAt })
|
||||
.where(eq(customWidgetDefinitions.id, definitionId))
|
||||
.run();
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function configureCustomWidgetSource(db: Database, input: ConfigureCustomWidgetSourceInput) {
|
||||
try {
|
||||
return await persistCustomWidgetSourceConfiguration(db, input);
|
||||
} catch (error) {
|
||||
if (!(error instanceof SourceConfigurationError)) throw error;
|
||||
if (error.issue === "definition-not-found") throw new TRPCError({ code: "NOT_FOUND" });
|
||||
if (error.issue === "source-not-found") {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
|
||||
}
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Widget source authentication changed while it was being configured",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function configureCustomWidgetSourceFromRequest(
|
||||
db: Database,
|
||||
input: ConfigureCustomWidgetSourceInput & { expectedSource: CustomWidgetSource },
|
||||
) {
|
||||
try {
|
||||
return {
|
||||
status: "configured" as const,
|
||||
source: await persistCustomWidgetSourceConfiguration(db, input),
|
||||
};
|
||||
} catch (error) {
|
||||
if (!(error instanceof SourceConfigurationError)) throw error;
|
||||
return { status: error.issue } as const;
|
||||
}
|
||||
}
|
||||
|
||||
async function persistCustomWidgetSourceConfiguration(db: Database, input: ConfigureCustomWidgetSourceInput) {
|
||||
let configuredSource: CustomWidgetSource | undefined;
|
||||
const secretRows = input.secrets.map((secret) => ({
|
||||
definitionId: input.definitionId,
|
||||
sourceId: input.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
}));
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
const [stored] = await transaction
|
||||
.select()
|
||||
.from(schema.customWidgetDefinitions)
|
||||
.where(eq(schema.customWidgetDefinitions.id, input.definitionId))
|
||||
.limit(1)
|
||||
.for("update");
|
||||
const sourceUpdate = prepareSourceUpdate(stored, input);
|
||||
configuredSource = sourceUpdate.source;
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set(sourceUpdate.definitionChanges)
|
||||
.where(eq(schema.customWidgetDefinitions.id, input.definitionId));
|
||||
if (sourceUpdate.bindingChanged) {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(schema.customWidgetSecrets.sourceId, input.sourceId),
|
||||
),
|
||||
);
|
||||
}
|
||||
for (const secret of secretRows) {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(schema.customWidgetSecrets.sourceId, input.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await transaction.insert(schema.customWidgetSecrets).values(secret);
|
||||
}
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction(
|
||||
(transaction) => {
|
||||
const stored = transaction
|
||||
.select()
|
||||
.from(customWidgetDefinitions)
|
||||
.where(eq(customWidgetDefinitions.id, input.definitionId))
|
||||
.limit(1)
|
||||
.get();
|
||||
const sourceUpdate = prepareSourceUpdate(stored, input);
|
||||
configuredSource = sourceUpdate.source;
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set(sourceUpdate.definitionChanges)
|
||||
.where(eq(customWidgetDefinitions.id, input.definitionId))
|
||||
.run();
|
||||
if (sourceUpdate.bindingChanged) {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(customWidgetSecrets.sourceId, input.sourceId),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
}
|
||||
for (const secret of secretRows) {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(customWidgetSecrets.sourceId, input.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
transaction.insert(customWidgetSecrets).values(secret).run();
|
||||
}
|
||||
},
|
||||
{ behavior: "immediate" },
|
||||
);
|
||||
},
|
||||
});
|
||||
if (!configuredSource) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
return configuredSource;
|
||||
}
|
||||
|
||||
function prepareSourceUpdate(
|
||||
stored: Parameters<typeof parseStoredCustomWidgetDefinition>[0] | undefined,
|
||||
input: ConfigureCustomWidgetSourceInput,
|
||||
) {
|
||||
if (!stored) throw new SourceConfigurationError("definition-not-found");
|
||||
const definition = parseStoredCustomWidgetDefinition(stored);
|
||||
const previousSource = definition.sources[input.sourceId];
|
||||
if (!previousSource) throw new SourceConfigurationError("source-not-found");
|
||||
if (input.expectedSource && !hasSameCustomWidgetSourceAuthentication(previousSource, input.expectedSource)) {
|
||||
throw new SourceConfigurationError("binding-changed");
|
||||
}
|
||||
const source = customWidgetSourceSchema.parse({
|
||||
...previousSource,
|
||||
baseUrl: input.baseUrl,
|
||||
networkScope: input.networkScope ?? previousSource.networkScope,
|
||||
});
|
||||
assertSecretSources({ [input.sourceId]: source }, input.secrets);
|
||||
return {
|
||||
source,
|
||||
bindingChanged: !hasSameSecretBinding(previousSource, source),
|
||||
definitionChanges: {
|
||||
...serializeCustomWidgetDefinition({
|
||||
...definition,
|
||||
sources: { ...definition.sources, [input.sourceId]: source },
|
||||
}),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function clearCustomWidgetSecret(
|
||||
db: Database,
|
||||
input: {
|
||||
definitionId: string;
|
||||
sourceId: string;
|
||||
kind: CustomWidgetSecretKind;
|
||||
},
|
||||
) {
|
||||
const updatedAt = new Date();
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(schema.customWidgetSecrets.sourceId, input.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, input.kind),
|
||||
),
|
||||
);
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set({ updatedAt })
|
||||
.where(eq(schema.customWidgetDefinitions.id, input.definitionId));
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.definitionId),
|
||||
eq(customWidgetSecrets.sourceId, input.sourceId),
|
||||
eq(customWidgetSecrets.kind, input.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ updatedAt })
|
||||
.where(eq(customWidgetDefinitions.id, input.definitionId))
|
||||
.run();
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import {
|
||||
getCustomWidgetRequiredSecretKinds,
|
||||
hasSameCustomWidgetSourceAuthentication,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
|
||||
export function requiredSecretKinds(authType: string) {
|
||||
return getCustomWidgetRequiredSecretKinds(authType as Parameters<typeof getCustomWidgetRequiredSecretKinds>[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Credentials may only survive edits that preserve their complete security
|
||||
* boundary. The path is intentionally excluded: credentials are scoped to an
|
||||
* origin, while the network scope and auth destination are part of the binding.
|
||||
*/
|
||||
export function hasSameSecretBinding(left: CustomWidgetSource, right: CustomWidgetSource) {
|
||||
return (
|
||||
new URL(left.baseUrl).origin === new URL(right.baseUrl).origin &&
|
||||
left.networkScope === right.networkScope &&
|
||||
hasSameCustomWidgetSourceAuthentication(left, right)
|
||||
);
|
||||
}
|
||||
|
||||
export function assertSecretSources(
|
||||
sources: Record<string, { auth: string | { type: string } }>,
|
||||
secrets: readonly { sourceId: string; kind: "apiKey" | "username" | "password" }[],
|
||||
) {
|
||||
const invalid = secrets.find((secret) => {
|
||||
const source = sources[secret.sourceId];
|
||||
const authType = typeof source?.auth === "string" ? source.auth : source?.auth.type;
|
||||
return !source || !authType || !new Set<string>(requiredSecretKinds(authType)).has(secret.kind);
|
||||
});
|
||||
if (invalid) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Secret does not match source '${invalid.sourceId}' authentication`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import {
|
||||
customWidgetSecretInputSchema,
|
||||
customWidgetSecretsInputSchema,
|
||||
customWidgetSourceSchema,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import {
|
||||
createCustomWidgetConfigurationRequest,
|
||||
getCustomWidgetConfigurationRequestForUser,
|
||||
} from "./configuration-requests";
|
||||
import { assertSecretSources, requiredSecretKinds } from "./secret-policy";
|
||||
import { clearCustomWidgetSecret, configureCustomWidgetSource, setCustomWidgetSecret } from "./secret-persistence";
|
||||
import { getPreviewSession } from "./preview-sessions";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
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: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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 setCustomWidgetSecret(ctx.db, input.definitionId, input.secret);
|
||||
return { sourceId: input.secret.sourceId, kind: input.secret.kind, isSet: true };
|
||||
}),
|
||||
|
||||
sourceConfigure: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Configure one custom widget API source and its credentials." } })
|
||||
.input(
|
||||
z.object({
|
||||
definitionId: z.string(),
|
||||
sourceId: z.string(),
|
||||
baseUrl: z.string(),
|
||||
networkScope: z.enum(["public", "private", "loopback"]).optional(),
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
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);
|
||||
const current = definition.sources[input.sourceId];
|
||||
if (!current) throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
|
||||
const source = customWidgetSourceSchema.parse({
|
||||
...current,
|
||||
baseUrl: input.baseUrl,
|
||||
networkScope: input.networkScope ?? current.networkScope,
|
||||
});
|
||||
assertSecretSources({ [input.sourceId]: source }, input.secrets);
|
||||
const configuredSource = await configureCustomWidgetSource(ctx.db, {
|
||||
definitionId: input.definitionId,
|
||||
sourceId: input.sourceId,
|
||||
baseUrl: source.baseUrl,
|
||||
networkScope: input.networkScope,
|
||||
secrets: input.secrets,
|
||||
});
|
||||
return {
|
||||
definitionId: input.definitionId,
|
||||
sourceId: input.sourceId,
|
||||
baseUrl: configuredSource.baseUrl,
|
||||
networkScope: configuredSource.networkScope,
|
||||
configuredSecrets: input.secrets.map(({ kind }) => kind),
|
||||
};
|
||||
}),
|
||||
|
||||
configurationRequestUser: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Create or check a short-lived user source-configuration request." } })
|
||||
.input(secretRequestInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.requestId) {
|
||||
const request = await getCustomWidgetConfigurationRequestForUser(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: string | { type: string }; value: CustomWidgetSource } | 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;
|
||||
const candidate = definition.sources[input.sourceId ?? ""];
|
||||
source = candidate
|
||||
? {
|
||||
id: input.sourceId ?? "",
|
||||
name: candidate.name ?? input.sourceId ?? "",
|
||||
auth: candidate.auth,
|
||||
value: candidate,
|
||||
}
|
||||
: undefined;
|
||||
target = { type: "definition", id: input.definitionId };
|
||||
} else {
|
||||
const preview = await getPreviewSession(input.previewSessionId ?? "", ctx.session.user.id);
|
||||
widgetName = preview.name;
|
||||
const candidate = preview.sources[input.sourceId ?? ""];
|
||||
source = candidate
|
||||
? {
|
||||
id: input.sourceId ?? "",
|
||||
name: candidate.name ?? input.sourceId ?? "",
|
||||
auth: candidate.auth,
|
||||
value: candidate,
|
||||
}
|
||||
: undefined;
|
||||
target = { type: "preview", id: preview.id };
|
||||
}
|
||||
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
|
||||
const kinds = [...requiredSecretKinds(typeof source.auth === "string" ? source.auth : source.auth.type)];
|
||||
const request = await createCustomWidgetConfigurationRequest({
|
||||
userId: ctx.session.user.id,
|
||||
target,
|
||||
widgetName,
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
source: source.value,
|
||||
kinds,
|
||||
});
|
||||
return {
|
||||
requestId: request.id,
|
||||
status: request.status,
|
||||
expiresAt: request.expiresAt,
|
||||
url: new URL(`/custom-widget-configuration/${request.id}`, ctx.baseUrl ?? "http://localhost").toString(),
|
||||
};
|
||||
}),
|
||||
|
||||
secretClear: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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 clearCustomWidgetSecret(ctx.db, input);
|
||||
return { sourceId: input.sourceId, kind: input.kind, isSet: false };
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
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";
|
||||
|
||||
type StoredCustomWidgetDefinition = Pick<
|
||||
CustomWidgetDefinition,
|
||||
"name" | "description" | "iconUrl" | "sources" | "requests" | "options" | "template"
|
||||
>;
|
||||
|
||||
export interface StoredCustomWidgetIssue {
|
||||
path?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type StoredCustomWidgetParseResult =
|
||||
| { success: true; widget: HomarrCustomWidgetV2 }
|
||||
| { success: false; issues: StoredCustomWidgetIssue[] };
|
||||
|
||||
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),
|
||||
options: stringifySuperJson(definition.options),
|
||||
template: definition.template,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseStoredCustomWidgetDefinition(definition: StoredCustomWidgetDefinition): 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),
|
||||
options: parseSuperJson(definition.options),
|
||||
template: definition.template,
|
||||
});
|
||||
}
|
||||
|
||||
export function safeParseStoredCustomWidgetDefinition(
|
||||
definition: StoredCustomWidgetDefinition,
|
||||
): StoredCustomWidgetParseResult {
|
||||
try {
|
||||
return { success: true, widget: parseStoredCustomWidgetDefinition(definition) };
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
|
||||
return {
|
||||
success: false,
|
||||
issues: error.issues.slice(0, 10).map((issue: { path?: PropertyKey[]; message?: unknown }) => ({
|
||||
path: issue.path?.map(String).join("."),
|
||||
message: typeof issue.message === "string" ? issue.message : "Invalid stored widget value",
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
issues: [{ message: "Stored widget data could not be read" }],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
import { and, eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
const getTemplateRevision = (template: string) => createHash("sha256").update(template).digest("hex").slice(0, 16);
|
||||
|
||||
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",
|
||||
message: result.error.issues
|
||||
.map((issue) => `${issue.path.map(String).join(".") || "template"}: ${issue.message}`)
|
||||
.join("; "),
|
||||
});
|
||||
}
|
||||
return result.data.template;
|
||||
};
|
||||
|
||||
export const templateProcedures = {
|
||||
readTemplate: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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),
|
||||
};
|
||||
}),
|
||||
|
||||
writeTemplate: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(
|
||||
z
|
||||
.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",
|
||||
})
|
||||
.refine((data) => !(data.template !== undefined && data.templateLines !== undefined), {
|
||||
message: "Provide template or templateLines, not both",
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
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 template = validateTemplate(parseStoredCustomWidgetDefinition(existing), resolved);
|
||||
await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.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, templateLines: template.split("\n"), revision: getTemplateRevision(template) };
|
||||
}),
|
||||
|
||||
templatePatch: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Patch selected JSX template lines using an optimistic revision." } })
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
expectedRevision: z.string().length(16),
|
||||
edits: z
|
||||
.array(
|
||||
z.object({
|
||||
startLine: z.number().int().min(1),
|
||||
deleteCount: z.number().int().min(0),
|
||||
replacementLines: z.array(z.string()),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(100),
|
||||
}),
|
||||
)
|
||||
.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", message: "Custom widget definition not found" });
|
||||
const definition = parseStoredCustomWidgetDefinition(existing);
|
||||
if (getTemplateRevision(definition.template) !== input.expectedRevision) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Template changed since it was read. Read it again and retry.",
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
if (edit.startLine > lines.length + 1 || edit.startLine + edit.deleteCount - 1 > lines.length) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `Edit at line ${edit.startLine} is out of range` });
|
||||
}
|
||||
if (edit.startLine + Math.max(edit.deleteCount, 1) > nextHigherStart) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Template patch edits must not overlap" });
|
||||
}
|
||||
nextHigherStart = edit.startLine;
|
||||
lines.splice(edit.startLine - 1, edit.deleteCount, ...edit.replacementLines);
|
||||
}
|
||||
|
||||
const template = validateTemplate(definition, lines.join("\n"));
|
||||
const updateResult = (await ctx.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ template, updatedAt: new Date() })
|
||||
.where(
|
||||
and(eq(customWidgetDefinitions.id, input.id), eq(customWidgetDefinitions.template, definition.template)),
|
||||
)) as unknown;
|
||||
if (getAffectedRowCount(updateResult) === 0) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Template changed since it was read. Read it again and retry.",
|
||||
});
|
||||
}
|
||||
logger.info("Patched custom widget template", { id: input.id, editCount: input.edits.length });
|
||||
return { id: input.id, template, templateLines: lines, revision: getTemplateRevision(template) };
|
||||
}),
|
||||
};
|
||||
|
||||
function getAffectedRowCount(result: unknown): number {
|
||||
if (Array.isArray(result)) return getAffectedRowCount(result[0]);
|
||||
if (!result || typeof result !== "object") return 0;
|
||||
if ("affectedRows" in result && typeof result.affectedRows === "number") return result.affectedRows;
|
||||
if ("rowCount" in result && typeof result.rowCount === "number") return result.rowCount;
|
||||
if ("changes" in result && typeof result.changes === "number") return result.changes;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { eq, handleTransactionsAsync } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { customWidgetImportSchema, customWidgetSecretsInputSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { insertCustomWidgetDefinition } from "./definition-insert";
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { assertSecretSources, requiredSecretKinds } from "./secret-policy";
|
||||
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget" });
|
||||
|
||||
export const transferProcedures = {
|
||||
export: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(z.object({ widget: customWidgetImportSchema, secrets: customWidgetSecretsInputSchema.default([]) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
assertSecretSources(input.widget.sources, input.secrets);
|
||||
const id = await insertCustomWidgetDefinition(ctx.db, input.widget, ctx.session.user.id, input.secrets);
|
||||
logger.info("Imported custom widget definition", { id, name: input.widget.name });
|
||||
return { id };
|
||||
}),
|
||||
|
||||
migrateLegacy: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Replace one preserved legacy Custom Widget with a validated v2 definition while retaining compatible encrypted credentials.",
|
||||
},
|
||||
})
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
widget: customWidgetImportSchema,
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
assertSecretSources(input.widget.sources, input.secrets);
|
||||
const [legacy, current] = await Promise.all([
|
||||
ctx.db.query.legacyCustomWidgetDefinitions.findFirst({
|
||||
where: eq(legacyCustomWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
}),
|
||||
ctx.db.query.customWidgetDefinitions.findFirst({ where: eq(customWidgetDefinitions.id, input.id) }),
|
||||
]);
|
||||
if (!legacy) throw new TRPCError({ code: "NOT_FOUND", message: "Legacy custom widget not found" });
|
||||
if (current) throw new TRPCError({ code: "CONFLICT", message: "A v2 widget already uses this identifier" });
|
||||
|
||||
const explicitKeys = new Set(input.secrets.map(({ sourceId, kind }) => `${sourceId}:${kind}`));
|
||||
const preservableKinds = new Set<string>(requiredSecretKinds(getAuthType(input.widget.sources.default?.auth)));
|
||||
const preservedSecrets = canPreserveLegacySecrets(legacy, input.widget)
|
||||
? legacy.secrets.filter(({ kind }) => preservableKinds.has(kind) && !explicitKeys.has(`default:${kind}`))
|
||||
: [];
|
||||
const now = new Date();
|
||||
const definitionRow = {
|
||||
id: legacy.id,
|
||||
...serializeCustomWidgetDefinition(input.widget),
|
||||
enabled: legacy.enabled,
|
||||
createdAt: legacy.createdAt,
|
||||
updatedAt: now,
|
||||
creatorId: legacy.creatorId,
|
||||
};
|
||||
const secretRows = [
|
||||
...preservedSecrets.map(({ kind, encryptedValue }) => ({
|
||||
definitionId: legacy.id,
|
||||
sourceId: "default",
|
||||
kind,
|
||||
encryptedValue,
|
||||
updatedAt: now,
|
||||
})),
|
||||
...input.secrets.map(({ sourceId, kind, value }) => ({
|
||||
definitionId: legacy.id,
|
||||
sourceId,
|
||||
kind,
|
||||
encryptedValue: encryptSecret(value),
|
||||
updatedAt: now,
|
||||
})),
|
||||
];
|
||||
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction.insert(schema.customWidgetDefinitions).values(definitionRow);
|
||||
if (secretRows.length > 0) await transaction.insert(schema.customWidgetSecrets).values(secretRows);
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction.insert(customWidgetDefinitions).values(definitionRow).run();
|
||||
if (secretRows.length > 0) transaction.insert(customWidgetSecrets).values(secretRows).run();
|
||||
});
|
||||
},
|
||||
});
|
||||
logger.info("Created v2 replacement for preserved legacy custom widget definition", {
|
||||
id: legacy.id,
|
||||
preservedSecretCount: preservedSecrets.length,
|
||||
});
|
||||
return { id: legacy.id, preservedSecretCount: preservedSecrets.length };
|
||||
}),
|
||||
};
|
||||
|
||||
function canPreserveLegacySecrets(
|
||||
legacy: typeof legacyCustomWidgetDefinitions.$inferSelect,
|
||||
widget: z.infer<typeof customWidgetImportSchema>,
|
||||
) {
|
||||
const source = widget.sources.default;
|
||||
if (!source || getAuthType(source.auth) !== legacy.authType) return false;
|
||||
if (getOrigin(source.baseUrl) !== getOrigin(legacy.url)) return false;
|
||||
const headerName = typeof source.auth === "object" && "name" in source.auth ? source.auth.name : undefined;
|
||||
return headerName === (legacy.headerName ?? undefined);
|
||||
}
|
||||
|
||||
function getAuthType(auth: string | { type: string } | undefined) {
|
||||
return typeof auth === "string" ? auth : (auth?.type ?? "none");
|
||||
}
|
||||
|
||||
function getOrigin(value: string) {
|
||||
try {
|
||||
return new URL(value).origin.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import {
|
||||
applyCustomWidgetSourceSetup,
|
||||
CUSTOM_WIDGET_SCHEMA,
|
||||
customWidgetDefinitionSchema,
|
||||
customWidgetIdentifierSchema,
|
||||
customWidgetSecretsInputSchema,
|
||||
getCustomWidgetSecretRequirements,
|
||||
getCustomWidgetSourceSetups,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { WorkshopBackend } from "@homarr/workshop/backend";
|
||||
import { resolveHomarrUrlConfig, validateWorkshopWidget } from "@homarr/workshop/schema";
|
||||
|
||||
import { env } from "../../env";
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { insertCustomWidgetDefinition } from "./definition-insert";
|
||||
import { assertSecretSources } from "./secret-policy";
|
||||
|
||||
const logger = createLogger({ module: "custom-widget:workshop" });
|
||||
const workshopUrls = resolveHomarrUrlConfig({
|
||||
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
|
||||
workshopApiUrl: env.WORKSHOP_API_URL,
|
||||
});
|
||||
const workshop = new WorkshopBackend(workshopUrls.workshopApiUrl);
|
||||
|
||||
function throwWorkshopUnavailable(
|
||||
message: string,
|
||||
event: "workshop_widget_lookup_failed" | "workshop_widget_search_failed",
|
||||
): never {
|
||||
logger.error(message, {
|
||||
event,
|
||||
errorName: "WorkshopBackendError",
|
||||
});
|
||||
throw new TRPCError({
|
||||
code: "BAD_GATEWAY",
|
||||
message: "Workshop is unavailable",
|
||||
});
|
||||
}
|
||||
|
||||
async function getWorkshopWidget(submissionId: string) {
|
||||
try {
|
||||
const submission = await workshop.get(submissionId);
|
||||
if (submission.type !== "customWidget" || submission.widgetSchema !== CUSTOM_WIDGET_SCHEMA) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Workshop submission is not a compatible Custom JSX widget",
|
||||
});
|
||||
}
|
||||
const validation = validateWorkshopWidget(submission.content);
|
||||
if (!validation.success) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: validation.error });
|
||||
}
|
||||
return { submission, widget: validation.data };
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error;
|
||||
throwWorkshopUnavailable("Workshop widget lookup failed", "workshop_widget_lookup_failed");
|
||||
}
|
||||
}
|
||||
|
||||
const workshopSearchInputSchema = z.object({
|
||||
query: z.string().trim().min(1).max(200),
|
||||
sort: z.enum(["top", "newest", "recent", "discussed"]).default("top"),
|
||||
limit: z.number().int().min(1).max(20).default(10),
|
||||
});
|
||||
|
||||
const sourceOverridesSchema = z.record(
|
||||
customWidgetIdentifierSchema,
|
||||
z.strictObject({
|
||||
baseUrl: z.string(),
|
||||
networkScope: z.enum(["public", "private", "loopback"]).optional(),
|
||||
}),
|
||||
);
|
||||
|
||||
export const workshopProcedures = {
|
||||
workshopSearch: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Search Workshop for Custom JSX widgets." } })
|
||||
.input(workshopSearchInputSchema)
|
||||
.query(async ({ input }) => {
|
||||
try {
|
||||
const result = await workshop.list({
|
||||
page: 1,
|
||||
perPage: input.limit,
|
||||
search: input.query,
|
||||
sort: input.sort,
|
||||
type: "customWidget",
|
||||
includeOutdated: true,
|
||||
});
|
||||
return {
|
||||
items: result.items
|
||||
.filter((item) => item.widgetSchema === CUSTOM_WIDGET_SCHEMA)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
authorName: item.authorName,
|
||||
score: item.score,
|
||||
revision: item.revision,
|
||||
outdated: item.outdated,
|
||||
reportCount: item.reportCount,
|
||||
})),
|
||||
};
|
||||
} catch {
|
||||
throwWorkshopUnavailable("Workshop widget search failed", "workshop_widget_search_failed");
|
||||
}
|
||||
}),
|
||||
|
||||
workshopGet: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Get and validate one Workshop Custom JSX widget." } })
|
||||
.input(z.object({ submissionId: z.string().min(1) }))
|
||||
.query(async ({ input }) => {
|
||||
const { submission, widget } = await getWorkshopWidget(input.submissionId);
|
||||
return {
|
||||
submission: {
|
||||
id: submission.id,
|
||||
title: submission.title,
|
||||
description: submission.description,
|
||||
authorName: submission.authorName,
|
||||
revision: submission.revision,
|
||||
score: submission.score,
|
||||
outdated: submission.outdated,
|
||||
reportCount: submission.reportCount,
|
||||
},
|
||||
widget,
|
||||
sourceSetup: getCustomWidgetSourceSetups(widget.sources),
|
||||
hasActions: Object.values(widget.requests).some((request) => request.kind === "action"),
|
||||
methods: [...new Set(Object.values(widget.requests).map((request) => request.method))],
|
||||
permissions: [...new Set(Object.values(widget.requests).map((request) => request.permission))],
|
||||
};
|
||||
}),
|
||||
|
||||
workshopInstall: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({ mcp: { enabled: true, description: "Install one validated Workshop Custom JSX widget." } })
|
||||
.input(
|
||||
z.object({
|
||||
submissionId: z.string().min(1),
|
||||
name: z.string().trim().min(1).max(128).optional(),
|
||||
sources: sourceOverridesSchema.default({}),
|
||||
secrets: customWidgetSecretsInputSchema.default([]),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { widget } = await getWorkshopWidget(input.submissionId);
|
||||
const unknownSource = Object.keys(input.sources).find((sourceId) => !widget.sources[sourceId]);
|
||||
if (unknownSource) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `Unknown Workshop widget source '${unknownSource}'` });
|
||||
}
|
||||
const configured = customWidgetDefinitionSchema.parse({
|
||||
...widget,
|
||||
name: input.name ?? widget.name,
|
||||
sources: applyCustomWidgetSourceSetup(
|
||||
widget.sources,
|
||||
Object.fromEntries(
|
||||
Object.entries(input.sources).map(([sourceId, source]) => [
|
||||
sourceId,
|
||||
{
|
||||
baseUrl: source.baseUrl,
|
||||
networkScope: source.networkScope ?? widget.sources[sourceId]?.networkScope ?? "public",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
});
|
||||
assertSecretSources(configured.sources, input.secrets);
|
||||
const id = await insertCustomWidgetDefinition(ctx.db, configured, ctx.session.user.id, input.secrets);
|
||||
const configuredSecrets = new Set(input.secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
||||
return {
|
||||
status: "installed" as const,
|
||||
definitionId: id,
|
||||
sourceSetup: getCustomWidgetSourceSetups(configured.sources, input.secrets),
|
||||
missingCredentials: getCustomWidgetSecretRequirements(configured.sources)
|
||||
.filter((requirement) => !configuredSecrets.has(`${requirement.sourceId}:${requirement.kind}`))
|
||||
.map(({ sourceId, kind }) => ({ sourceId, kind })),
|
||||
};
|
||||
}),
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards } from "@homarr/db/schema";
|
||||
import { removeQueryCacheAsync, setQueryCacheAsync } from "@homarr/redis";
|
||||
|
||||
import { queryCacheDefaultGcTimeMs, queryCacheMaxValueBytes } from "../query-cache";
|
||||
import { createTRPCRouter, internalProcedure } from "../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "./board/board-access";
|
||||
|
||||
const queryCacheBoardInput = z.object({
|
||||
boardId: z.string().min(1),
|
||||
});
|
||||
|
||||
const queryCacheSetInput = queryCacheBoardInput.extend({
|
||||
value: z.string().max(queryCacheMaxValueBytes * 2),
|
||||
});
|
||||
|
||||
const validateBoardAccessAsync = async (ctx: Parameters<typeof throwIfActionForbiddenAsync>[0], boardId: string) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, boardId), "view");
|
||||
};
|
||||
|
||||
export const queryCacheRouter = createTRPCRouter({
|
||||
setItem: internalProcedure.input(queryCacheSetInput).mutation(async ({ ctx, input }) => {
|
||||
await validateBoardAccessAsync(ctx, input.boardId);
|
||||
const userId = ctx.session?.user.id ?? "anonymous";
|
||||
return {
|
||||
stored: await setQueryCacheAsync(
|
||||
userId,
|
||||
input.boardId,
|
||||
input.value,
|
||||
queryCacheDefaultGcTimeMs,
|
||||
queryCacheMaxValueBytes,
|
||||
),
|
||||
};
|
||||
}),
|
||||
removeItem: internalProcedure.input(queryCacheBoardInput).mutation(async ({ ctx, input }) => {
|
||||
await validateBoardAccessAsync(ctx, input.boardId);
|
||||
const userId = ctx.session?.user.id ?? "anonymous";
|
||||
await removeQueryCacheAsync(userId, input.boardId);
|
||||
}),
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { and, eq } from "@homarr/db";
|
||||
import { sectionCollapseStates, sections } from "@homarr/db/schema";
|
||||
import { emptySuperJSON } from "@homarr/definitions";
|
||||
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure } from "../../trpc";
|
||||
|
||||
@@ -16,7 +19,7 @@ export const sectionRouter = createTRPCRouter({
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const section = await ctx.db.query.sections.findFirst({
|
||||
where: and(eq(sections.id, input.sectionId), eq(sections.kind, "category")),
|
||||
where: eq(sections.id, input.sectionId),
|
||||
with: {
|
||||
collapseStates: {
|
||||
where: eq(sectionCollapseStates.userId, ctx.session.user.id),
|
||||
@@ -31,6 +34,23 @@ export const sectionRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
if (section.kind !== "container") {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Section cannot be collapsed id=${input.sectionId}`,
|
||||
});
|
||||
}
|
||||
|
||||
const rawOptions = superjson.parse(section.options ?? emptySuperJSON);
|
||||
const parsedOptions = containerSectionOptionsSchema.safeParse(rawOptions);
|
||||
|
||||
if (!parsedOptions.success || !parsedOptions.data.collapsible) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Section cannot be collapsed id=${input.sectionId}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (section.collapseStates.length === 0) {
|
||||
await ctx.db.insert(sectionCollapseStates).values({
|
||||
sectionId: section.id,
|
||||
|
||||
@@ -572,6 +572,38 @@ describe("getBoardByName should return board by name", () => {
|
||||
expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "view");
|
||||
});
|
||||
|
||||
it("returns configured container behavior", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, sectionId: rootSectionId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
const sectionId = await addContainerAsync(db, {
|
||||
boardId,
|
||||
layoutId,
|
||||
parentSectionId: rootSectionId,
|
||||
options: {
|
||||
title: "Media",
|
||||
showLabel: false,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await caller.getBoardByName({ name: "default" });
|
||||
const section = expectToBeDefined(result.sections.find((candidate) => candidate.id === sectionId));
|
||||
|
||||
expect(result.id).toBe(boardId);
|
||||
expect(section.kind).toBe("container");
|
||||
if (section.kind === "container") {
|
||||
expect(section.collapsed).toBe(false);
|
||||
expect(section.options).toMatchObject({
|
||||
title: "Media",
|
||||
showLabel: false,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw error when not present", async () => {
|
||||
// Arrange
|
||||
const db = createDb();
|
||||
@@ -828,60 +860,194 @@ describe("saveBoard should save full board", () => {
|
||||
expect(integration).toBeUndefined();
|
||||
expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "modify");
|
||||
});
|
||||
it.each([[{ kind: "empty" as const }], [{ kind: "category" as const, collapsed: false, name: "My first category" }]])(
|
||||
"should add section when present in input",
|
||||
async (partialSection) => {
|
||||
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
it("should add root section when present in input", async () => {
|
||||
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
|
||||
const { boardId, sectionId } = await createFullBoardAsync(db, "default");
|
||||
const { boardId, sectionId } = await createFullBoardAsync(db, "default");
|
||||
|
||||
const newSectionId = createId();
|
||||
await caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [
|
||||
{
|
||||
id: newSectionId,
|
||||
xOffset: 0,
|
||||
yOffset: 1,
|
||||
...partialSection,
|
||||
},
|
||||
{
|
||||
id: sectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
});
|
||||
|
||||
const board = await db.query.boards.findFirst({
|
||||
where: eq(boards.id, boardId),
|
||||
with: {
|
||||
sections: true,
|
||||
const newSectionId = createId();
|
||||
await caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [
|
||||
{
|
||||
id: newSectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 1,
|
||||
},
|
||||
});
|
||||
{
|
||||
id: sectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
});
|
||||
|
||||
const section = await db.query.sections.findFirst({
|
||||
where: eq(sections.id, newSectionId),
|
||||
});
|
||||
const board = await db.query.boards.findFirst({
|
||||
where: eq(boards.id, boardId),
|
||||
with: {
|
||||
sections: true,
|
||||
},
|
||||
});
|
||||
|
||||
const definedBoard = expectToBeDefined(board);
|
||||
expect(definedBoard.sections.length).toBe(2);
|
||||
const addedSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === newSectionId));
|
||||
expect(addedSection).toBeDefined();
|
||||
expect(addedSection.id).toBe(newSectionId);
|
||||
expect(addedSection.kind).toBe(partialSection.kind);
|
||||
expect(addedSection.yOffset).toBe(1);
|
||||
if ("name" in partialSection) {
|
||||
expect(addedSection.name).toBe(partialSection.name);
|
||||
}
|
||||
expect(section).toBeDefined();
|
||||
expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "modify");
|
||||
},
|
||||
);
|
||||
const section = await db.query.sections.findFirst({
|
||||
where: eq(sections.id, newSectionId),
|
||||
});
|
||||
|
||||
const definedBoard = expectToBeDefined(board);
|
||||
expect(definedBoard.sections.length).toBe(2);
|
||||
const addedSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === newSectionId));
|
||||
expect(addedSection).toBeDefined();
|
||||
expect(addedSection.id).toBe(newSectionId);
|
||||
expect(addedSection.kind).toBe("empty");
|
||||
expect(addedSection.yOffset).toBe(1);
|
||||
expect(addedSection.name).toBeNull();
|
||||
expect(section).toBeDefined();
|
||||
expect(spy).toHaveBeenCalledWith(expect.anything(), expect.anything(), "modify");
|
||||
});
|
||||
it("should add and update container behavior options", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId, sectionId: rootSectionId } = await createFullBoardAsync(db, "default");
|
||||
const containerId = createId();
|
||||
|
||||
await caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [
|
||||
{
|
||||
id: rootSectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
{
|
||||
id: containerId,
|
||||
kind: "container",
|
||||
collapsed: false,
|
||||
options: {
|
||||
title: "Navigation",
|
||||
customCssClasses: ["pinned"],
|
||||
borderColor: "#123456",
|
||||
showLabel: true,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
},
|
||||
layouts: [
|
||||
{
|
||||
layoutId,
|
||||
parentSectionId: rootSectionId,
|
||||
xOffset: 1,
|
||||
yOffset: 2,
|
||||
width: 3,
|
||||
height: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
});
|
||||
|
||||
await caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [
|
||||
{
|
||||
id: rootSectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
{
|
||||
id: containerId,
|
||||
kind: "container",
|
||||
collapsed: false,
|
||||
options: {
|
||||
title: "Operations",
|
||||
customCssClasses: ["dense"],
|
||||
borderColor: "#654321",
|
||||
showLabel: false,
|
||||
collapsible: false,
|
||||
showOpenAll: false,
|
||||
},
|
||||
layouts: [
|
||||
{
|
||||
layoutId,
|
||||
parentSectionId: rootSectionId,
|
||||
xOffset: 2,
|
||||
yOffset: 3,
|
||||
width: 4,
|
||||
height: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
});
|
||||
|
||||
const section = await db.query.sections.findFirst({
|
||||
where: eq(sections.id, containerId),
|
||||
});
|
||||
|
||||
expect(SuperJSON.parse(section?.options ?? "")).toEqual({
|
||||
title: "Operations",
|
||||
customCssClasses: ["dense"],
|
||||
borderColor: "#654321",
|
||||
showLabel: false,
|
||||
collapsible: false,
|
||||
showOpenAll: false,
|
||||
});
|
||||
expect(
|
||||
await db.query.sectionLayouts.findFirst({
|
||||
where: and(eq(sectionLayouts.sectionId, containerId), eq(sectionLayouts.layoutId, layoutId)),
|
||||
}),
|
||||
).toMatchObject({
|
||||
parentSectionId: rootSectionId,
|
||||
xOffset: 2,
|
||||
yOffset: 3,
|
||||
width: 4,
|
||||
height: 5,
|
||||
});
|
||||
});
|
||||
it("should add a container without layouts", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, sectionId: rootSectionId } = await createFullBoardAsync(db, "default");
|
||||
const containerId = createId();
|
||||
|
||||
await caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [
|
||||
{
|
||||
id: rootSectionId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
{
|
||||
id: containerId,
|
||||
kind: "container",
|
||||
collapsed: false,
|
||||
options: {},
|
||||
layouts: [],
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
await db.query.sections.findFirst({
|
||||
where: eq(sections.id, containerId),
|
||||
}),
|
||||
).toMatchObject({ id: containerId, kind: "container" });
|
||||
expect(
|
||||
await db.query.sectionLayouts.findMany({
|
||||
where: eq(sectionLayouts.sectionId, containerId),
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
it("should add item when present in input", async () => {
|
||||
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
|
||||
const db = createDb();
|
||||
@@ -1027,15 +1193,22 @@ describe("saveBoard should save full board", () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
|
||||
const { boardId, sectionId } = await createFullBoardAsync(db, "default");
|
||||
const newSectionId = createId();
|
||||
const { boardId, sectionId, layoutId } = await createFullBoardAsync(db, "default");
|
||||
const containerId = createId();
|
||||
await db.insert(sections).values({
|
||||
id: newSectionId,
|
||||
kind: "category",
|
||||
name: "Before",
|
||||
yOffset: 1,
|
||||
xOffset: 0,
|
||||
id: containerId,
|
||||
kind: "container",
|
||||
boardId,
|
||||
options: SuperJSON.stringify({ title: "Before" }),
|
||||
});
|
||||
await db.insert(sectionLayouts).values({
|
||||
sectionId: containerId,
|
||||
layoutId,
|
||||
parentSectionId: sectionId,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
width: 2,
|
||||
height: 2,
|
||||
});
|
||||
|
||||
await caller.saveBoard({
|
||||
@@ -1043,19 +1216,32 @@ describe("saveBoard should save full board", () => {
|
||||
sections: [
|
||||
{
|
||||
id: sectionId,
|
||||
kind: "category",
|
||||
kind: "empty",
|
||||
yOffset: 1,
|
||||
xOffset: 0,
|
||||
name: "Test",
|
||||
collapsed: true,
|
||||
},
|
||||
{
|
||||
id: newSectionId,
|
||||
kind: "category",
|
||||
name: "After",
|
||||
yOffset: 0,
|
||||
xOffset: 0,
|
||||
id: containerId,
|
||||
kind: "container",
|
||||
collapsed: false,
|
||||
options: {
|
||||
title: "After",
|
||||
customCssClasses: ["dense"],
|
||||
borderColor: "#123456",
|
||||
showLabel: false,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
},
|
||||
layouts: [
|
||||
{
|
||||
layoutId,
|
||||
parentSectionId: sectionId,
|
||||
xOffset: 1,
|
||||
yOffset: 2,
|
||||
width: 3,
|
||||
height: 4,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
@@ -1075,11 +1261,17 @@ describe("saveBoard should save full board", () => {
|
||||
expect(firstSection.kind).toBe("empty");
|
||||
expect(firstSection.yOffset).toBe(1);
|
||||
expect(firstSection.name).toBe(null);
|
||||
const secondSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === newSectionId));
|
||||
expect(secondSection.id).toBe(newSectionId);
|
||||
expect(secondSection.kind).toBe("category");
|
||||
expect(secondSection.yOffset).toBe(0);
|
||||
expect(secondSection.name).toBe("After");
|
||||
const secondSection = expectToBeDefined(definedBoard.sections.find((section) => section.id === containerId));
|
||||
expect(secondSection.id).toBe(containerId);
|
||||
expect(secondSection.kind).toBe("container");
|
||||
expect(secondSection.yOffset).toBeNull();
|
||||
expect(secondSection.name).toBeNull();
|
||||
expect(SuperJSON.parse(secondSection.options ?? "")).toMatchObject({ title: "After", collapsible: true });
|
||||
expect(
|
||||
await db.query.sectionLayouts.findFirst({
|
||||
where: and(eq(sectionLayouts.sectionId, containerId), eq(sectionLayouts.layoutId, layoutId)),
|
||||
}),
|
||||
).toMatchObject({ xOffset: 1, yOffset: 2, width: 3, height: 4, parentSectionId: sectionId });
|
||||
});
|
||||
it("should update item when present in input", async () => {
|
||||
const spy = vi.spyOn(boardAccess, "throwIfActionForbiddenAsync");
|
||||
@@ -1328,12 +1520,16 @@ const createExistingLayout = (id: string) => ({
|
||||
id,
|
||||
name: "Base",
|
||||
columnCount: 10,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 0,
|
||||
});
|
||||
const createNewLayout = (columnCount: number) => ({
|
||||
id: createId(),
|
||||
name: "New layout",
|
||||
columnCount,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 1400,
|
||||
});
|
||||
describe("saveLayouts should save layout changes", () => {
|
||||
@@ -1361,7 +1557,7 @@ describe("saveLayouts should save layout changes", () => {
|
||||
expect(definedLayout.columnCount).toBe(newLayout.columnCount);
|
||||
expect(definedLayout.breakpoint).toBe(newLayout.breakpoint);
|
||||
});
|
||||
test("should add items and dynamic sections generated from grid-algorithm when new layout is added", async () => {
|
||||
test("should add items and containers generated from grid-algorithm when new layout is added", async () => {
|
||||
// Arrange
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
@@ -1390,7 +1586,7 @@ describe("saveLayouts should save layout changes", () => {
|
||||
a: itemId,
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layout!.id, assignments.inDynamicSection);
|
||||
await expectLayoutForContainerAsync(db, assignments.inRoot.f, layout!.id, assignments.inContainer);
|
||||
});
|
||||
test("should update layout when present in input", async () => {
|
||||
// Arrange
|
||||
@@ -1443,7 +1639,81 @@ describe("saveLayouts should save layout changes", () => {
|
||||
...assignments.inRoot,
|
||||
a: itemId,
|
||||
});
|
||||
await expectLayoutForDynamicSectionAsync(db, assignments.inRoot.f, layoutId, assignments.inDynamicSection);
|
||||
await expectLayoutForContainerAsync(db, assignments.inRoot.f, layoutId, assignments.inContainer);
|
||||
});
|
||||
test("should reserve gutter columns and return gutter contents to the canvas when disabled", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId, sectionId, itemId } = await createFullBoardAsync(db, "gutters");
|
||||
|
||||
await db
|
||||
.update(itemLayouts)
|
||||
.set({
|
||||
xOffset: 9,
|
||||
})
|
||||
.where(and(eq(itemLayouts.itemId, itemId), eq(itemLayouts.layoutId, layoutId)));
|
||||
|
||||
await caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [
|
||||
{
|
||||
...createExistingLayout(layoutId),
|
||||
leftGutterColumnCount: 2,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const enabledLayout = expectToBeDefined(await db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) }));
|
||||
expect(enabledLayout.leftGutterColumnCount).toBe(2);
|
||||
const leftRoot = expectToBeDefined(
|
||||
await db.query.sections.findFirst({
|
||||
where: and(eq(sections.boardId, boardId), eq(sections.kind, "empty"), eq(sections.xOffset, -1)),
|
||||
}),
|
||||
);
|
||||
const reflowedMainItem = expectToBeDefined(
|
||||
await db.query.itemLayouts.findFirst({
|
||||
where: and(eq(itemLayouts.itemId, itemId), eq(itemLayouts.layoutId, layoutId)),
|
||||
}),
|
||||
);
|
||||
expect(reflowedMainItem.xOffset + reflowedMainItem.width).toBeLessThanOrEqual(8);
|
||||
|
||||
const gutterItemId = await addItemAsync(db, {
|
||||
boardId,
|
||||
layoutId,
|
||||
sectionId: leftRoot.id,
|
||||
});
|
||||
await caller.saveLayouts({
|
||||
id: boardId,
|
||||
layouts: [createExistingLayout(layoutId)],
|
||||
});
|
||||
|
||||
const returnedItem = expectToBeDefined(
|
||||
await db.query.itemLayouts.findFirst({
|
||||
where: and(eq(itemLayouts.itemId, gutterItemId), eq(itemLayouts.layoutId, layoutId)),
|
||||
}),
|
||||
);
|
||||
expect(returnedItem.sectionId).toBe(sectionId);
|
||||
});
|
||||
test("should create one gutter root when layouts are saved concurrently", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, layoutId } = await createFullBoardAsync(db, "concurrent-gutters");
|
||||
const input = {
|
||||
id: boardId,
|
||||
layouts: [
|
||||
{
|
||||
...createExistingLayout(layoutId),
|
||||
leftGutterColumnCount: 2,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await Promise.all([caller.saveLayouts(input), caller.saveLayouts(input)]);
|
||||
|
||||
const leftRoots = await db.query.sections.findMany({
|
||||
where: and(eq(sections.boardId, boardId), eq(sections.kind, "empty"), eq(sections.xOffset, -1)),
|
||||
});
|
||||
expect(leftRoots).toHaveLength(1);
|
||||
});
|
||||
test("should remove layout when not present in input", async () => {
|
||||
// Arrange
|
||||
@@ -1483,6 +1753,63 @@ describe("saveLayouts should save layout changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Custom Widget placement permissions", () => {
|
||||
test("rejects a direct addItem request from a non-admin board modifier", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId } = await createFullBoardAsync(db, "custom-widget-add");
|
||||
|
||||
await expect(
|
||||
caller.addItem({
|
||||
boardId,
|
||||
kind: "customApi",
|
||||
options: {
|
||||
definitionId: "definition-1",
|
||||
refreshInterval: 30,
|
||||
configuration: {},
|
||||
},
|
||||
integrationIds: [],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
|
||||
test("rejects a direct saveBoard request that adds a Custom Widget for a non-admin", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const { boardId, sectionId, layoutId } = await createFullBoardAsync(db, "custom-widget-save");
|
||||
|
||||
await expect(
|
||||
caller.saveBoard({
|
||||
id: boardId,
|
||||
sections: [{ id: sectionId, kind: "empty", yOffset: 0, xOffset: 0 }],
|
||||
items: [
|
||||
{
|
||||
id: createId(),
|
||||
kind: "customApi",
|
||||
options: {
|
||||
definitionId: "definition-1",
|
||||
refreshInterval: 30,
|
||||
configuration: {},
|
||||
},
|
||||
integrationIds: [],
|
||||
advancedOptions: { title: null, customCssClasses: [], borderColor: "" },
|
||||
layouts: [
|
||||
{
|
||||
layoutId,
|
||||
sectionId,
|
||||
height: 1,
|
||||
width: 1,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
});
|
||||
|
||||
const expectInputToBeFullBoardWithName = (
|
||||
input: RouterOutputs["board"]["getHomeBoard"],
|
||||
props: { name: string } & Awaited<ReturnType<typeof createFullBoardAsync>>,
|
||||
@@ -1601,19 +1928,21 @@ const addItemAsync = async (
|
||||
return itemId;
|
||||
};
|
||||
|
||||
const addDynamicSectionAsync = async (
|
||||
const addContainerAsync = async (
|
||||
db: Database,
|
||||
section: Partial<Pick<InferInsertModel<typeof sectionLayouts>, "xOffset" | "yOffset" | "width" | "height">> & {
|
||||
parentSectionId: string;
|
||||
boardId: string;
|
||||
layoutId: string;
|
||||
options?: Record<string, unknown>;
|
||||
},
|
||||
) => {
|
||||
const sectionId = createId();
|
||||
await db.insert(sections).values({
|
||||
id: sectionId,
|
||||
kind: "dynamic",
|
||||
kind: "container",
|
||||
boardId: section.boardId,
|
||||
options: SuperJSON.stringify(section.options ?? {}),
|
||||
});
|
||||
await db.insert(sectionLayouts).values({
|
||||
parentSectionId: section.parentSectionId,
|
||||
@@ -1655,7 +1984,7 @@ const createItemsAndSectionsAsync = async (
|
||||
const itemC = await addItemAsync(db, { boardId, layoutId, sectionId, xOffset: 6, width: 2, height: 2 });
|
||||
const itemD = await addItemAsync(db, { boardId, layoutId, sectionId, xOffset: 8, width: 2, height: 3 });
|
||||
const itemE = await addItemAsync(db, { boardId, layoutId, sectionId, yOffset: 1, height: 3 });
|
||||
const sectionF = await addDynamicSectionAsync(db, {
|
||||
const sectionF = await addContainerAsync(db, {
|
||||
yOffset: 1,
|
||||
xOffset: 1,
|
||||
width: 5,
|
||||
@@ -1664,7 +1993,7 @@ const createItemsAndSectionsAsync = async (
|
||||
boardId,
|
||||
layoutId,
|
||||
});
|
||||
const sectionG = await addDynamicSectionAsync(db, {
|
||||
const sectionG = await addContainerAsync(db, {
|
||||
yOffset: 2,
|
||||
xOffset: 6,
|
||||
width: 2,
|
||||
@@ -1695,7 +2024,7 @@ const createItemsAndSectionsAsync = async (
|
||||
f: sectionF,
|
||||
g: sectionG,
|
||||
},
|
||||
inDynamicSection: {
|
||||
inContainer: {
|
||||
h: itemH,
|
||||
i: itemI,
|
||||
j: itemJ,
|
||||
@@ -1731,7 +2060,7 @@ gg`,
|
||||
);
|
||||
};
|
||||
|
||||
const expectLayoutForDynamicSectionAsync = async (
|
||||
const expectLayoutForContainerAsync = async (
|
||||
db: Database,
|
||||
sectionId: string,
|
||||
layoutId: string,
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { stringify } from "superjson";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards, boardUserPermissions, customWidgetDefinitions, items, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import type { GroupPermissionKey } from "@homarr/definitions";
|
||||
|
||||
import { customWidgetRouter } from "../custom-widget/custom-widget-router";
|
||||
import { customApiRouter } from "../widgets/custom-api";
|
||||
|
||||
const createSession = (userId: string, permissions: GroupPermissionKey[] = []): Session => ({
|
||||
user: { id: userId, permissions, colorScheme: "light" },
|
||||
expires: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const createCustomWidgetCaller = (db: Database, session: Session | null) =>
|
||||
customWidgetRouter.createCaller({ db, deviceType: undefined, session });
|
||||
|
||||
const createCustomApiCaller = (db: Database, session: Session | null) =>
|
||||
customApiRouter.createCaller({ db, deviceType: undefined, session });
|
||||
|
||||
async function createFixtureAsync(db: Database) {
|
||||
const ownerId = createId();
|
||||
const viewerId = createId();
|
||||
const modifierId = createId();
|
||||
const unrelatedId = createId();
|
||||
const adminId = createId();
|
||||
const boardId = createId();
|
||||
const itemId = createId();
|
||||
const definitionId = createId();
|
||||
|
||||
await db.insert(users).values(
|
||||
[ownerId, viewerId, modifierId, unrelatedId, adminId].map((id) => ({
|
||||
id,
|
||||
name: id,
|
||||
})),
|
||||
);
|
||||
await db.insert(boards).values({ id: boardId, name: `board-${boardId}`, creatorId: ownerId, isPublic: false });
|
||||
await db.insert(boardUserPermissions).values([
|
||||
{ boardId, userId: viewerId, permission: "view" },
|
||||
{ boardId, userId: modifierId, permission: "modify" },
|
||||
]);
|
||||
await db.insert(customWidgetDefinitions).values({
|
||||
id: definitionId,
|
||||
name: "Restart service",
|
||||
description: "Restarts a service",
|
||||
url: "https://api.example.com/restart",
|
||||
method: "POST",
|
||||
displayType: "actionButton",
|
||||
displayConfig: stringify({
|
||||
type: "actionButton",
|
||||
buttonLabel: "Restart",
|
||||
confirmText: "Continue?",
|
||||
}),
|
||||
creatorId: adminId,
|
||||
});
|
||||
await db.insert(items).values({
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind: "customApi",
|
||||
options: stringify({ definitionId, refreshInterval: 30 }),
|
||||
});
|
||||
|
||||
return { ownerId, viewerId, modifierId, unrelatedId, adminId, boardId, itemId, definitionId };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("custom widget definition authorization", () => {
|
||||
it("restricts the full definition list to administrators", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
|
||||
await expect(createCustomWidgetCaller(db, null).all()).rejects.toMatchObject({ code: "UNAUTHORIZED" });
|
||||
for (const userId of [fixture.ownerId, fixture.viewerId, fixture.modifierId, fixture.unrelatedId]) {
|
||||
await expect(createCustomWidgetCaller(db, createSession(userId)).all()).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
|
||||
await expect(createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).all()).resolves.toEqual([
|
||||
expect.objectContaining({ id: fixture.definitionId, url: "https://api.example.com/restart" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns only safe definition summaries to board modifiers", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
|
||||
const result = await createCustomWidgetCaller(db, createSession(fixture.modifierId)).available({
|
||||
boardId: fixture.boardId,
|
||||
});
|
||||
expect(result).toEqual([
|
||||
{
|
||||
id: fixture.definitionId,
|
||||
name: "Restart service",
|
||||
description: "Restarts a service",
|
||||
iconUrl: null,
|
||||
displayType: "actionButton",
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
expect(JSON.stringify(result)).not.toContain("api.example.com");
|
||||
|
||||
for (const userId of [fixture.viewerId, fixture.unrelatedId]) {
|
||||
await expect(
|
||||
createCustomWidgetCaller(db, createSession(userId)).available({ boardId: fixture.boardId }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("custom widget action authorization", () => {
|
||||
it("requires an administrator even for users who can view or modify the board", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const input = {
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
};
|
||||
|
||||
await expect(createCustomWidgetCaller(db, null).execute(input)).rejects.toMatchObject({ code: "UNAUTHORIZED" });
|
||||
for (const userId of [fixture.ownerId, fixture.viewerId, fixture.modifierId, fixture.unrelatedId]) {
|
||||
await expect(createCustomWidgetCaller(db, createSession(userId)).execute(input)).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("executes for an administrator only when board, item, and definition are bound", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const caller = createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"]));
|
||||
|
||||
await expect(
|
||||
caller.execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
}),
|
||||
).resolves.toEqual({ success: true, responseInfo: { status: 204 } });
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://api.example.com/restart",
|
||||
expect.objectContaining({ method: "POST", redirect: "error", signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["board", "item", "definition"] as const)("rejects a mismatched %s binding", async (mismatch) => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const input = {
|
||||
boardId: mismatch === "board" ? createId() : fixture.boardId,
|
||||
itemId: mismatch === "item" ? createId() : fixture.itemId,
|
||||
definitionId: mismatch === "definition" ? createId() : fixture.definitionId,
|
||||
};
|
||||
|
||||
await expect(
|
||||
createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute(input),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects disabled definitions before sending a request", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ enabled: false })
|
||||
.where(eq(customWidgetDefinitions.id, fixture.definitionId));
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
await expect(
|
||||
createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("custom API outbound request hardening", () => {
|
||||
it("rejects credential-bearing action URLs without exposing the credential", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ url: "https://operator:super-secret@private.example.com/restart" })
|
||||
.where(eq(customWidgetDefinitions.id, fixture.definitionId));
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
});
|
||||
expect(result).toEqual({ success: false, errorCode: "REQUEST_FAILED", responseInfo: null });
|
||||
expect(JSON.stringify(result)).not.toMatch(/super-secret|private\.example\.com/);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects redirects and redacts fetch errors", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockRejectedValue(
|
||||
new TypeError("Redirect to http://token:secret@internal.example.local/admin?apiKey=top-secret was rejected"),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://api.example.com/restart",
|
||||
expect.objectContaining({ redirect: "error" }),
|
||||
);
|
||||
expect(result).toEqual({ success: false, errorCode: "REQUEST_FAILED", responseInfo: null });
|
||||
expect(JSON.stringify(result)).not.toMatch(/top-secret|internal\.example\.local|apiKey/);
|
||||
});
|
||||
|
||||
it("aborts timed-out action requests and returns a stable failure", async () => {
|
||||
vi.useFakeTimers();
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const started = Promise.withResolvers<void>();
|
||||
const fetchMock = vi.fn((_url: string, init: RequestInit) => {
|
||||
started.resolve();
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener("abort", () => {
|
||||
reject(new Error("Timed out calling http://internal.example.local?secret=timeout-secret"));
|
||||
});
|
||||
});
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const request = createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
});
|
||||
await started.promise;
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
|
||||
const result = await request;
|
||||
expect(result).toEqual({ success: false, errorCode: "REQUEST_FAILED", responseInfo: null });
|
||||
expect(JSON.stringify(result)).not.toMatch(/timeout-secret|internal\.example\.local/);
|
||||
});
|
||||
|
||||
it("bounds action responses before reporting success", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("x".repeat(2 * 1024 * 1024 + 1))));
|
||||
|
||||
await expect(
|
||||
createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"])).execute({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
}),
|
||||
).resolves.toEqual({ success: false, errorCode: "REQUEST_FAILED", responseInfo: null });
|
||||
});
|
||||
|
||||
it("binds data requests to a viewable item and never exposes backend error text", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({
|
||||
displayType: "singleValue",
|
||||
method: "GET",
|
||||
displayConfig: stringify({ type: "singleValue", jsonPath: "$.value" }),
|
||||
})
|
||||
.where(eq(customWidgetDefinitions.id, fixture.definitionId));
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockRejectedValue(new Error("Backend http://private.example.local/path?token=super-secret\nstack trace")),
|
||||
);
|
||||
|
||||
const input = {
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
};
|
||||
const error = await createCustomApiCaller(db, createSession(fixture.viewerId))
|
||||
.getData(input)
|
||||
.catch((caught: unknown) => caught);
|
||||
expect(error).toMatchObject({ code: "INTERNAL_SERVER_ERROR", message: "Custom API request failed" });
|
||||
expect(JSON.stringify(error)).not.toMatch(/super-secret|private\.example\.local|stack trace/);
|
||||
|
||||
await expect(createCustomApiCaller(db, createSession(fixture.unrelatedId)).getData(input)).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
await expect(
|
||||
createCustomApiCaller(db, createSession(fixture.viewerId)).getData({ ...input, definitionId: createId() }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("bounds and disposes non-success data responses", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({
|
||||
displayType: "singleValue",
|
||||
method: "GET",
|
||||
displayConfig: stringify({ type: "singleValue", jsonPath: "$.value" }),
|
||||
})
|
||||
.where(eq(customWidgetDefinitions.id, fixture.definitionId));
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("x".repeat(2 * 1024 * 1024 + 1), { status: 502 })));
|
||||
|
||||
const error = await createCustomApiCaller(db, createSession(fixture.viewerId))
|
||||
.getData({
|
||||
boardId: fixture.boardId,
|
||||
itemId: fixture.itemId,
|
||||
definitionId: fixture.definitionId,
|
||||
})
|
||||
.catch((caught: unknown) => caught);
|
||||
|
||||
expect(error).toMatchObject({ code: "INTERNAL_SERVER_ERROR", message: "Custom API request failed" });
|
||||
expect(JSON.stringify(error)).not.toContain("x".repeat(100));
|
||||
});
|
||||
|
||||
it("redacts unsafe preview failures and rejects redirects", async () => {
|
||||
const db = createDb();
|
||||
const fixture = await createFixtureAsync(db);
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error("redirected to http://private.local?secret=value"));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const caller = createCustomWidgetCaller(db, createSession(fixture.adminId, ["admin"]));
|
||||
|
||||
const result = await caller.preview({
|
||||
url: "https://api.example.com/data",
|
||||
method: "GET",
|
||||
authType: "none",
|
||||
displayType: "singleValue",
|
||||
displayConfig: { type: "singleValue", jsonPath: "$.value", label: "Value", unit: "" },
|
||||
secrets: [],
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://api.example.com/data",
|
||||
expect.objectContaining({ redirect: "error" }),
|
||||
);
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: "Custom API preview failed",
|
||||
responseInfo: null,
|
||||
rawResponse: null,
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toMatch(/private\.local|secret=value/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
claimCustomWidgetConfigurationRequest,
|
||||
completeCustomWidgetConfigurationRequest,
|
||||
createCustomWidgetConfigurationRequest,
|
||||
getCustomWidgetConfigurationRequestForUser,
|
||||
releaseCustomWidgetConfigurationRequest,
|
||||
} from "../../custom-widget/configuration-requests";
|
||||
|
||||
describe("custom widget source configuration requests", () => {
|
||||
it("is user-scoped, one-time, and reports completion without returning configuration", async () => {
|
||||
const request = await createCustomWidgetConfigurationRequest({
|
||||
userId: "user-1",
|
||||
target: { type: "preview", id: "preview-1" },
|
||||
widgetName: "Printer",
|
||||
sourceId: "default",
|
||||
sourceName: "Printer API",
|
||||
source: { baseUrl: "http://printer.local", networkScope: "private", auth: "bearer" },
|
||||
kinds: ["apiKey"],
|
||||
});
|
||||
|
||||
expect(await getCustomWidgetConfigurationRequestForUser(request.id, "user-2")).toBeNull();
|
||||
expect(await claimCustomWidgetConfigurationRequest(request.id)).toMatchObject({ status: "pending" });
|
||||
expect(await claimCustomWidgetConfigurationRequest(request.id)).toBeNull();
|
||||
await releaseCustomWidgetConfigurationRequest(request.id);
|
||||
expect(await claimCustomWidgetConfigurationRequest(request.id)).not.toBeNull();
|
||||
await completeCustomWidgetConfigurationRequest(request.id);
|
||||
expect(await getCustomWidgetConfigurationRequestForUser(request.id, "user-1")).toMatchObject({
|
||||
status: "completed",
|
||||
});
|
||||
expect(await claimCustomWidgetConfigurationRequest(request.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,551 @@
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { eq, sql } from "@homarr/db";
|
||||
import {
|
||||
customWidgetDefinitions,
|
||||
customWidgetSecrets,
|
||||
legacyCustomWidgetDefinitions,
|
||||
legacyCustomWidgetSecrets,
|
||||
users,
|
||||
} from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { customWidgetRouter } from "../../custom-widget/custom-widget-router";
|
||||
import { getCustomWidgetConfigurationRequestForUser } from "../../custom-widget/configuration-requests";
|
||||
import { configureCustomWidgetSourceFromRequest } from "../../custom-widget/secret-persistence";
|
||||
import { serializeCustomWidgetDefinition } from "../../custom-widget/stored-definition";
|
||||
|
||||
const userId = createId();
|
||||
const session = {
|
||||
user: {
|
||||
id: userId,
|
||||
permissions: ["admin"],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date().toISOString(),
|
||||
} satisfies Session;
|
||||
const nonAdminSession = {
|
||||
...session,
|
||||
user: { ...session.user, permissions: ["board-modify-all"] },
|
||||
} satisfies Session;
|
||||
|
||||
const jellyfin = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-jellyfin")?.widget;
|
||||
if (!jellyfin) throw new Error("Jellyfin bundled widget is missing");
|
||||
const jellyfinDefaultSource = jellyfin.sources.default;
|
||||
if (!jellyfinDefaultSource) throw new Error("Jellyfin default source is missing");
|
||||
|
||||
function createCaller(db: ReturnType<typeof createDb>) {
|
||||
return customWidgetRouter.createCaller({ db, deviceType: undefined, session });
|
||||
}
|
||||
|
||||
function createNonAdminCaller(db: ReturnType<typeof createDb>) {
|
||||
return customWidgetRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: nonAdminSession,
|
||||
});
|
||||
}
|
||||
|
||||
async function prepareDatabase() {
|
||||
const db = createDb();
|
||||
await db.insert(users).values({ id: userId });
|
||||
return db;
|
||||
}
|
||||
|
||||
function rejectSecretInserts(db: ReturnType<typeof createDb>) {
|
||||
db.run(
|
||||
sql.raw(`CREATE TRIGGER reject_custom_widget_v2_secret_insert
|
||||
BEFORE INSERT ON custom_widget_v2_secret
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced secret insert failure');
|
||||
END`),
|
||||
);
|
||||
}
|
||||
|
||||
function rejectDefinitionUpdates(db: ReturnType<typeof createDb>) {
|
||||
db.run(
|
||||
sql.raw(`CREATE TRIGGER reject_custom_widget_v2_definition_update
|
||||
BEFORE UPDATE ON custom_widget_v2_definition
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced definition update failure');
|
||||
END`),
|
||||
);
|
||||
}
|
||||
|
||||
async function insertLegacyJellyfin(db: ReturnType<typeof createDb>) {
|
||||
const id = "legacy-jellyfin";
|
||||
const encryptedValue = "preserved.secret" as `${string}.${string}`;
|
||||
await db.insert(legacyCustomWidgetDefinitions).values({
|
||||
id,
|
||||
name: "Legacy Jellyfin",
|
||||
url: "http://jellyfin.local/Items/Counts",
|
||||
authType: "apiKeyHeader",
|
||||
headerName: "X-Emby-Token",
|
||||
method: "GET",
|
||||
displayType: "singleValue",
|
||||
enabled: false,
|
||||
creatorId: userId,
|
||||
});
|
||||
await db.insert(legacyCustomWidgetSecrets).values({
|
||||
definitionId: id,
|
||||
kind: "apiKey",
|
||||
encryptedValue,
|
||||
updatedAt: new Date(0),
|
||||
});
|
||||
return { id, encryptedValue };
|
||||
}
|
||||
|
||||
const secret = { sourceId: "default", kind: "apiKey" as const, value: "test-secret" };
|
||||
|
||||
describe("custom widget definition persistence", () => {
|
||||
test("atomically creates a v2 replacement while preserving the legacy widget and its stable ID", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const legacy = await insertLegacyJellyfin(db);
|
||||
|
||||
await createCaller(db).migrateLegacy({ id: legacy.id, widget: jellyfin, secrets: [] });
|
||||
|
||||
expect(await db.query.legacyCustomWidgetDefinitions.findFirst()).toMatchObject({
|
||||
id: legacy.id,
|
||||
name: "Legacy Jellyfin",
|
||||
enabled: false,
|
||||
});
|
||||
expect(await db.query.legacyCustomWidgetSecrets.findFirst()).toMatchObject({
|
||||
definitionId: legacy.id,
|
||||
encryptedValue: legacy.encryptedValue,
|
||||
});
|
||||
expect(await db.query.customWidgetDefinitions.findFirst()).toMatchObject({
|
||||
id: legacy.id,
|
||||
enabled: false,
|
||||
creatorId: userId,
|
||||
});
|
||||
expect(await db.query.customWidgetSecrets.findFirst()).toMatchObject({
|
||||
definitionId: legacy.id,
|
||||
sourceId: "default",
|
||||
kind: "apiKey",
|
||||
encryptedValue: legacy.encryptedValue,
|
||||
});
|
||||
|
||||
const migratedList = await createCaller(db).list();
|
||||
expect(migratedList).toHaveLength(1);
|
||||
expect(migratedList[0]).toMatchObject({ id: legacy.id, migrationRequired: false });
|
||||
|
||||
await createCaller(db).delete({ id: legacy.id });
|
||||
|
||||
const fallbackList = await createCaller(db).list();
|
||||
expect(fallbackList).toHaveLength(1);
|
||||
expect(fallbackList[0]).toMatchObject({ id: legacy.id, migrationRequired: true });
|
||||
expect(await db.query.legacyCustomWidgetSecrets.findFirst()).toMatchObject({
|
||||
definitionId: legacy.id,
|
||||
encryptedValue: legacy.encryptedValue,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the legacy widget recoverable when confirmed replacement fails", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const legacy = await insertLegacyJellyfin(db);
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(createCaller(db).migrateLegacy({ id: legacy.id, widget: jellyfin, secrets: [] })).rejects.toThrow(
|
||||
"forced secret insert failure",
|
||||
);
|
||||
|
||||
expect(await db.query.legacyCustomWidgetDefinitions.findFirst()).toMatchObject({ id: legacy.id });
|
||||
expect(await db.query.legacyCustomWidgetSecrets.findFirst()).toMatchObject({
|
||||
definitionId: legacy.id,
|
||||
encryptedValue: legacy.encryptedValue,
|
||||
});
|
||||
expect(await db.query.customWidgetDefinitions.findMany()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("rolls back create when its secret cannot be stored", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(caller.create({ ...jellyfin, secrets: [secret] })).rejects.toThrow("forced secret insert failure");
|
||||
|
||||
expect(await db.query.customWidgetDefinitions.findMany()).toHaveLength(0);
|
||||
expect(await db.query.customWidgetSecrets.findMany()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("rolls back import when its secret cannot be stored", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(caller.import({ widget: jellyfin, secrets: [secret] })).rejects.toThrow(
|
||||
"forced secret insert failure",
|
||||
);
|
||||
|
||||
expect(await db.query.customWidgetDefinitions.findMany()).toHaveLength(0);
|
||||
expect(await db.query.customWidgetSecrets.findMany()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("refuses to export a stored definition containing embedded credentials", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const definition = customWidgetDefinitionSchema.parse(jellyfin);
|
||||
const counts = definition.requests.counts;
|
||||
if (!counts) throw new Error("Jellyfin counts request is missing");
|
||||
const id = createId();
|
||||
await db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
...serializeCustomWidgetDefinition({
|
||||
...definition,
|
||||
requests: {
|
||||
...definition.requests,
|
||||
counts: {
|
||||
...counts,
|
||||
headers: { ...counts.headers, "X-Auth": "Bearer sk-secret-123456" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
creatorId: userId,
|
||||
});
|
||||
|
||||
await expect(createCaller(db).export({ id })).rejects.toThrow("Credentials must use source authentication");
|
||||
});
|
||||
|
||||
test("rolls back definition and secret changes when a replacement secret cannot be stored", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [secret] });
|
||||
const originalDefinition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
});
|
||||
const originalSecret = await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
});
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(
|
||||
caller.update({
|
||||
id: created.id,
|
||||
name: "Changed Jellyfin Library",
|
||||
secrets: [{ ...secret, value: "replacement-secret" }],
|
||||
}),
|
||||
).rejects.toThrow("forced secret insert failure");
|
||||
|
||||
const storedDefinition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
});
|
||||
const storedSecret = await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
});
|
||||
expect(storedDefinition?.name).toBe(originalDefinition?.name);
|
||||
expect(storedDefinition?.updatedAt).toEqual(originalDefinition?.updatedAt);
|
||||
expect(storedSecret).toEqual(originalSecret);
|
||||
});
|
||||
|
||||
test("keeps the existing secret when setting its replacement fails", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [secret] });
|
||||
const originalDefinition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
});
|
||||
const originalSecret = await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
});
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(
|
||||
caller.secretSet({
|
||||
definitionId: created.id,
|
||||
secret: { ...secret, value: "replacement-secret" },
|
||||
}),
|
||||
).rejects.toThrow("forced secret insert failure");
|
||||
|
||||
expect(
|
||||
await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
}),
|
||||
).toEqual(originalDefinition);
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toEqual(originalSecret);
|
||||
});
|
||||
|
||||
test("keeps the existing secret when clearing it cannot update the definition revision", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [secret] });
|
||||
const originalDefinition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
});
|
||||
const originalSecret = await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
});
|
||||
rejectDefinitionUpdates(db);
|
||||
|
||||
await expect(
|
||||
caller.secretClear({
|
||||
definitionId: created.id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
}),
|
||||
).rejects.toThrow("forced definition update failure");
|
||||
|
||||
expect(
|
||||
await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, created.id),
|
||||
}),
|
||||
).toEqual(originalDefinition);
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findFirst({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toEqual(originalSecret);
|
||||
});
|
||||
|
||||
test("configures a source URL and credential together", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [] });
|
||||
|
||||
await caller.sourceConfigure({
|
||||
definitionId: created.id,
|
||||
sourceId: "default",
|
||||
baseUrl: "http://jellyfin.local:8096",
|
||||
networkScope: "private",
|
||||
secrets: [secret],
|
||||
});
|
||||
|
||||
const definition = await caller.get({ id: created.id });
|
||||
expect(definition.sources.default?.baseUrl).toBe("http://jellyfin.local:8096");
|
||||
expect(definition.secrets).toMatchObject([{ sourceId: "default", kind: "apiKey", hasValue: true }]);
|
||||
});
|
||||
|
||||
test("rolls back a source URL when its credential cannot be stored", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [] });
|
||||
const before = await caller.get({ id: created.id });
|
||||
rejectSecretInserts(db);
|
||||
|
||||
await expect(
|
||||
caller.sourceConfigure({
|
||||
definitionId: created.id,
|
||||
sourceId: "default",
|
||||
baseUrl: "http://jellyfin.local:8096",
|
||||
networkScope: "private",
|
||||
secrets: [secret],
|
||||
}),
|
||||
).rejects.toThrow("forced secret insert failure");
|
||||
|
||||
expect((await caller.get({ id: created.id })).sources.default?.baseUrl).toBe(before.sources.default?.baseUrl);
|
||||
});
|
||||
|
||||
test("uses the preview widget name in a user configuration request", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const preview = await caller.previewCreate({
|
||||
definition: { ...jellyfin, name: "Living room Jellyfin" },
|
||||
secrets: [],
|
||||
});
|
||||
|
||||
const request = await caller.configurationRequestUser({
|
||||
previewSessionId: preview.previewSession.id,
|
||||
sourceId: "default",
|
||||
});
|
||||
|
||||
expect(await getCustomWidgetConfigurationRequestForUser(request.requestId, userId)).toMatchObject({
|
||||
widgetName: "Living room Jellyfin",
|
||||
});
|
||||
});
|
||||
|
||||
test("does not inherit a stored credential after a preview source binding changes", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [secret] });
|
||||
const changedDefinition = {
|
||||
...jellyfin,
|
||||
sources: {
|
||||
...jellyfin.sources,
|
||||
default: { ...jellyfinDefaultSource, baseUrl: "https://attacker.example" },
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
createNonAdminCaller(db).previewCreate({
|
||||
definitionId: created.id,
|
||||
definition: changedDefinition,
|
||||
secrets: [],
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
await expect(
|
||||
caller.previewCreate({ definitionId: created.id, definition: changedDefinition, secrets: [secret] }),
|
||||
).resolves.toMatchObject({ success: true });
|
||||
});
|
||||
|
||||
test("clears persisted credentials when an admin source edit changes its binding", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const created = await createCaller(db).create({ ...jellyfin, secrets: [secret] });
|
||||
|
||||
await createCaller(db).sourceConfigure({
|
||||
definitionId: created.id,
|
||||
sourceId: "default",
|
||||
baseUrl: "https://other.example/api",
|
||||
networkScope: "public",
|
||||
secrets: [],
|
||||
});
|
||||
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findMany({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("uses the persisted source binding from inside the configuration transaction", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const created = await createCaller(db).create({ ...jellyfin, secrets: [secret] });
|
||||
const definition = customWidgetDefinitionSchema.parse(jellyfin);
|
||||
const defaultSource = definition.sources.default;
|
||||
if (!defaultSource) throw new Error("Jellyfin default source is missing");
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set(
|
||||
serializeCustomWidgetDefinition({
|
||||
...definition,
|
||||
name: "Concurrent definition edit",
|
||||
sources: {
|
||||
...definition.sources,
|
||||
default: { ...defaultSource, baseUrl: "https://changed.example/api" },
|
||||
},
|
||||
}),
|
||||
)
|
||||
.where(eq(customWidgetDefinitions.id, created.id));
|
||||
|
||||
await expect(
|
||||
configureCustomWidgetSourceFromRequest(db, {
|
||||
definitionId: created.id,
|
||||
sourceId: "default",
|
||||
baseUrl: defaultSource.baseUrl,
|
||||
networkScope: defaultSource.networkScope,
|
||||
secrets: [],
|
||||
expectedSource: defaultSource,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
status: "configured",
|
||||
source: { baseUrl: defaultSource.baseUrl },
|
||||
});
|
||||
|
||||
expect(await createCaller(db).get({ id: created.id })).toMatchObject({
|
||||
name: "Concurrent definition edit",
|
||||
sources: { default: { baseUrl: defaultSource.baseUrl } },
|
||||
});
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findMany({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("rejects stale setup-link credentials after a concurrent authentication binding change", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const created = await createCaller(db).create({ ...jellyfin, secrets: [] });
|
||||
const definition = customWidgetDefinitionSchema.parse(jellyfin);
|
||||
const expectedSource = definition.sources.default;
|
||||
if (!expectedSource || typeof expectedSource.auth === "string") {
|
||||
throw new Error("Jellyfin default source must use header authentication");
|
||||
}
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set(
|
||||
serializeCustomWidgetDefinition({
|
||||
...definition,
|
||||
name: "Concurrent definition edit",
|
||||
sources: {
|
||||
...definition.sources,
|
||||
default: {
|
||||
...expectedSource,
|
||||
auth: { ...expectedSource.auth, name: "X-Replaced-Credential" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
.where(eq(customWidgetDefinitions.id, created.id));
|
||||
|
||||
await expect(
|
||||
configureCustomWidgetSourceFromRequest(db, {
|
||||
definitionId: created.id,
|
||||
sourceId: "default",
|
||||
baseUrl: "https://configured.example/api",
|
||||
networkScope: "public",
|
||||
secrets: [secret],
|
||||
expectedSource,
|
||||
}),
|
||||
).resolves.toEqual({ status: "binding-changed" });
|
||||
|
||||
expect(await createCaller(db).get({ id: created.id })).toMatchObject({
|
||||
name: "Concurrent definition edit",
|
||||
sources: {
|
||||
default: {
|
||||
baseUrl: expectedSource.baseUrl,
|
||||
auth: { name: "X-Replaced-Credential" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findMany({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("clears persisted credentials when a general definition update changes its binding", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, secrets: [secret] });
|
||||
|
||||
await createCaller(db).update({
|
||||
id: created.id,
|
||||
sources: {
|
||||
...jellyfin.sources,
|
||||
default: { ...jellyfinDefaultSource, baseUrl: "https://other.example/api" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await db.query.customWidgetSecrets.findMany({
|
||||
where: eq(customWidgetSecrets.definitionId, created.id),
|
||||
}),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("requires an administrator to create a stored-definition setup link", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const created = await createCaller(db).create({ ...jellyfin, secrets: [] });
|
||||
|
||||
await expect(
|
||||
createNonAdminCaller(db).configurationRequestUser({ definitionId: created.id, sourceId: "default" }),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
|
||||
test("allows only one concurrent template patch for a revision", async () => {
|
||||
const db = await prepareDatabase();
|
||||
const caller = createCaller(db);
|
||||
const created = await caller.create({ ...jellyfin, template: "<Text>Original</Text>", secrets: [] });
|
||||
const read = await caller.readTemplate({ id: created.id });
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
caller.templatePatch({
|
||||
id: created.id,
|
||||
expectedRevision: read.revision,
|
||||
edits: [{ startLine: 1, deleteCount: 1, replacementLines: ["<Text>First</Text>"] }],
|
||||
}),
|
||||
caller.templatePatch({
|
||||
id: created.id,
|
||||
expectedRevision: read.revision,
|
||||
edits: [{ startLine: 1, deleteCount: 1, replacementLines: ["<Text>Second</Text>"] }],
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(results.filter(({ status }) => status === "fulfilled")).toHaveLength(1);
|
||||
expect(results.filter(({ status }) => status === "rejected")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
|
||||
import { buildLegacyCustomWidgetMigrationPrompt } from "../../custom-widget/legacy-migration";
|
||||
|
||||
describe("legacy custom widget migration prompt", () => {
|
||||
test("describes the legacy widget without exposing URL or body credentials", () => {
|
||||
const prompt = buildLegacyCustomWidgetMigrationPrompt(
|
||||
{
|
||||
id: "legacy",
|
||||
name: "Private service",
|
||||
description: "Status",
|
||||
iconUrl: "https://icons:password@example.test/private/icon.svg?access_token=icon-secret",
|
||||
url: "https://admin:password@example.test/hooks/path-token?api_key=top-secret&mode=full",
|
||||
authType: "bearer",
|
||||
headerName: null,
|
||||
method: "POST",
|
||||
requestBody: JSON.stringify({ token: "body-secret", limit: 5 }),
|
||||
displayType: "singleValue",
|
||||
displayConfig: "corrupted-config-with-display-secret",
|
||||
enabled: true,
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date(0),
|
||||
creatorId: null,
|
||||
},
|
||||
["apiKey"],
|
||||
);
|
||||
|
||||
expect(prompt).toContain("homarr-custom-widget-v1");
|
||||
expect(prompt).toContain("homarr-custom-widget-v2");
|
||||
expect(prompt).toContain("configuredSecretKinds");
|
||||
expect(prompt).not.toContain("top-secret");
|
||||
expect(prompt).not.toContain("body-secret");
|
||||
expect(prompt).not.toContain("admin:password");
|
||||
expect(prompt).not.toContain("path-token");
|
||||
expect(prompt).not.toContain("icon-secret");
|
||||
expect(prompt).not.toContain("icons:password");
|
||||
expect(prompt).not.toContain("private/icon.svg");
|
||||
expect(prompt).not.toContain("display-secret");
|
||||
});
|
||||
|
||||
test("omits valid free-text display configuration from the migration prompt", () => {
|
||||
const prompt = buildLegacyCustomWidgetMigrationPrompt(
|
||||
{
|
||||
id: "legacy-custom-jsx",
|
||||
name: "Private service",
|
||||
description: "Status",
|
||||
iconUrl: null,
|
||||
url: "https://example.test/api/status",
|
||||
authType: "bearer",
|
||||
headerName: null,
|
||||
method: "GET",
|
||||
requestBody: null,
|
||||
displayType: "customJsx",
|
||||
displayConfig: stringifySuperJson({
|
||||
type: "customJsx",
|
||||
template: "<Text>LEGACY_PRIVATE_MARKER Bearer sk-secret-123456</Text>",
|
||||
}),
|
||||
enabled: true,
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date(0),
|
||||
creatorId: null,
|
||||
},
|
||||
["apiKey"],
|
||||
);
|
||||
|
||||
expect(prompt).toContain("display configuration was intentionally omitted");
|
||||
expect(prompt).not.toContain("LEGACY_PRIVATE_MARKER");
|
||||
expect(prompt).not.toContain("Bearer sk-secret-123456");
|
||||
expect(prompt).not.toContain("sk-secret-123456");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { CustomJsxRequest } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { resolvePreviewRequestParams } from "../../custom-widget/preview-procedure-helpers";
|
||||
import { resolveOptionRequestValues } from "../../custom-widget/management-queries";
|
||||
|
||||
const loadRequest: CustomJsxRequest = {
|
||||
source: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
path: "/endpoints/{option:environmentId}/containers",
|
||||
auth: "inherit",
|
||||
permission: "view",
|
||||
trigger: "load",
|
||||
};
|
||||
|
||||
describe("preview request option bindings", () => {
|
||||
it("resolves load request parameters from the selected preview options", () => {
|
||||
expect(resolvePreviewRequestParams(loadRequest, { environmentId: 7 }, {})).toEqual({
|
||||
"option:environmentId": 7,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves invoking component parameters for manual requests", () => {
|
||||
const manualRequest = {
|
||||
...loadRequest,
|
||||
trigger: "manual" as const,
|
||||
path: "/endpoints/{param:endpointId}/containers",
|
||||
};
|
||||
expect(resolvePreviewRequestParams(manualRequest, { environmentId: 7 }, { endpointId: 12 })).toEqual({
|
||||
endpointId: 12,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("configuration option request bindings", () => {
|
||||
it("resolves option configuration and runtime parameters in their own slots", () => {
|
||||
const request: CustomJsxRequest = {
|
||||
...loadRequest,
|
||||
path: "/environments/{option:environmentId}/containers/{param:containerId}",
|
||||
};
|
||||
|
||||
expect(resolveOptionRequestValues(request, { environmentId: 7, containerId: 12, unrelated: true })).toEqual({
|
||||
"option:environmentId": 7,
|
||||
containerId: 12,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
assertJsonBudget,
|
||||
assertSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
resolveAndValidateHost,
|
||||
resolveSameOriginTarget,
|
||||
validateCustomWidgetUrl,
|
||||
} from "../../custom-widget/request-executor";
|
||||
|
||||
describe("custom widget request executor", () => {
|
||||
test.each([
|
||||
["8.8.8.8", "public"],
|
||||
["10.0.0.1", "private"],
|
||||
["127.0.0.1", "loopback"],
|
||||
["169.254.169.254", "blocked"],
|
||||
["224.0.0.1", "blocked"],
|
||||
["::ffff:127.0.0.1", "blocked"],
|
||||
["fe80::1", "blocked"],
|
||||
] as const)("classifies %s as %s", (address, expected) => {
|
||||
expect(classifyAddress(address)).toBe(expected);
|
||||
});
|
||||
|
||||
test("enforces configured address scopes", async () => {
|
||||
await expect(resolveAndValidateHost("10.0.0.1", "public")).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
await expect(resolveAndValidateHost("10.0.0.1", "private")).resolves.toHaveLength(1);
|
||||
await expect(resolveAndValidateHost("127.0.0.1", "private")).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
await expect(resolveAndValidateHost("127.0.0.1", "loopback")).resolves.toHaveLength(1);
|
||||
await expect(resolveAndValidateHost("169.254.169.254", "loopback")).rejects.toMatchObject({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
});
|
||||
|
||||
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("Only HTTP and HTTPS");
|
||||
expect(() => validateCustomWidgetUrl("https://user:password@example.com/api")).toThrow("credentials");
|
||||
expect(() => validateCustomWidgetUrl("https://example.com/api#secret")).toThrow("fragments");
|
||||
});
|
||||
|
||||
test("rejects cross-origin named request targets", () => {
|
||||
expect(resolveSameOriginTarget("https://example.com/base", "https://example.com/status").pathname).toBe("/status");
|
||||
expect(() => resolveSameOriginTarget("https://example.com/base", "https://attacker.example/status")).toThrow(
|
||||
"origin",
|
||||
);
|
||||
});
|
||||
|
||||
test.each(["Authorization", "Cookie", "Host", "Proxy-Authorization", "Sec-Fetch-Site", "X-Forwarded-For"])(
|
||||
"rejects the reserved %s header",
|
||||
(header) => {
|
||||
expect(() => assertSafeStaticHeaders({ [header]: "value" })).toThrow("reserved");
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects response JSON that exceeds the depth budget", () => {
|
||||
let nested: Record<string, unknown> = {};
|
||||
const root = nested;
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
nested.child = {};
|
||||
nested = nested.child as Record<string, unknown>;
|
||||
}
|
||||
expect(() => assertJsonBudget(root)).toThrow("deeply nested");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
|
||||
import { acquireCustomWidgetRequestLimit } from "../../custom-widget/request-limits";
|
||||
|
||||
test("enforces the server-side DELETE rate limit with retry metadata", async () => {
|
||||
const input = { category: "delete" as const, userId: createId(), itemId: createId(), definitionId: createId() };
|
||||
for (let count = 0; count < 3; count += 1) {
|
||||
const release = await acquireCustomWidgetRequestLimit(input);
|
||||
await release();
|
||||
}
|
||||
|
||||
try {
|
||||
await acquireCustomWidgetRequestLimit(input);
|
||||
expect.unreachable("the fourth DELETE request should be rate limited");
|
||||
} catch (error) {
|
||||
expect(error).toMatchObject({ code: "TOO_MANY_REQUESTS" });
|
||||
const cause = (error as { cause?: { flatten?: () => Record<string, unknown> } }).cause;
|
||||
expect(cause?.flatten?.()).toMatchObject({ retryAfterMs: expect.any(Number) });
|
||||
}
|
||||
});
|
||||
|
||||
test("enforces four concurrent requests per user and item", async () => {
|
||||
const input = { category: "query" as const, userId: createId(), itemId: createId(), definitionId: createId() };
|
||||
const releases = await Promise.all(Array.from({ length: 4 }, () => acquireCustomWidgetRequestLimit(input)));
|
||||
|
||||
await expect(acquireCustomWidgetRequestLimit(input)).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
|
||||
await Promise.all(releases.map((release) => release()));
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { stringify as stringifySuperJson } from "superjson";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
BUNDLED_CUSTOM_WIDGETS,
|
||||
CUSTOM_WIDGET_STARTER,
|
||||
customWidgetDefinitionSchema,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
|
||||
import {
|
||||
safeParseStoredCustomWidgetDefinition,
|
||||
serializeCustomWidgetDefinition,
|
||||
} from "../../custom-widget/stored-definition";
|
||||
|
||||
describe("stored custom widget definitions", () => {
|
||||
test("parses a valid stored definition", () => {
|
||||
const result = safeParseStoredCustomWidgetDefinition(
|
||||
serializeCustomWidgetDefinition(customWidgetDefinitionSchema.parse(CUSTOM_WIDGET_STARTER)),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ success: true, widget: { $schema: "homarr-custom-widget-v2" } });
|
||||
});
|
||||
|
||||
test("returns useful issues for an invalid stored request instead of throwing", () => {
|
||||
const currency = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-currency-exchange");
|
||||
if (!currency) throw new Error("Currency Exchange bundled widget is missing");
|
||||
|
||||
const stored = serializeCustomWidgetDefinition(customWidgetDefinitionSchema.parse(currency.widget));
|
||||
const result = safeParseStoredCustomWidgetDefinition({
|
||||
...stored,
|
||||
requests: stringifySuperJson({ rates: { path: "/latest/{option:missing}" } }),
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
issues: expect.arrayContaining([expect.objectContaining({ path: "requests.rates" })]),
|
||||
});
|
||||
});
|
||||
|
||||
test("contains malformed serialized data", () => {
|
||||
const stored = serializeCustomWidgetDefinition(customWidgetDefinitionSchema.parse(CUSTOM_WIDGET_STARTER));
|
||||
|
||||
expect(safeParseStoredCustomWidgetDefinition({ ...stored, requests: "not-json" })).toEqual({
|
||||
success: false,
|
||||
issues: [{ message: "Stored widget data could not be read" }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
get: vi.fn(async (_id: string): Promise<unknown> => undefined),
|
||||
list: vi.fn(async (_options: unknown): Promise<unknown> => undefined),
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/logs", () => ({
|
||||
createLogger: () => mocks.logger,
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/workshop/backend", () => ({
|
||||
WorkshopBackend: class {
|
||||
public get(id: string) {
|
||||
return mocks.get(id);
|
||||
}
|
||||
|
||||
public list(options: unknown) {
|
||||
return mocks.list(options);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { customWidgetRouter } from "../../custom-widget/custom-widget-router";
|
||||
|
||||
const session = {
|
||||
user: {
|
||||
id: createId(),
|
||||
permissions: ["admin"],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||
} satisfies Session;
|
||||
|
||||
const createCaller = () =>
|
||||
customWidgetRouter.createCaller({
|
||||
db: createDb(),
|
||||
deviceType: undefined,
|
||||
session,
|
||||
});
|
||||
|
||||
const createTokenizedFailure = (apiKey: string) => {
|
||||
const tokenizedUrl = `https://workshop.example/api/submissions?access_token=${apiKey}`;
|
||||
const error = new Error(`Workshop request failed for ${tokenizedUrl}`);
|
||||
error.name = `WorkshopTransportError:${tokenizedUrl}`;
|
||||
return error;
|
||||
};
|
||||
|
||||
const expectSafeFailure = (
|
||||
error: unknown,
|
||||
apiKey: string,
|
||||
logMessage: string,
|
||||
event: "workshop_widget_lookup_failed" | "workshop_widget_search_failed",
|
||||
) => {
|
||||
expect(error).toMatchObject({
|
||||
code: "BAD_GATEWAY",
|
||||
message: "Workshop is unavailable",
|
||||
});
|
||||
expect((error as Error).cause).toBeUndefined();
|
||||
expect(String(error)).not.toContain(apiKey);
|
||||
expect(String(error)).not.toContain("access_token");
|
||||
expect(mocks.logger.error).toHaveBeenCalledWith(logMessage, {
|
||||
event,
|
||||
errorName: "WorkshopBackendError",
|
||||
});
|
||||
expect(JSON.stringify(mocks.logger.error.mock.calls)).not.toContain(apiKey);
|
||||
expect(JSON.stringify(mocks.logger.error.mock.calls)).not.toContain("access_token");
|
||||
};
|
||||
|
||||
describe("Workshop backend error privacy", () => {
|
||||
beforeEach(() => {
|
||||
mocks.get.mockReset();
|
||||
mocks.list.mockReset();
|
||||
mocks.logger.error.mockClear();
|
||||
});
|
||||
|
||||
test("redacts backend lookup failures from TRPC output and logs", async () => {
|
||||
const apiKey = "workshop-lookup-secret";
|
||||
mocks.get.mockRejectedValueOnce(createTokenizedFailure(apiKey));
|
||||
|
||||
const error = await createCaller()
|
||||
.workshopGet({ submissionId: "submission-id" })
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
|
||||
expectSafeFailure(error, apiKey, "Workshop widget lookup failed", "workshop_widget_lookup_failed");
|
||||
});
|
||||
|
||||
test("redacts backend search failures from TRPC output and logs", async () => {
|
||||
const apiKey = "workshop-search-secret";
|
||||
mocks.list.mockRejectedValueOnce(createTokenizedFailure(apiKey));
|
||||
|
||||
const error = await createCaller()
|
||||
.workshopSearch({ query: "weather" })
|
||||
.then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
|
||||
expectSafeFailure(error, apiKey, "Workshop widget search failed", "workshop_widget_search_failed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { stringify } from "superjson";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards, sectionCollapseStates, sections, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
|
||||
import { sectionRouter } from "../section/section-router";
|
||||
|
||||
const userId = createId();
|
||||
const session = {
|
||||
user: {
|
||||
id: userId,
|
||||
permissions: [],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date().toISOString(),
|
||||
} satisfies Session;
|
||||
|
||||
const createCallerAsync = async () => {
|
||||
const db = createDb();
|
||||
const boardId = createId();
|
||||
|
||||
await db.insert(users).values({ id: userId });
|
||||
await db.insert(boards).values({
|
||||
id: boardId,
|
||||
name: createId(),
|
||||
creatorId: userId,
|
||||
});
|
||||
|
||||
return {
|
||||
boardId,
|
||||
db,
|
||||
caller: sectionRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
describe("changeCollapsed", () => {
|
||||
it("rejects a root section", async () => {
|
||||
const { boardId, caller, db } = await createCallerAsync();
|
||||
const sectionId = createId();
|
||||
await db.insert(sections).values({
|
||||
id: sectionId,
|
||||
boardId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
});
|
||||
|
||||
await expect(caller.changeCollapsed({ sectionId, collapsed: true })).rejects.toThrow("Section cannot be collapsed");
|
||||
});
|
||||
|
||||
it("creates and updates collapse state for an enabled container", async () => {
|
||||
const { boardId, caller, db } = await createCallerAsync();
|
||||
const sectionId = createId();
|
||||
await db.insert(sections).values({
|
||||
id: sectionId,
|
||||
boardId,
|
||||
kind: "container",
|
||||
options: stringify({ collapsible: true }),
|
||||
});
|
||||
|
||||
await caller.changeCollapsed({ sectionId, collapsed: true });
|
||||
await caller.changeCollapsed({ sectionId, collapsed: false });
|
||||
|
||||
const states = await db.query.sectionCollapseStates.findMany({
|
||||
where: eq(sectionCollapseStates.sectionId, sectionId),
|
||||
});
|
||||
expect(states).toHaveLength(1);
|
||||
expect(states[0]?.collapsed).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a container when collapsing is disabled", async () => {
|
||||
const { boardId, caller, db } = await createCallerAsync();
|
||||
const sectionId = createId();
|
||||
await db.insert(sections).values({
|
||||
id: sectionId,
|
||||
boardId,
|
||||
kind: "container",
|
||||
});
|
||||
|
||||
await expect(caller.changeCollapsed({ sectionId, collapsed: true })).rejects.toThrow("Section cannot be collapsed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import type { Database } from "@homarr/db";
|
||||
import type { GroupPermissionKey } from "@homarr/definitions";
|
||||
|
||||
import { updateCheckerRouter } from "../update-checker";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getDataAsync: vi.fn(async () => ({
|
||||
data: { availableUpdates: [{ tagName: "v99.0.0" }] },
|
||||
timestamp: new Date(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/request-handler/update-checker", () => ({
|
||||
updateCheckerRequestHandler: {
|
||||
handler: () => ({ getDataAsync: mocks.getDataAsync }),
|
||||
},
|
||||
}));
|
||||
|
||||
const createSession = (permissions: GroupPermissionKey[]): Session => ({
|
||||
user: {
|
||||
id: "user",
|
||||
permissions,
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const createCaller = (session: Session | null) =>
|
||||
updateCheckerRouter.createCaller({
|
||||
db: null as unknown as Database,
|
||||
deviceType: undefined,
|
||||
session,
|
||||
});
|
||||
|
||||
describe("update checker authorization", () => {
|
||||
test("allows administrators to read the cached result", async () => {
|
||||
await expect(createCaller(createSession(["admin"])).getAvailableUpdates()).resolves.toEqual([
|
||||
{ tagName: "v99.0.0" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects authenticated users without admin permission", async () => {
|
||||
await expect(createCaller(createSession([])).getAvailableUpdates()).rejects.toThrow("Permission denied");
|
||||
});
|
||||
|
||||
test("rejects anonymous users", async () => {
|
||||
await expect(createCaller(null).getAvailableUpdates()).rejects.toThrow("UNAUTHORIZED");
|
||||
});
|
||||
|
||||
test("returns an empty result when the cache reader fails", async () => {
|
||||
mocks.getDataAsync.mockRejectedValueOnce(new Error("Redis unavailable"));
|
||||
|
||||
await expect(createCaller(createSession(["admin"])).getAvailableUpdates()).resolves.toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
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";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
|
||||
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,
|
||||
invalidateCustomWidgetResponseCache: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../custom-widget/request-limits", () => ({
|
||||
acquireCustomWidgetRequestLimit: vi.fn(async () => async () => undefined),
|
||||
}));
|
||||
|
||||
import { serializeCustomWidgetDefinition } from "../../custom-widget/stored-definition";
|
||||
import { customApiRouter } from "../../widgets/custom-api";
|
||||
|
||||
const definition: HomarrCustomWidgetV2 = {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Router test widget",
|
||||
sources: {
|
||||
default: {
|
||||
name: "API",
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: "public",
|
||||
auth: "none",
|
||||
},
|
||||
},
|
||||
requests: {
|
||||
"load-status": {
|
||||
source: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
auth: "inherit",
|
||||
permission: "view",
|
||||
trigger: "load",
|
||||
},
|
||||
status: {
|
||||
source: "default",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
path: "/status/{param:name}",
|
||||
auth: "inherit",
|
||||
permission: "view",
|
||||
trigger: "manual",
|
||||
},
|
||||
toggle: {
|
||||
source: "default",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
path: "/toggle",
|
||||
body: { enabled: { $param: "enabled" } },
|
||||
auth: "inherit",
|
||||
permission: "modify",
|
||||
trigger: "manual",
|
||||
},
|
||||
delete: {
|
||||
source: "default",
|
||||
kind: "action",
|
||||
method: "DELETE",
|
||||
path: "/resource",
|
||||
auth: "inherit",
|
||||
permission: "full",
|
||||
trigger: "manual",
|
||||
confirmation: { title: "Delete resource", message: "Delete this resource?", destructive: true },
|
||||
},
|
||||
},
|
||||
options: {},
|
||||
template: "<Text>{data['load-status']?.value}</Text>",
|
||||
};
|
||||
|
||||
const createSession = (userId: string): Session => ({
|
||||
user: { id: userId, permissions: [], colorScheme: "light" },
|
||||
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||
});
|
||||
|
||||
async function setup(isPublic = true) {
|
||||
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,
|
||||
...serializeCustomWidgetDefinition(definition),
|
||||
creatorId: ownerId,
|
||||
});
|
||||
await db.insert(items).values({
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind: "customApi",
|
||||
options: stringifySuperJson({ definitionId, configuration: {}, configurationVersion: 1 }),
|
||||
});
|
||||
return { db, ownerId, boardId, itemId, definitionId };
|
||||
}
|
||||
|
||||
describe("Custom JSX v2 board router", () => {
|
||||
beforeEach(() => mocks.executeRequest.mockClear());
|
||||
|
||||
test("allows public queries only through the definition placed on an accessible board", async () => {
|
||||
const { db, itemId } = await setup();
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await expect(caller.queryRequest({ itemId, requestId: "status", params: { name: "homarr" } })).resolves.toEqual(
|
||||
expect.objectContaining({ ok: true, data: { value: 42 } }),
|
||||
);
|
||||
await expect(caller.queryRequest({ itemId, requestId: "missing", params: {} })).rejects.toMatchObject({
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
expect(mocks.executeRequest).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("hides private boards and disabled definitions before executing a request", async () => {
|
||||
const privateSetup = await setup(false);
|
||||
const anonymous = customApiRouter.createCaller({
|
||||
db: privateSetup.db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
});
|
||||
await expect(
|
||||
anonymous.queryRequest({ itemId: privateSetup.itemId, requestId: "status", params: { name: "homarr" } }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
|
||||
const enabledSetup = await setup();
|
||||
await enabledSetup.db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ enabled: false })
|
||||
.where(eq(customWidgetDefinitions.id, enabledSetup.definitionId));
|
||||
const publicCaller = customApiRouter.createCaller({ db: enabledSetup.db, deviceType: undefined, session: null });
|
||||
await expect(publicCaller.getData({ itemId: enabledSetup.itemId })).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
await expect(
|
||||
publicCaller.queryRequest({ itemId: enabledSetup.itemId, requestId: "status", params: { name: "homarr" } }),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
const ownerCaller = customApiRouter.createCaller({
|
||||
db: enabledSetup.db,
|
||||
deviceType: undefined,
|
||||
session: createSession(enabledSetup.ownerId),
|
||||
});
|
||||
await expect(
|
||||
ownerCaller.executeAction({ itemId: enabledSetup.itemId, requestId: "toggle", params: { enabled: true } }),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects request-kind and parameter mismatches", async () => {
|
||||
const { db, itemId, ownerId } = await setup();
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(ownerId) });
|
||||
|
||||
await expect(caller.queryRequest({ itemId, requestId: "toggle", params: { enabled: true } })).rejects.toMatchObject(
|
||||
{ code: "NOT_FOUND" },
|
||||
);
|
||||
await expect(caller.queryRequest({ itemId, requestId: "status", params: {} })).rejects.toThrow();
|
||||
expect(mocks.executeRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("enforces modify permission and renders an authorized action body", async () => {
|
||||
const { db, itemId, boardId } = await setup(false);
|
||||
const editorId = createId();
|
||||
await db.insert(users).values({ id: editorId });
|
||||
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(editorId) });
|
||||
|
||||
await expect(
|
||||
caller.executeAction({ itemId, requestId: "toggle", params: { enabled: true } }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
await db.insert(boardUserPermissions).values({ boardId, userId: editorId, permission: "modify" });
|
||||
await expect(caller.executeAction({ itemId, requestId: "toggle", params: { enabled: true } })).resolves.toEqual(
|
||||
expect.objectContaining({ ok: true }),
|
||||
);
|
||||
expect(mocks.executeRequest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ method: "POST", body: '{"enabled":true}' }),
|
||||
);
|
||||
});
|
||||
|
||||
test("requires confirmation and full permission for DELETE actions", async () => {
|
||||
const { db, itemId, boardId, ownerId } = await setup(false);
|
||||
const owner = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(ownerId) });
|
||||
await expect(owner.executeAction({ itemId, requestId: "delete", params: {} })).rejects.toMatchObject({
|
||||
code: "PRECONDITION_FAILED",
|
||||
});
|
||||
|
||||
const editorId = createId();
|
||||
await db.insert(users).values({ id: editorId });
|
||||
await db.insert(boardUserPermissions).values({ boardId, userId: editorId, permission: "modify" });
|
||||
const editor = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(editorId) });
|
||||
await expect(
|
||||
editor.executeAction({ itemId, requestId: "delete", params: {}, confirmed: true }),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
await expect(owner.executeAction({ itemId, requestId: "delete", params: {}, confirmed: true })).resolves.toEqual(
|
||||
expect.objectContaining({ ok: true }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import SuperJSON from "superjson";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { eq } from "@homarr/db";
|
||||
import { boards, items, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
|
||||
import { optionsRouter } from "../../widgets/options";
|
||||
|
||||
const createSession = (userId: string, isAdmin = false): Session => ({
|
||||
user: {
|
||||
id: userId,
|
||||
permissions: isAdmin ? ["admin"] : [],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date(Date.now() + 60_000).toISOString(),
|
||||
});
|
||||
|
||||
async function setup(kind: "customApi" | "weather") {
|
||||
const db = createDb();
|
||||
const userId = createId();
|
||||
const boardId = createId();
|
||||
const itemId = createId();
|
||||
await db.insert(users).values({ id: userId });
|
||||
await db.insert(boards).values({ id: boardId, name: createId(), creatorId: userId });
|
||||
await db.insert(items).values({
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind,
|
||||
options: SuperJSON.stringify(
|
||||
kind === "customApi"
|
||||
? { definitionId: "definition-1", refreshInterval: 30, configuration: { server: "primary" } }
|
||||
: { location: "Paris" },
|
||||
),
|
||||
});
|
||||
return { db, userId, boardId, itemId };
|
||||
}
|
||||
|
||||
describe("saveItemOptions Custom Widget access", () => {
|
||||
test("rejects direct Custom Widget reconfiguration by a non-admin board modifier", async () => {
|
||||
const { db, userId, boardId, itemId } = await setup("customApi");
|
||||
const caller = optionsRouter.createCaller({ db, deviceType: undefined, session: createSession(userId) });
|
||||
|
||||
await expect(
|
||||
caller.saveItemOptions({
|
||||
boardId,
|
||||
itemId,
|
||||
newOptions: {
|
||||
definitionId: "definition-2",
|
||||
refreshInterval: 1,
|
||||
configuration: { server: "attacker" },
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
|
||||
const stored = await db.query.items.findFirst({ where: eq(items.id, itemId) });
|
||||
expect(SuperJSON.parse(stored?.options ?? "")).toMatchObject({
|
||||
definitionId: "definition-1",
|
||||
refreshInterval: 30,
|
||||
configuration: { server: "primary" },
|
||||
});
|
||||
});
|
||||
|
||||
test("allows a Homarr admin to reconfigure a Custom Widget placement", async () => {
|
||||
const { db, userId, boardId, itemId } = await setup("customApi");
|
||||
const caller = optionsRouter.createCaller({ db, deviceType: undefined, session: createSession(userId, true) });
|
||||
|
||||
await expect(
|
||||
caller.saveItemOptions({ boardId, itemId, newOptions: { refreshInterval: 60 } }),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
const stored = await db.query.items.findFirst({ where: eq(items.id, itemId) });
|
||||
expect(SuperJSON.parse(stored?.options ?? "")).toMatchObject({ refreshInterval: 60 });
|
||||
});
|
||||
|
||||
test("allows normalized missing defaults without treating them as reconfiguration", async () => {
|
||||
const { db, userId, boardId, itemId } = await setup("customApi");
|
||||
const stored = await db.query.items.findFirst({ where: eq(items.id, itemId) });
|
||||
const options = SuperJSON.parse<Record<string, unknown>>(stored?.options ?? "");
|
||||
delete options.configuration;
|
||||
delete options.configurationVersion;
|
||||
await db
|
||||
.update(items)
|
||||
.set({ options: SuperJSON.stringify(options) })
|
||||
.where(eq(items.id, itemId));
|
||||
const caller = optionsRouter.createCaller({ db, deviceType: undefined, session: createSession(userId) });
|
||||
|
||||
await expect(
|
||||
caller.saveItemOptions({
|
||||
boardId,
|
||||
itemId,
|
||||
newOptions: { configuration: {}, configurationVersion: 1 },
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test("preserves ordinary board-modifier option updates for other widgets", async () => {
|
||||
const { db, userId, boardId, itemId } = await setup("weather");
|
||||
const caller = optionsRouter.createCaller({ db, deviceType: undefined, session: createSession(userId) });
|
||||
|
||||
await expect(
|
||||
caller.saveItemOptions({ boardId, itemId, newOptions: { location: "Lyon" } }),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -12,8 +12,8 @@ export const updateCheckerRouter = createTRPCRouter({
|
||||
const data = await handler.getDataAsync();
|
||||
return data.data.availableUpdates;
|
||||
} catch (error) {
|
||||
logger.error(new Error("Failed to get available updates", { cause: error }));
|
||||
return undefined; // We return undefined to not show the indicator in the UI
|
||||
logger.error(new Error("Failed to read the cached update check", { cause: error }));
|
||||
return []; // An empty list hides the indicator without violating TanStack Query's data contract.
|
||||
}
|
||||
}),
|
||||
});
|
||||
@@ -1,252 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { JSONPath } from "jsonpath-plus";
|
||||
|
||||
import {
|
||||
sonarrResponse,
|
||||
sonarrStatGridConfig,
|
||||
proxmoxResponse,
|
||||
proxmoxProgressBarsConfig,
|
||||
diskUsageResponse,
|
||||
diskTableConfig,
|
||||
piholeResponse,
|
||||
piholeStatusIndicatorConfig,
|
||||
piholeCountGridConfig,
|
||||
radarrResponse,
|
||||
radarrStatGridConfig,
|
||||
jellyfinItemCountsResponse,
|
||||
jellyfinCountGridConfig,
|
||||
} from "./custom-api-fixtures";
|
||||
|
||||
const extractors: Record<string, (json: unknown, config: Record<string, unknown>) => unknown> = {
|
||||
singleValue: (json, c) => ({
|
||||
type: "singleValue",
|
||||
label: (c.label as string) ?? "",
|
||||
unit: (c.unit as string) ?? "",
|
||||
value: JSONPath({ path: (c.jsonPath as string) ?? "$", json: json as object, wrap: false }),
|
||||
valueSize: c.valueSize ?? "lg",
|
||||
labelPosition: c.labelPosition ?? "below",
|
||||
}),
|
||||
keyValue: (json, c) => ({
|
||||
type: "keyValue",
|
||||
entries: ((c.mappings as Array<{ label: string; jsonPath: string; unit: string }>) ?? []).map((m) => ({
|
||||
label: m.label,
|
||||
unit: m.unit,
|
||||
value: JSONPath({ path: m.jsonPath, json: json as object, wrap: false }),
|
||||
})),
|
||||
layout: c.layout ?? "list",
|
||||
columns: c.columns ?? 2,
|
||||
}),
|
||||
table: (json, c) => {
|
||||
const tablePath = (c.tablePath as string) ?? "$";
|
||||
const columns = (c.columns as Array<{ header: string; jsonPath: string }>) ?? [];
|
||||
const rows = JSONPath({ path: tablePath, json: json as object, wrap: true }) as unknown[];
|
||||
const flatRows = Array.isArray(rows[0]) ? (rows[0] as unknown[]) : rows;
|
||||
return {
|
||||
type: "table",
|
||||
columns: columns.map((col) => col.header),
|
||||
rows: flatRows.map((row) =>
|
||||
columns.map((col) => JSONPath({ path: col.jsonPath, json: row as object, wrap: false })),
|
||||
),
|
||||
striped: c.striped ?? true,
|
||||
compact: c.compact ?? false,
|
||||
};
|
||||
},
|
||||
statGrid: (json, c) => ({
|
||||
type: "statGrid",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; unit: string; color?: string }>) ?? []).map(
|
||||
(item) => ({
|
||||
label: item.label,
|
||||
unit: item.unit,
|
||||
color: item.color ?? "blue",
|
||||
value: JSONPath({ path: item.jsonPath, json: json as object, wrap: false }),
|
||||
}),
|
||||
),
|
||||
columns: c.columns ?? 2,
|
||||
cardStyle: c.cardStyle ?? "filled",
|
||||
}),
|
||||
progressBars: (json, c) => ({
|
||||
type: "progressBars",
|
||||
bars: (
|
||||
(c.bars as Array<{ label: string; valuePath: string; maxPath?: string; unit: string; color?: string }>) ?? []
|
||||
).map((bar) => {
|
||||
const value = JSONPath({ path: bar.valuePath, json: json as object, wrap: false });
|
||||
const max = bar.maxPath ? JSONPath({ path: bar.maxPath, json: json as object, wrap: false }) : undefined;
|
||||
return {
|
||||
label: bar.label,
|
||||
unit: bar.unit,
|
||||
color: bar.color ?? "blue",
|
||||
value: Number(value) || 0,
|
||||
max: max !== undefined ? Number(max) || 100 : undefined,
|
||||
};
|
||||
}),
|
||||
showPercentage: c.showPercentage ?? true,
|
||||
barSize: c.barSize ?? "md",
|
||||
}),
|
||||
statusIndicator: (json, c) => ({
|
||||
type: "statusIndicator",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; goodValues: string[] }>) ?? []).map((item) => {
|
||||
const value = JSONPath({ path: item.jsonPath, json: json as object, wrap: false });
|
||||
const isGood = item.goodValues.some((gv) => String(value).toLowerCase() === gv.toLowerCase());
|
||||
return { label: item.label, value: String(value ?? "unknown"), isGood };
|
||||
}),
|
||||
layout: c.layout ?? "list",
|
||||
dotSize: c.dotSize ?? "md",
|
||||
}),
|
||||
countGrid: (json, c) => ({
|
||||
type: "countGrid",
|
||||
items: ((c.items as Array<{ label: string; jsonPath: string; unit: string }>) ?? []).map((item) => ({
|
||||
label: item.label,
|
||||
unit: item.unit,
|
||||
value: JSONPath({ path: item.jsonPath, json: json as object, wrap: false }),
|
||||
})),
|
||||
columns: c.columns ?? 2,
|
||||
valueSize: c.valueSize ?? "md",
|
||||
}),
|
||||
raw: (json, c) => ({
|
||||
type: "raw",
|
||||
data: JSONPath({ path: (c.jsonPath as string) ?? "$", json: json as object, wrap: false }),
|
||||
maxHeight: c.maxHeight ?? 300,
|
||||
}),
|
||||
customJsx: (json, config) => ({
|
||||
type: "customJsx" as const,
|
||||
template: config.template as string,
|
||||
data: json,
|
||||
}),
|
||||
};
|
||||
|
||||
function extract(type: string, json: unknown, config: Record<string, unknown>) {
|
||||
const fn = extractors[type];
|
||||
if (!fn) throw new Error(`No extractor for type: ${type}`);
|
||||
return fn(json, config);
|
||||
}
|
||||
|
||||
describe("custom-api extractors", () => {
|
||||
it("sonarr statGrid extracts missing and queue counts", () => {
|
||||
const result = extract("statGrid", sonarrResponse, sonarrStatGridConfig) as {
|
||||
type: string;
|
||||
items: Array<{ label: string; value: unknown; color: string }>;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("statGrid");
|
||||
expect(result.items).toHaveLength(2);
|
||||
expect(result.items[0]?.value).toBe(42);
|
||||
expect(result.items[0]?.label).toBe("Missing");
|
||||
expect(result.items[0]?.color).toBe("red");
|
||||
expect(result.items[1]?.value).toBe(5);
|
||||
});
|
||||
|
||||
it("proxmox progressBars extracts memory and disk usage", () => {
|
||||
const result = extract("progressBars", proxmoxResponse, proxmoxProgressBarsConfig) as {
|
||||
type: string;
|
||||
bars: Array<{ label: string; value: number; max: number }>;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("progressBars");
|
||||
expect(result.bars).toHaveLength(2);
|
||||
expect(result.bars[0]?.value).toBe(12_884_901_888);
|
||||
expect(result.bars[0]?.max).toBe(34_359_738_368);
|
||||
expect(result.bars[1]?.label).toBe("Disk");
|
||||
});
|
||||
|
||||
it("disk table extracts filesystem rows", () => {
|
||||
const result = extract("table", diskUsageResponse, diskTableConfig) as {
|
||||
type: string;
|
||||
columns: string[];
|
||||
rows: unknown[][];
|
||||
};
|
||||
|
||||
expect(result.type).toBe("table");
|
||||
expect(result.columns).toEqual(["Mount", "Size", "Used"]);
|
||||
expect(result.rows).toHaveLength(3);
|
||||
expect(result.rows[0]?.[0]).toBe("/");
|
||||
expect(result.rows[2]?.[2]).toBe("95%");
|
||||
});
|
||||
|
||||
it("pihole statusIndicator detects enabled state", () => {
|
||||
const result = extract("statusIndicator", piholeResponse, piholeStatusIndicatorConfig) as {
|
||||
type: string;
|
||||
items: Array<{ label: string; value: string; isGood: boolean }>;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("statusIndicator");
|
||||
expect(result.items).toHaveLength(1);
|
||||
expect(result.items[0]?.isGood).toBe(true);
|
||||
expect(result.items[0]?.value).toBe("enabled");
|
||||
});
|
||||
|
||||
it("pihole countGrid extracts all 4 stats", () => {
|
||||
const result = extract("countGrid", piholeResponse, piholeCountGridConfig) as {
|
||||
type: string;
|
||||
items: Array<{ label: string; value: unknown; unit: string }>;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("countGrid");
|
||||
expect(result.items).toHaveLength(4);
|
||||
expect(result.items[0]?.value).toBe(12_847);
|
||||
expect(result.items[1]?.value).toBe(48_291);
|
||||
expect(result.items[2]?.value).toBe(26.6);
|
||||
expect(result.items[2]?.unit).toBe("%");
|
||||
expect(result.items[3]?.value).toBe(14);
|
||||
});
|
||||
|
||||
it("radarr statGrid with outline card style", () => {
|
||||
const result = extract("statGrid", radarrResponse, radarrStatGridConfig) as {
|
||||
type: string;
|
||||
items: Array<{ label: string; value: unknown }>;
|
||||
cardStyle: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("statGrid");
|
||||
expect(result.cardStyle).toBe("outline");
|
||||
expect(result.items[0]?.value).toBe(15);
|
||||
expect(result.items[1]?.value).toBe(3);
|
||||
});
|
||||
|
||||
it("raw extractor returns raw data at path", () => {
|
||||
const result = extract("raw", piholeResponse, { type: "raw", jsonPath: "$.status", maxHeight: 200 }) as {
|
||||
type: string;
|
||||
data: unknown;
|
||||
maxHeight: number;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("raw");
|
||||
expect(result.data).toBe("enabled");
|
||||
expect(result.maxHeight).toBe(200);
|
||||
});
|
||||
|
||||
it("customJsx passes full JSON and template through", () => {
|
||||
const json = { title: "Status", items: [{ name: "CPU", value: 42 }] };
|
||||
const config = {
|
||||
type: "customJsx" as const,
|
||||
template: "<Stack><Title>{data.title}</Title></Stack>",
|
||||
};
|
||||
|
||||
const result = extract("customJsx", json, config) as {
|
||||
type: string;
|
||||
template: string;
|
||||
data: typeof json;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("customJsx");
|
||||
expect(result.template).toBe(config.template);
|
||||
expect(result.data).toEqual(json);
|
||||
});
|
||||
|
||||
it("jellyfin countGrid extracts movies/series/episodes/songs in 4-column grid", () => {
|
||||
const result = extract("countGrid", jellyfinItemCountsResponse, jellyfinCountGridConfig) as {
|
||||
type: string;
|
||||
items: Array<{ label: string; value: unknown; unit: string }>;
|
||||
columns: number;
|
||||
valueSize: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("countGrid");
|
||||
expect(result.columns).toBe(4);
|
||||
expect(result.valueSize).toBe("lg");
|
||||
expect(result.items).toHaveLength(4);
|
||||
expect(result.items[0]).toEqual({ label: "Movies", value: 185, unit: "" });
|
||||
expect(result.items[1]).toEqual({ label: "Series", value: 38, unit: "" });
|
||||
expect(result.items[2]).toEqual({ label: "Episodes", value: 770, unit: "" });
|
||||
expect(result.items[3]).toEqual({ label: "Songs", value: 0, unit: "" });
|
||||
});
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
export const sonarrResponse = {
|
||||
wanted: { totalRecords: 42 },
|
||||
queue: { totalRecords: 5 },
|
||||
series: [
|
||||
{ title: "Breaking Bad", seasons: 5, episodeCount: 62, episodeFileCount: 60 },
|
||||
{ title: "The Wire", seasons: 5, episodeCount: 60, episodeFileCount: 55 },
|
||||
],
|
||||
diskspace: [
|
||||
{ path: "/tv", label: "TV Shows", freeSpace: 150_000_000_000, totalSpace: 500_000_000_000 },
|
||||
{ path: "/movies", label: "Movies", freeSpace: 80_000_000_000, totalSpace: 250_000_000_000 },
|
||||
],
|
||||
};
|
||||
|
||||
export const sonarrStatGridConfig = {
|
||||
type: "statGrid" as const,
|
||||
items: [
|
||||
{ label: "Missing", jsonPath: "$.wanted.totalRecords", unit: "", color: "red" },
|
||||
{ label: "Queue", jsonPath: "$.queue.totalRecords", unit: "", color: "blue" },
|
||||
],
|
||||
columns: 2,
|
||||
cardStyle: "filled" as const,
|
||||
};
|
||||
|
||||
export const proxmoxResponse = {
|
||||
data: {
|
||||
cpu: 0.23,
|
||||
memory: { used: 12_884_901_888, total: 34_359_738_368 },
|
||||
rootfs: { used: 42_949_672_960, total: 107_374_182_400 },
|
||||
uptime: 864_000,
|
||||
status: "running",
|
||||
maxcpu: 8,
|
||||
maxmem: 34_359_738_368,
|
||||
name: "proxmox-node1",
|
||||
},
|
||||
};
|
||||
|
||||
export const proxmoxProgressBarsConfig = {
|
||||
type: "progressBars" as const,
|
||||
bars: [
|
||||
{ label: "Memory", valuePath: "$.data.memory.used", maxPath: "$.data.memory.total", unit: "B", color: "blue" },
|
||||
{ label: "Disk", valuePath: "$.data.rootfs.used", maxPath: "$.data.rootfs.total", unit: "B", color: "orange" },
|
||||
],
|
||||
showPercentage: true,
|
||||
barSize: "md" as const,
|
||||
};
|
||||
|
||||
export const diskUsageResponse = {
|
||||
filesystems: [
|
||||
{ filesystem: "/dev/sda1", size: "500G", used: "350G", avail: "150G", usePct: "70%", mountedOn: "/" },
|
||||
{ filesystem: "/dev/sdb1", size: "2T", used: "1.2T", avail: "800G", usePct: "60%", mountedOn: "/data" },
|
||||
{ filesystem: "/dev/sdc1", size: "4T", used: "3.8T", avail: "200G", usePct: "95%", mountedOn: "/media" },
|
||||
],
|
||||
};
|
||||
|
||||
export const diskTableConfig = {
|
||||
type: "table" as const,
|
||||
tablePath: "$.filesystems",
|
||||
columns: [
|
||||
{ header: "Mount", jsonPath: "$.mountedOn" },
|
||||
{ header: "Size", jsonPath: "$.size" },
|
||||
{ header: "Used", jsonPath: "$.usePct" },
|
||||
],
|
||||
striped: true,
|
||||
compact: false,
|
||||
};
|
||||
|
||||
export const piholeResponse = {
|
||||
domains_being_blocked: 125_432,
|
||||
dns_queries_today: 48_291,
|
||||
ads_blocked_today: 12_847,
|
||||
ads_percentage_today: 26.6,
|
||||
unique_clients: 14,
|
||||
status: "enabled",
|
||||
gravity_last_updated: { relative: { days: 2, hours: 3 } },
|
||||
};
|
||||
|
||||
export const piholeStatusIndicatorConfig = {
|
||||
type: "statusIndicator" as const,
|
||||
items: [{ label: "Pi-Hole", jsonPath: "$.status", goodValues: ["enabled"] }],
|
||||
layout: "list" as const,
|
||||
dotSize: "md" as const,
|
||||
};
|
||||
|
||||
export const piholeCountGridConfig = {
|
||||
type: "countGrid" as const,
|
||||
items: [
|
||||
{ label: "Blocked Today", jsonPath: "$.ads_blocked_today", unit: "" },
|
||||
{ label: "DNS Queries", jsonPath: "$.dns_queries_today", unit: "" },
|
||||
{ label: "Block Rate", jsonPath: "$.ads_percentage_today", unit: "%" },
|
||||
{ label: "Clients", jsonPath: "$.unique_clients", unit: "" },
|
||||
],
|
||||
columns: 2,
|
||||
valueSize: "md" as const,
|
||||
};
|
||||
|
||||
export const radarrResponse = {
|
||||
wanted: { totalRecords: 15 },
|
||||
queue: { totalRecords: 3 },
|
||||
movie: [
|
||||
{ title: "Inception", hasFile: true, monitored: true, runtime: 148, year: 2010 },
|
||||
{ title: "Interstellar", hasFile: false, monitored: true, runtime: 169, year: 2014 },
|
||||
{ title: "The Dark Knight", hasFile: true, monitored: false, runtime: 152, year: 2008 },
|
||||
],
|
||||
rootfolder: [{ path: "/movies", freeSpace: 200_000_000_000, totalSpace: 1_000_000_000_000 }],
|
||||
};
|
||||
|
||||
export const radarrStatGridConfig = {
|
||||
type: "statGrid" as const,
|
||||
items: [
|
||||
{ label: "Missing", jsonPath: "$.wanted.totalRecords", unit: "", color: "red" },
|
||||
{ label: "Queue", jsonPath: "$.queue.totalRecords", unit: "", color: "teal" },
|
||||
],
|
||||
columns: 2,
|
||||
cardStyle: "outline" as const,
|
||||
};
|
||||
|
||||
export const jellyfinItemCountsResponse = {
|
||||
MovieCount: 185,
|
||||
SeriesCount: 38,
|
||||
EpisodeCount: 770,
|
||||
ArtistCount: 0,
|
||||
ProgramCount: 0,
|
||||
TrailerCount: 0,
|
||||
SongCount: 0,
|
||||
AlbumCount: 0,
|
||||
MusicVideoCount: 0,
|
||||
BoxSetCount: 12,
|
||||
BookCount: 0,
|
||||
ItemCount: 0,
|
||||
};
|
||||
|
||||
export const jellyfinCountGridConfig = {
|
||||
type: "countGrid" as const,
|
||||
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" as const,
|
||||
};
|
||||
@@ -1,88 +1,293 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { parse } from "superjson";
|
||||
import { parse as parseSuperJson } from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { eq } from "@homarr/db";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createTRPCRouter, protectedProcedure } from "../../trpc";
|
||||
import { applyAuth } from "../custom-widget/auth";
|
||||
import { assertCustomApiItemBindingAsync, customApiItemInputSchema } from "../custom-widget/custom-widget-access";
|
||||
import { extractActionButtonDisplay, extractDisplayDataWithFallback } from "../custom-widget/display-data";
|
||||
import { boards, customWidgetDefinitions, items, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
|
||||
import type { BoardPermission } from "@homarr/definitions";
|
||||
import {
|
||||
consumeBoundedResponseAsync,
|
||||
readBoundedJsonResponseAsync,
|
||||
validateCustomApiUrl,
|
||||
withCustomApiResponseAsync,
|
||||
} from "./custom-api-security";
|
||||
getCustomWidgetConfirmation,
|
||||
getCustomWidgetDefaultOptions,
|
||||
validateCustomWidgetOptions,
|
||||
} from "@homarr/custom-widgets/core";
|
||||
import type { CustomJsxRequest, CustomWidgetSource } from "@homarr/custom-widgets/core";
|
||||
|
||||
const logger = createLogger({ module: "widget:customApi" });
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { executeCustomWidgetRequest, invalidateCustomWidgetResponseCache } from "../custom-widget/request-executor";
|
||||
import {
|
||||
hashRuntimeParams,
|
||||
renderRequestBody,
|
||||
renderRequestTarget,
|
||||
resolveCustomWidgetRequestValues,
|
||||
} from "../custom-widget/request-manifest";
|
||||
import { acquireCustomWidgetRequestLimit } from "../custom-widget/request-limits";
|
||||
import { getCustomWidgetCacheVersion } from "../custom-widget/cache-version";
|
||||
import { parseStoredCustomWidgetDefinition } from "../custom-widget/stored-definition";
|
||||
|
||||
export const customApiRouter = createTRPCRouter({
|
||||
getData: protectedProcedure.input(customApiItemInputSchema).query(async ({ ctx, input }) => {
|
||||
await assertCustomApiItemBindingAsync(ctx, input, "view");
|
||||
const definition = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.definitionId),
|
||||
with: { secrets: true },
|
||||
const runtimeParamsSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]));
|
||||
const itemInputSchema = z.object({ itemId: z.string().min(1) });
|
||||
const namedRequestInputSchema = itemInputSchema.extend({
|
||||
requestId: z.string().min(1).max(64),
|
||||
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): 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,
|
||||
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" });
|
||||
}
|
||||
};
|
||||
|
||||
async function resolvePlacedDefinitionAsync(ctx: RouterContext, itemId: string) {
|
||||
const item = await ctx.db.query.items.findFirst({
|
||||
where: eq(items.id, itemId),
|
||||
columns: { id: true, boardId: true, kind: true, options: true },
|
||||
});
|
||||
if (!item || item.kind !== "customApi") {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget item not found" });
|
||||
}
|
||||
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, item.boardId), "view");
|
||||
const itemOptions = parseItemOptions(item.options);
|
||||
const stored = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, itemOptions.definitionId),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!stored) {
|
||||
const legacy = await ctx.db.query.legacyCustomWidgetDefinitions.findFirst({
|
||||
where: eq(legacyCustomWidgetDefinitions.id, itemOptions.definitionId),
|
||||
columns: { id: true },
|
||||
});
|
||||
|
||||
if (!definition) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget definition not found" });
|
||||
}
|
||||
|
||||
if (!definition.enabled) {
|
||||
return { type: "disabled" };
|
||||
}
|
||||
|
||||
let displayConfig: Record<string, unknown>;
|
||||
try {
|
||||
displayConfig = parse(definition.displayConfig) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Widget has corrupt display configuration" });
|
||||
}
|
||||
|
||||
if (definition.displayType === "actionButton") {
|
||||
const actionDisplay = extractActionButtonDisplay(displayConfig);
|
||||
return {
|
||||
...actionDisplay,
|
||||
canExecute: ctx.session.user.permissions.includes("admin"),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const decryptedSecrets = definition.secrets.map((s) => ({
|
||||
kind: s.kind,
|
||||
value: decryptSecret(s.value),
|
||||
}));
|
||||
const url = validateCustomApiUrl(definition.url);
|
||||
const headers = new Headers({ Accept: "application/json" });
|
||||
if (definition.method !== "GET" && definition.requestBody) headers.set("Content-Type", "application/json");
|
||||
applyAuth(headers, url, definition.authType, decryptedSecrets, definition.headerName);
|
||||
|
||||
return await withCustomApiResponseAsync(
|
||||
url,
|
||||
{
|
||||
method: definition.method,
|
||||
headers,
|
||||
body: definition.method !== "GET" ? definition.requestBody : undefined,
|
||||
},
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
await consumeBoundedResponseAsync(response);
|
||||
throw new Error(`Custom API returned HTTP ${response.status}`);
|
||||
}
|
||||
const json = await readBoundedJsonResponseAsync(response);
|
||||
return extractDisplayDataWithFallback(json, definition.displayType, displayConfig);
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
const errorId = createId();
|
||||
logger.error("Failed to fetch custom API data", { errorId, definitionId: input.definitionId, error });
|
||||
if (legacy) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Custom API request failed",
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: "LEGACY_CUSTOM_WIDGET_MIGRATION_REQUIRED",
|
||||
});
|
||||
}
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Custom widget unavailable" });
|
||||
}
|
||||
if (!stored.enabled) throw new TRPCError({ code: "FORBIDDEN", message: "Widget is disabled" });
|
||||
|
||||
const definition = parseStoredCustomWidgetDefinition(stored);
|
||||
const configuration = { ...getCustomWidgetDefaultOptions(definition.options), ...itemOptions.configuration };
|
||||
const issues = validateCustomWidgetOptions(definition.options, configuration);
|
||||
if (issues.length > 0) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message: `Custom widget configuration needs repair: ${issues[0]?.path} ${issues[0]?.message}`,
|
||||
});
|
||||
}
|
||||
return { item, stored, definition, itemOptions, configuration };
|
||||
}
|
||||
|
||||
const findRequest = (resolved: ResolvedDefinition, requestId: string, kind: "query" | "action") => {
|
||||
const request = resolved.definition.requests[requestId];
|
||||
if (request?.kind !== kind) throw new TRPCError({ code: "NOT_FOUND", message: "Named request not found" });
|
||||
if (!request) throw new TRPCError({ code: "NOT_FOUND", message: "Named request not found" });
|
||||
return { id: requestId, ...request };
|
||||
};
|
||||
|
||||
const findSource = (resolved: ResolvedDefinition, sourceId: string) => {
|
||||
const source = resolved.definition.sources[sourceId];
|
||||
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Widget API source not found" });
|
||||
return { id: sourceId, ...source };
|
||||
};
|
||||
|
||||
type IdentifiedRequest = CustomJsxRequest & { id: string };
|
||||
type IdentifiedSource = CustomWidgetSource & { id: string };
|
||||
|
||||
const getAuth = (resolved: ResolvedDefinition, source: IdentifiedSource, mode: "inherit" | "none") => {
|
||||
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
|
||||
if (mode === "none" || authType === "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: authType,
|
||||
secrets,
|
||||
headerName:
|
||||
typeof source.auth === "object" && source.auth.type === "apiKeyHeader"
|
||||
? source.auth.name
|
||||
: typeof source.auth === "object" && source.auth.type === "apiKeyQuery"
|
||||
? source.auth.name
|
||||
: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const withRequestLimit = async <T>(
|
||||
ctx: RouterContext,
|
||||
resolved: ResolvedDefinition,
|
||||
request: IdentifiedRequest,
|
||||
callback: () => Promise<T>,
|
||||
) => {
|
||||
const release = await acquireCustomWidgetRequestLimit({
|
||||
category: request.kind === "query" ? "query" : request.method === "DELETE" ? "delete" : "action",
|
||||
userId: ctx.session?.user.id,
|
||||
itemId: resolved.item.id,
|
||||
definitionId: resolved.stored.id,
|
||||
});
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
};
|
||||
|
||||
const getCacheKey = (resolved: ResolvedDefinition, request: IdentifiedRequest, params: Record<string, unknown>) =>
|
||||
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${request.id}:${hashRuntimeParams(params)}`;
|
||||
|
||||
const executeRequest = async (
|
||||
ctx: RouterContext,
|
||||
resolved: ResolvedDefinition,
|
||||
request: IdentifiedRequest,
|
||||
params: Record<string, string | number | boolean>,
|
||||
) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, resolved.item.boardId), request.permission as BoardPermission);
|
||||
const source = findSource(resolved, request.source);
|
||||
const values = resolveCustomWidgetRequestValues(request, resolved.configuration, params);
|
||||
const targetUrl = renderRequestTarget(source.baseUrl, request, values);
|
||||
return withRequestLimit(ctx, resolved, request, () =>
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: source.baseUrl,
|
||||
targetUrl,
|
||||
method: request.method,
|
||||
body: renderRequestBody(request, values),
|
||||
staticHeaders: request.headers,
|
||||
auth: getAuth(resolved, source, request.auth),
|
||||
networkScope: source.networkScope,
|
||||
kind: request.kind,
|
||||
cacheKey: request.kind === "query" ? getCacheKey(resolved, request, values) : undefined,
|
||||
cacheTtlSeconds: request.cacheSeconds,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const customApiRouter = createTRPCRouter({
|
||||
getData: publicProcedure.input(itemInputSchema).query(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const loadRequests = Object.entries(resolved.definition.requests).filter(
|
||||
([, request]) => request.kind === "query" && request.trigger === "load",
|
||||
);
|
||||
const entries = await Promise.all(
|
||||
loadRequests.map(async ([requestId, request]) => {
|
||||
try {
|
||||
const response = await executeRequest(ctx, resolved, { id: requestId, ...request }, {});
|
||||
return [
|
||||
requestId,
|
||||
{
|
||||
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 [
|
||||
requestId,
|
||||
{
|
||||
data: null,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: false,
|
||||
status: 0,
|
||||
error: error instanceof Error ? error.message : "Request failed",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
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,
|
||||
requestCapabilities: Object.entries(resolved.definition.requests).map(([id, request]) => ({
|
||||
id,
|
||||
kind: request.kind,
|
||||
method: request.method,
|
||||
trigger: request.trigger,
|
||||
minimumBoardPermission: request.permission,
|
||||
confirmation: getCustomWidgetConfirmation(request),
|
||||
invalidates: request.invalidates ?? [],
|
||||
})),
|
||||
};
|
||||
}),
|
||||
|
||||
queryRequest: publicProcedure.input(namedRequestInputSchema).query(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
const request = findRequest(resolved, input.requestId, "query");
|
||||
if (request.trigger !== "manual") {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Load queries cannot be invoked manually" });
|
||||
}
|
||||
const response = await executeRequest(ctx, resolved, request, input.params);
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
data: response.data,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
};
|
||||
}),
|
||||
|
||||
executeAction: protectedProcedure
|
||||
.input(namedRequestInputSchema.extend({ confirmed: z.boolean().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
|
||||
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}:`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
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 ?? [],
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import type { WidgetOptionsSettings } from "../../../../widgets/src";
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
import { validateTimetableOptionsChangeAsync } from "./timetable";
|
||||
import { throwIfCustomWidgetPlacementChangeForbidden } from "../board/custom-widget-placement-access";
|
||||
|
||||
export const optionsRouter = createTRPCRouter({
|
||||
getWidgetOptionSettings: publicProcedure.query(async ({ ctx }): Promise<WidgetOptionsSettings> => {
|
||||
@@ -47,13 +48,18 @@ export const optionsRouter = createTRPCRouter({
|
||||
}
|
||||
|
||||
const previousOptions = SuperJSON.parse<Record<string, unknown>>(item.options);
|
||||
const options = { ...previousOptions, ...input.newOptions };
|
||||
const updatedOptions = { ...previousOptions, ...input.newOptions };
|
||||
if (item.kind === "timetable") {
|
||||
await validateTimetableOptionsChangeAsync(options, previousOptions);
|
||||
await validateTimetableOptionsChangeAsync(updatedOptions, previousOptions);
|
||||
}
|
||||
throwIfCustomWidgetPlacementChangeForbidden({
|
||||
isAdmin: ctx.session.user.permissions.includes("admin"),
|
||||
submittedItems: [{ id: item.id, kind: item.kind, options: updatedOptions }],
|
||||
storedItems: [{ id: item.id, kind: item.kind, options: previousOptions }],
|
||||
});
|
||||
await ctx.db
|
||||
.update(items)
|
||||
.set({ options: SuperJSON.stringify(options) })
|
||||
.set({ options: SuperJSON.stringify(updatedOptions) })
|
||||
.where(eq(items.id, input.itemId));
|
||||
}),
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import SuperJSON from "superjson";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { env } from "@homarr/common/env";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { eq } from "@homarr/db";
|
||||
import { items, users } from "@homarr/db/schema";
|
||||
@@ -31,6 +32,8 @@ const feedsInput = z.object({
|
||||
|
||||
export const rssFeedRouter = createTRPCRouter({
|
||||
getFeeds: publicProcedure.input(feedsInput).query(async ({ ctx, input }) => {
|
||||
if (env.NO_EXTERNAL_CONNECTION) return { entries: [], failedFeedCount: 0 };
|
||||
|
||||
const urls = (await canAccessAllFeedsAsync(ctx.db, ctx.session))
|
||||
? input.urls
|
||||
: await restrictUrlsAsync(ctx.db, input.urls);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { env } from "@homarr/common/env";
|
||||
import { weatherRequestHandler } from "@homarr/request-handler/weather";
|
||||
|
||||
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||
@@ -11,6 +12,8 @@ const atLocationInput = z.object({
|
||||
|
||||
export const weatherRouter = createTRPCRouter({
|
||||
atLocation: publicProcedure.input(atLocationInput).query(async ({ input }) => {
|
||||
if (env.NO_EXTERNAL_CONNECTION) return null;
|
||||
|
||||
const handler = weatherRequestHandler.handler(input);
|
||||
return await handler.getDataAsync().then((result) => result.data);
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { cache } from "react";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { auth } from "@homarr/auth/next";
|
||||
|
||||
import { createTRPCContext } from "./trpc";
|
||||
|
||||
export const createRscTrpcContext = cache(async () => {
|
||||
const requestHeaders = new Headers(await headers());
|
||||
requestHeaders.set("x-trpc-source", "rsc");
|
||||
|
||||
return createTRPCContext({
|
||||
session: await auth(),
|
||||
headers: requestHeaders,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { db } from "@homarr/db";
|
||||
import { getServerSettingsAsync } from "@homarr/db/queries";
|
||||
|
||||
// One settings snapshot per RSC request, shared by the root layout, theme, and
|
||||
// widget prefetching. React invalidates this cache between requests.
|
||||
export const getRscServerSettingsAsync = cache(async () => await getServerSettingsAsync(db));
|
||||
@@ -1,25 +1,16 @@
|
||||
import { cache } from "react";
|
||||
import { headers } from "next/headers";
|
||||
import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query";
|
||||
|
||||
import { appRouter, createCaller, createTRPCContext } from "@homarr/api";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { appRouter, createCaller } from "@homarr/api";
|
||||
|
||||
import { createRscTrpcContext } from "./rsc-context";
|
||||
import { makeQueryClient } from "./shared";
|
||||
|
||||
/**
|
||||
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
|
||||
* handling a tRPC call from a React Server Component.
|
||||
*/
|
||||
const createContext = cache(async () => {
|
||||
const heads = new Headers(await headers());
|
||||
heads.set("x-trpc-source", "rsc");
|
||||
|
||||
return createTRPCContext({
|
||||
session: await auth(),
|
||||
headers: heads,
|
||||
});
|
||||
});
|
||||
const createContext = () => createRscTrpcContext();
|
||||
|
||||
export const api = createCaller(createContext);
|
||||
|
||||
|
||||
@@ -1,49 +1,225 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
import type { TRPCError } from "@trpc/server";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { extractToolsFromProcedures } from "trpc-to-mcp";
|
||||
|
||||
import { appRouter } from "../router/app";
|
||||
import { boardRouter } from "../router/board";
|
||||
import { infoRouter } from "../router/info";
|
||||
import { inviteRouter } from "../router/invite";
|
||||
import { serverSettingsRouter } from "../router/serverSettings";
|
||||
import { createTRPCRouter } from "../trpc";
|
||||
import { mcpRouter } from "../mcp";
|
||||
|
||||
vi.mock("@homarr/auth", () => ({}));
|
||||
|
||||
const mcpTestRouter = createTRPCRouter({
|
||||
app: appRouter,
|
||||
board: boardRouter,
|
||||
info: infoRouter,
|
||||
invite: inviteRouter,
|
||||
serverSettings: serverSettingsRouter,
|
||||
const MCP_TOOL_ALLOWLIST = {
|
||||
query: [
|
||||
"apiKeys_getAll",
|
||||
"app_all",
|
||||
"app_byId",
|
||||
"app_getPaginated",
|
||||
"app_search",
|
||||
"bazarr_getBadges",
|
||||
"beszel_getAlerts",
|
||||
"beszel_getSystems",
|
||||
"beszel_getSystemStats",
|
||||
"board_getAllBoards",
|
||||
"calendar_findAllEvents",
|
||||
"customWidget_get",
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_legacyMigrationPrompt",
|
||||
"customWidget_list",
|
||||
"customWidget_previewJournal",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_workshopGet",
|
||||
"customWidget_workshopSearch",
|
||||
"dnsHole_summary",
|
||||
"docker_getContainers",
|
||||
"docker_logs",
|
||||
"downloads_getJobsAndStatuses",
|
||||
"healthMonitoring_getClusterHealthStatus",
|
||||
"healthMonitoring_getSystemHealthStatus",
|
||||
"healthMonitoring_listStorageVolumes",
|
||||
"icon_findIcons",
|
||||
"info_getInfo",
|
||||
"integration_all",
|
||||
"integration_byId",
|
||||
"integration_getKinds",
|
||||
"integration_getMediaRequestOptions",
|
||||
"integration_mediaRequestSearchTargets",
|
||||
"integration_search",
|
||||
"integration_searchInIntegration",
|
||||
"integration_searchMediaRequests",
|
||||
"invite_getAll",
|
||||
"mediaRequests_getLatestRequests",
|
||||
"mediaRequests_getStats",
|
||||
"mediaServer_getCurrentStreams",
|
||||
"patchmon_getStats",
|
||||
"serverSettings_getBoardSettings",
|
||||
"smartHome_entityState",
|
||||
"widgetSecrets_getConfiguredKinds",
|
||||
],
|
||||
mutation: [
|
||||
"app_create",
|
||||
"app_delete",
|
||||
"app_update",
|
||||
"board_addItem",
|
||||
"board_changeBoardVisibility",
|
||||
"board_createBoard",
|
||||
"board_deleteBoard",
|
||||
"board_duplicateBoard",
|
||||
"board_renameBoard",
|
||||
"board_savePartialBoardSettings",
|
||||
"board_setHomeBoard",
|
||||
"board_setMobileHomeBoard",
|
||||
"customWidget_delete",
|
||||
"customWidget_previewAction",
|
||||
"customWidget_templatePatch",
|
||||
"dnsHole_disable",
|
||||
"dnsHole_enable",
|
||||
"docker_removeAll",
|
||||
"docker_restartAll",
|
||||
"docker_startAll",
|
||||
"docker_stopAll",
|
||||
"downloads_pause",
|
||||
"downloads_resume",
|
||||
"integration_create",
|
||||
"integration_delete",
|
||||
"integration_requestMedia",
|
||||
"invite_createInvite",
|
||||
"invite_deleteInvite",
|
||||
"mediaRequests_answerRequest",
|
||||
"serverSettings_updateBoardSettings",
|
||||
"smartHome_executeAutomation",
|
||||
"smartHome_switchEntity",
|
||||
],
|
||||
secret: [
|
||||
"apiKeys_create",
|
||||
"apiKeys_delete",
|
||||
"customWidget_configurationRequestUser",
|
||||
"customWidget_create",
|
||||
"customWidget_migrateLegacy",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_secretSet",
|
||||
"customWidget_sourceConfigure",
|
||||
"customWidget_update",
|
||||
"customWidget_workshopInstall",
|
||||
"widgetSecrets_deleteSecret",
|
||||
"widgetSecrets_setSecret",
|
||||
],
|
||||
} as const;
|
||||
|
||||
type ToolClassification = keyof typeof MCP_TOOL_ALLOWLIST;
|
||||
|
||||
function expectedToolInventory() {
|
||||
return Object.entries(MCP_TOOL_ALLOWLIST)
|
||||
.flatMap(([classification, names]) =>
|
||||
names.map((name) => ({ name, classification: classification as ToolClassification })),
|
||||
)
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
function actualToolInventory() {
|
||||
const secretTools = new Set<string>(MCP_TOOL_ALLOWLIST.secret);
|
||||
const procedures = mcpRouter["_def"].procedures as unknown as Record<
|
||||
string,
|
||||
{ _def?: { type?: "query" | "mutation" } }
|
||||
>;
|
||||
return extractToolsFromProcedures(mcpRouter)
|
||||
.map((tool) => {
|
||||
const procedure = procedures[tool.pathInRouter.join(".")];
|
||||
const type = procedure?.["_def"]?.type;
|
||||
if (type !== "query" && type !== "mutation") throw new Error(`Unable to classify MCP tool '${tool.name}'`);
|
||||
return {
|
||||
name: tool.name,
|
||||
classification: secretTools.has(tool.name) ? ("secret" as const) : type,
|
||||
};
|
||||
})
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
describe("production MCP router", () => {
|
||||
test("matches the reviewed tool and permission inventory exactly", () => {
|
||||
expect(actualToolInventory()).toEqual(expectedToolInventory());
|
||||
});
|
||||
|
||||
test("keeps every secret-bearing tool behind a mutation procedure", () => {
|
||||
const tools = extractToolsFromProcedures(mcpRouter);
|
||||
const procedures = mcpRouter["_def"].procedures as unknown as Record<
|
||||
string,
|
||||
{ _def?: { type?: "query" | "mutation" } }
|
||||
>;
|
||||
for (const name of MCP_TOOL_ALLOWLIST.secret) {
|
||||
const tool = tools.find((candidate) => candidate.name === name);
|
||||
expect(tool, `Missing reviewed secret tool '${name}'`).toBeDefined();
|
||||
const procedure = tool ? procedures[tool.pathInRouter.join(".")] : undefined;
|
||||
expect(procedure?.["_def"]?.type, `Secret tool '${name}' must remain a mutation`).toBe("mutation");
|
||||
}
|
||||
});
|
||||
|
||||
test("gives every production tool a description", () => {
|
||||
const tools = extractToolsFromProcedures(mcpRouter);
|
||||
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("MCP tools should be extractable from the router", () => {
|
||||
const act = () => extractToolsFromProcedures(mcpTestRouter);
|
||||
describe("custom widget authoring procedure access", () => {
|
||||
const unauthenticatedCaller = mcpRouter.createCaller({
|
||||
db: null as never,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
});
|
||||
|
||||
expect(act).not.toThrow();
|
||||
});
|
||||
|
||||
test("MCP tools should contain expected procedures", () => {
|
||||
const tools = extractToolsFromProcedures(mcpTestRouter);
|
||||
const toolNames = tools.map((tool) => tool.name);
|
||||
|
||||
expect(tools.length).toBeGreaterThan(0);
|
||||
expect(toolNames).toContain("app_all");
|
||||
expect(toolNames).toContain("app_byId");
|
||||
expect(toolNames).toContain("app_create");
|
||||
expect(toolNames).toContain("board_savePartialBoardSettings");
|
||||
expect(toolNames).toContain("board_duplicateBoard");
|
||||
expect(toolNames).toContain("info_getInfo");
|
||||
expect(toolNames).toContain("invite_getAll");
|
||||
expect(toolNames).toContain("serverSettings_getBoardSettings");
|
||||
expect(toolNames).toContain("serverSettings_updateBoardSettings");
|
||||
});
|
||||
|
||||
test("MCP tools should have descriptions", () => {
|
||||
const tools = extractToolsFromProcedures(mcpTestRouter);
|
||||
|
||||
for (const tool of tools) {
|
||||
expect(tool.description, `Tool ${tool.name} should have a description`).toBeTruthy();
|
||||
}
|
||||
test("rejects every authoring procedure without a session", async () => {
|
||||
const calls = [
|
||||
unauthenticatedCaller.customWidget.schema(),
|
||||
unauthenticatedCaller.customWidget.getAuthoringPrompt(),
|
||||
unauthenticatedCaller.customWidget.getSkill(),
|
||||
unauthenticatedCaller.customWidget.list(),
|
||||
unauthenticatedCaller.customWidget.validate({ widget: {} }),
|
||||
unauthenticatedCaller.customWidget.secretSet({
|
||||
definitionId: "widget",
|
||||
secret: { sourceId: "default", kind: "apiKey", value: "secret" },
|
||||
}),
|
||||
];
|
||||
for (const call of calls) {
|
||||
await expect(call).rejects.toEqual(expect.objectContaining<Partial<TRPCError>>({ code: "UNAUTHORIZED" }));
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects authoring and secret tools for authenticated non-admins", async () => {
|
||||
const nonAdminCaller = mcpRouter.createCaller({
|
||||
db: null as never,
|
||||
deviceType: undefined,
|
||||
session: { user: { id: "user-1", permissions: ["board-modify-all"] } } as never,
|
||||
});
|
||||
const calls = [
|
||||
nonAdminCaller.customWidget.schema(),
|
||||
nonAdminCaller.customWidget.getAuthoringPrompt(),
|
||||
nonAdminCaller.customWidget.getSkill(),
|
||||
nonAdminCaller.customWidget.secretSet({
|
||||
definitionId: "widget",
|
||||
secret: { sourceId: "default", kind: "apiKey", value: "secret" },
|
||||
}),
|
||||
];
|
||||
for (const call of calls) {
|
||||
await expect(call).rejects.toEqual(expect.objectContaining<Partial<TRPCError>>({ code: "FORBIDDEN" }));
|
||||
}
|
||||
});
|
||||
|
||||
test("allows admins to read authoring resources", async () => {
|
||||
const adminCaller = mcpRouter.createCaller({
|
||||
db: null as never,
|
||||
deviceType: undefined,
|
||||
session: { user: { id: "admin-1", permissions: ["admin"] } } as never,
|
||||
});
|
||||
await expect(adminCaller.customWidget.schema()).resolves.toMatchObject({ type: "object" });
|
||||
await expect(adminCaller.customWidget.getAuthoringPrompt()).resolves.toMatchObject({
|
||||
version: 2,
|
||||
prompt: expect.any(String),
|
||||
});
|
||||
await expect(adminCaller.customWidget.getSkill()).resolves.toMatchObject({
|
||||
name: expect.any(String),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,65 +1,20 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { boards, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import {
|
||||
isPersistableWidgetQueryKey,
|
||||
dashboardSupportingQueryPolicies,
|
||||
isWidgetDataQueryKey,
|
||||
isWidgetDataTrpcPath,
|
||||
queryCacheDefaultRefetchIntervalMs,
|
||||
queryCacheDefaultStaleTimeMs,
|
||||
queryCacheMaxValueBytes,
|
||||
queryCacheMetadataStaleTimeMs,
|
||||
} from "@homarr/api/query-cache";
|
||||
|
||||
import { queryCacheRouter } from "../router/query-cache";
|
||||
|
||||
const redisMock = vi.hoisted(() => {
|
||||
const values = new Map<string, string>();
|
||||
|
||||
return {
|
||||
values,
|
||||
setQueryCacheAsync: vi.fn(
|
||||
async (_userId: string, _boardId: string, value: string, _ttlMs: number, maxValueBytes: number) => {
|
||||
if (Buffer.byteLength(value, "utf8") > maxValueBytes) return false;
|
||||
values.set(`${_userId}:${_boardId}`, value);
|
||||
return true;
|
||||
},
|
||||
),
|
||||
removeQueryCacheAsync: vi.fn(async (_userId: string, _boardId: string) => {
|
||||
values.delete(`${_userId}:${_boardId}`);
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@homarr/redis", () => ({
|
||||
setQueryCacheAsync: redisMock.setQueryCacheAsync,
|
||||
removeQueryCacheAsync: redisMock.removeQueryCacheAsync,
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
redisMock.values.clear();
|
||||
redisMock.setQueryCacheAsync.mockClear();
|
||||
redisMock.removeQueryCacheAsync.mockClear();
|
||||
});
|
||||
|
||||
const createSession = (userId = createId()): Session => ({
|
||||
user: {
|
||||
id: userId,
|
||||
permissions: [],
|
||||
colorScheme: "light",
|
||||
},
|
||||
expires: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const insertUserAsync = async (db: Database, id: string) => {
|
||||
await db.insert(users).values({ id });
|
||||
};
|
||||
|
||||
describe("isPersistableWidgetQueryKey", () => {
|
||||
describe("isWidgetDataQueryKey", () => {
|
||||
test.each([
|
||||
[[["widget", "calendar", "findAllEvents"], { type: "query" }], true],
|
||||
[[["app", "byId"], { type: "query" }], true],
|
||||
@@ -72,77 +27,22 @@ describe("isPersistableWidgetQueryKey", () => {
|
||||
[[["app", "selectable"], { type: "query" }], false],
|
||||
[[["board", "getBoardByName"], { type: "query" }], false],
|
||||
[["widget"], false],
|
||||
])("matches persist filter for %j", (queryKey, expected) => {
|
||||
expect(isPersistableWidgetQueryKey(queryKey)).toBe(expected);
|
||||
])("matches widget data queries for %j", (queryKey, expected) => {
|
||||
expect(isWidgetDataQueryKey(queryKey)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("queryCacheRouter", () => {
|
||||
test("stores and removes data for a board viewer", async () => {
|
||||
const db = createDb();
|
||||
const session = createSession();
|
||||
await insertUserAsync(db, session.user.id);
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: session.user.id, isPublic: false });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session });
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value: "cached-value" })).resolves.toEqual({
|
||||
stored: true,
|
||||
});
|
||||
expect(redisMock.setQueryCacheAsync).toHaveBeenCalledWith(
|
||||
session.user.id,
|
||||
"board-1",
|
||||
"cached-value",
|
||||
expect.any(Number),
|
||||
queryCacheMaxValueBytes,
|
||||
);
|
||||
|
||||
await caller.removeItem({ boardId: "board-1" });
|
||||
expect(redisMock.removeQueryCacheAsync).toHaveBeenCalledWith(session.user.id, "board-1");
|
||||
});
|
||||
|
||||
test("does not touch Redis when board access is denied", async () => {
|
||||
const db = createDb();
|
||||
await insertUserAsync(db, "owner");
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: "owner", isPublic: false });
|
||||
|
||||
redisMock.setQueryCacheAsync.mockClear();
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session: createSession("other-user") });
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value: "cached-value" })).rejects.toThrow("Board not found");
|
||||
expect(redisMock.setQueryCacheAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("scopes anonymous public-board cache entries by anonymous user", async () => {
|
||||
const db = createDb();
|
||||
await insertUserAsync(db, "owner");
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: "owner", isPublic: true });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session: null });
|
||||
|
||||
await caller.setItem({ boardId: "board-1", value: "cached-value" });
|
||||
|
||||
expect(redisMock.setQueryCacheAsync).toHaveBeenCalledWith(
|
||||
"anonymous",
|
||||
"board-1",
|
||||
"cached-value",
|
||||
expect.any(Number),
|
||||
queryCacheMaxValueBytes,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects oversized values", async () => {
|
||||
const db = createDb();
|
||||
const session = createSession("user-1");
|
||||
await insertUserAsync(db, session.user.id);
|
||||
await db.insert(boards).values({ id: "board-1", name: "board", creatorId: session.user.id, isPublic: false });
|
||||
|
||||
const caller = queryCacheRouter.createCaller({ db, deviceType: undefined, session });
|
||||
const value = "x".repeat(queryCacheMaxValueBytes + 1);
|
||||
|
||||
await expect(caller.setItem({ boardId: "board-1", value })).resolves.toEqual({
|
||||
stored: false,
|
||||
});
|
||||
describe("isWidgetDataTrpcPath", () => {
|
||||
test.each([
|
||||
["widget.calendar.findAllEvents", true],
|
||||
["app.byIds", true],
|
||||
["integration.byIds", true],
|
||||
["docker.getContainers", true],
|
||||
["widget.app.ping", false],
|
||||
["widget.beszel.getSystemStats", false],
|
||||
["board.getBoardByName", false],
|
||||
])("classifies dashboard data path %s", (path, expected) => {
|
||||
expect(isWidgetDataTrpcPath(path)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -176,3 +76,38 @@ describe("query cache stale handling", () => {
|
||||
expect(queryFn).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dashboard supporting query policies", () => {
|
||||
test("bounds metadata staleness without adding per-widget timers", () => {
|
||||
expect(dashboardSupportingQueryPolicies).toEqual([
|
||||
{
|
||||
queryKey: [["app", "byId"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["app", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["integration", "byIds"]],
|
||||
refetchInterval: false,
|
||||
staleTime: queryCacheMetadataStaleTimeMs,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
},
|
||||
{
|
||||
queryKey: [["docker", "getContainers"]],
|
||||
refetchInterval: queryCacheDefaultRefetchIntervalMs,
|
||||
staleTime: queryCacheDefaultStaleTimeMs,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { cache } from "react";
|
||||
|
||||
import { db, eq } from "@homarr/db";
|
||||
import { users } from "@homarr/db/schema";
|
||||
|
||||
// Keep the authenticated user lookup shared across nested RSC layouts. React
|
||||
// clears this memo between requests, so authorization changes cannot leak.
|
||||
export const getRscUserSettingsAsync = cache(async (userId: string) =>
|
||||
db.query.users.findFirst({
|
||||
columns: {
|
||||
homeBoardId: true,
|
||||
mobileHomeBoardId: true,
|
||||
firstDayOfWeek: true,
|
||||
pingIconsEnabled: true,
|
||||
enableRightClickOnWidgets: true,
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
},
|
||||
where: eq(users.id, userId),
|
||||
}),
|
||||
);
|
||||
Reference in new issue
Block a user