Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

fix(boards): validate item layout bounds and repair invalid layouts in the editor (#7351)

Thomas689d59f94434
diff --git a/apps/docs/public/api/open-api-schema.json b/apps/docs/public/api/open-api-schema.json
index cbc6acae8..da21db286 100644
--- a/apps/docs/public/api/open-api-schema.json
+++ b/apps/docs/public/api/open-api-schema.json
@@ -2801,7 +2801,7 @@
"put": {
"operationId": "boardRouter-saveBoard",
"summary": "Save dashboard content",
- "description": "Save the editor's complete sections and items arrays, including widget options and placements. Omitted items and sections are removed. Requires modify access; Custom Widget placement changes require admin access.",
+ "description": "Save the editor's complete sections and items arrays, including widget options and placements. Omitted items and sections are removed. Placements must fit their parent section's columns in each layout. Requires modify access; Custom Widget placement changes require admin access.",
"tags": [
"boards"
],
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
index d2ef0ccd4..3bd244c08 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_header-actions.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { useRouter, useSearchParams } from "next/navigation";
import { Tooltip } from "@mantine/core";
@@ -11,6 +11,7 @@ import { IconDeviceFloppy, IconPencil, IconPencilOff, IconSettings, IconX } from
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { useEditMode } from "@homarr/boards/edit-mode";
+import { useUpdateBoard } from "@homarr/boards/updater";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { env } from "@homarr/common/env";
import { hotkeys } from "@homarr/definitions";
@@ -18,6 +19,7 @@ import { useConfirmModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
import { useBoardPermissions } from "~/components/board/permissions/client";
+import { normalizeBoardLayoutBounds } from "~/components/board/layout/normalize-board-layout-bounds";
import { loadGridEditorAsync, scheduleGridEditorWarmup } from "~/components/board/sections/grid/grid-editor-loader";
import { HeaderButton } from "~/components/layout/header/button";
import { TourTarget } from "~/components/layout/header/tour-target";
@@ -78,6 +80,7 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const [editorLoadState, setEditorLoadState] = useState<"scheduled" | "loading" | "ready" | "error">("scheduled");
const [isEnteringEditMode, setIsEnteringEditMode] = useState(false);
const board = useRequiredBoard();
+ const { updateBoard } = useUpdateBoard();
const utils = clientApi.useUtils();
const router = useRouter();
const searchParams = useSearchParams();
@@ -93,6 +96,10 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
const latestBoardRef = useRef(board);
latestBoardRef.current = board;
+ useLayoutEffect(() => {
+ if (isEditMode) updateBoard(normalizeBoardLayoutBounds);
+ }, [isEditMode, updateBoard]);
+
const { mutate: saveBoard, isPending } = clientApi.board.saveBoard.useMutation({
onMutate(boardToSave) {
boardToSave.items.forEach(({ id }) => notifications.hide(`board-item-created:${id}`));
@@ -108,10 +115,12 @@ const EditModeMenu = ({ demoReadOnly }: { demoReadOnly: boolean }) => {
close();
if (returnToLayoutSettings) router.push(`/boards/${board.name}/settings?tab=layout`);
},
- onError() {
+ onError(error) {
+ let message = t("notification.error.message");
+ if (error.data?.isBoardLayoutBoundsError) message = error.message;
showErrorNotification({
title: tCommon("notification.update.error"),
- message: t("notification.error.message"),
+ message,
});
},
});
diff --git a/apps/nextjs/src/app/api/mcp/_handler.ts b/apps/nextjs/src/app/api/mcp/_handler.ts
index d057d8b4e..fefff9d6e 100644
--- a/apps/nextjs/src/app/api/mcp/_handler.ts
+++ b/apps/nextjs/src/app/api/mcp/_handler.ts
@@ -21,6 +21,7 @@ import {
} from "@homarr/custom-widgets/authoring-resources";
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { db } from "@homarr/db";
+import { BoardLayoutBoundsError } from "@homarr/validation/board-layout-bounds-error";
import { getPackageVersion } from "~/versions/package-reader";
import { getSafeAssistantToolError } from "../assistant/chat/assistant-tool-error";
@@ -212,6 +213,7 @@ const SAFE_ERROR_MESSAGES: Record<string, string> = {
};
function sanitizeErrorMessage(error: unknown, toolName: string): string {
+ if (error instanceof Error && error.cause instanceof BoardLayoutBoundsError) return error.cause.message;
if (toolName.startsWith("customWidget_")) return getSafeAssistantToolError(error, { toolName });
if (error instanceof Error && "code" in error) {
const trpcCode = (error as Error & { code: string }).code;
diff --git a/apps/nextjs/src/components/board/layout/normalize-board-layout-bounds.ts b/apps/nextjs/src/components/board/layout/normalize-board-layout-bounds.ts
new file mode 100644
index 000000000..26412ea57
--- /dev/null
+++ b/apps/nextjs/src/components/board/layout/normalize-board-layout-bounds.ts
@@ -0,0 +1,61 @@
+import { getBoardSectionColumnCount } from "@homarr/validation/board-layout-bounds";
+
+import type { Board } from "~/app/[locale]/boards/_types";
+
+export const normalizeBoardLayoutBounds = (board: Board): Board => {
+ let items = board.items;
+ let sections = board.sections;
+ let hasChanges = false;
+
+ for (const layout of board.layouts) {
+ const visited = new Set<string>();
+ const normalizeSection = (sectionId: string, columnCount: number) => {
+ if (columnCount < 1 || visited.has(sectionId)) return;
+ visited.add(sectionId);
+
+ const normalizePlacement = <T extends { xOffset: number; width: number }>(placement: T): T => {
+ const width = Math.max(1, Math.min(placement.width, columnCount));
+ const xOffset = Math.max(0, Math.min(placement.xOffset, columnCount - width));
+ if (width === placement.width && xOffset === placement.xOffset) return placement;
+ hasChanges = true;
+ return { ...placement, width, xOffset };
+ };
+
+ items = items.map((item) => {
+ const layouts = item.layouts.map((placement) => {
+ if (placement.layoutId !== layout.id || placement.sectionId !== sectionId) return placement;
+ return normalizePlacement(placement);
+ });
+ if (layouts.every((placement, index) => placement === item.layouts[index])) return item;
+ return { ...item, layouts };
+ });
+
+ sections = sections.map((section) => {
+ if (section.kind !== "container") return section;
+ const layouts = section.layouts.map((placement) => {
+ if (placement.layoutId !== layout.id || placement.parentSectionId !== sectionId) return placement;
+ return normalizePlacement(placement);
+ });
+ if (layouts.every((placement, index) => placement === section.layouts[index])) return section;
+ return { ...section, layouts };
+ });
+
+ for (const section of sections) {
+ if (section.kind !== "container") continue;
+ const placement = section.layouts.find(
+ (candidate) => candidate.layoutId === layout.id && candidate.parentSectionId === sectionId,
+ );
+ if (placement) normalizeSection(section.id, placement.width);
+ }
+ };
+
+ for (const section of sections) {
+ if (section.kind !== "empty") continue;
+ const columnCount = getBoardSectionColumnCount(board, layout.id, section.id);
+ if (columnCount !== null) normalizeSection(section.id, columnCount);
+ }
+ }
+
+ if (!hasChanges) return board;
+ return { ...board, items, sections };
+};
diff --git a/packages/api/src/router/board.ts b/packages/api/src/router/board.ts
index 861deb3b5..885d6bbac 100644
--- a/packages/api/src/router/board.ts
+++ b/packages/api/src/router/board.ts
@@ -69,6 +69,8 @@ import {
boardSummarySchema,
updateBoardItemLayoutSchema,
} from "@homarr/validation/board";
+import { getBoardLayoutBoundsIssue, getBoardPlacementBoundsIssue } from "@homarr/validation/board-layout-bounds";
+import { BoardLayoutBoundsError } from "@homarr/validation/board-layout-bounds-error";
import { byIdSchema } from "@homarr/validation/common";
import { zodUnionFromArray } from "@homarr/validation/enums";
import type { BoardItemAdvancedOptions } from "@homarr/validation/shared";
@@ -142,6 +144,11 @@ const doBoardItemPlacementsOverlap = (left: BoardItemPlacementRectangle, right:
left.xOffset < right.xOffset + right.width &&
left.xOffset + left.width > right.xOffset;
+const throwIfBoardLayoutBoundsInvalid = (issue: string | null) => {
+ if (!issue) return;
+ throw new TRPCError({ code: "BAD_REQUEST", message: issue, cause: new BoardLayoutBoundsError(issue) });
+};
+
interface WidgetConfiguration {
id: string;
kind: WidgetKind;
@@ -1710,12 +1717,12 @@ export const boardRouter = createTRPCRouter({
protect: true,
summary: "Save dashboard content",
description:
- "Save the editor's complete sections and items arrays, including widget options and placements. Omitted items and sections are removed. Requires modify access; Custom Widget placement changes require admin access.",
+ "Save the editor's complete sections and items arrays, including widget options and placements. Omitted items and sections are removed. Placements must fit their parent section's columns in each layout. Requires modify access; Custom Widget placement changes require admin access.",
},
mcp: {
enabled: true,
description:
- "Save complete dashboard sections and items, including widget options and placements. Omitted entries are removed. Read current content with board_getBoardByName first. Requires modify access; Custom Widget placement changes require admin access.",
+ "Save complete dashboard sections and items, including widget options and placements. Omitted entries are removed. Placements must fit their parent section's columns in each layout. Read current content with board_getBoardByName first. Requires modify access; Custom Widget placement changes require admin access.",
},
})
.input(boardSaveSchema)
@@ -1724,6 +1731,7 @@ 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);
+ throwIfBoardLayoutBoundsInvalid(getBoardLayoutBoundsIssue({ ...input, layouts: dbBoard.layouts }));
await validateWidgetConfigurationsAsync(ctx, input.items, dbBoard.items);
throwIfCustomWidgetPlacementChangeForbidden({
isAdmin: ctx.session.user.permissions.includes("admin"),
@@ -2388,6 +2396,12 @@ export const boardRouter = createTRPCRouter({
};
});
+ for (const placement of layoutRows) {
+ throwIfBoardLayoutBoundsInvalid(
+ getBoardPlacementBoundsIssue(board, placement, placement.sectionId, `Item "${itemId}"`),
+ );
+ }
+
await ctx.db.insert(items).values({
id: itemId,
boardId: input.boardId,
@@ -2452,18 +2466,8 @@ export const boardRouter = createTRPCRouter({
throw new TRPCError({ code: "NOT_FOUND", message: "Item section not found on this board" });
}
- let columnCount: number;
- if (section.kind === "empty") {
- columnCount = getBoardLaneColumnCount(layout, getRootSectionLane(section.xOffset));
- } else {
- const sectionLayout = section.layouts.find((candidate) => candidate.layoutId === layout.id);
- if (!sectionLayout) {
- throw new TRPCError({ code: "BAD_REQUEST", message: "Item section has no layout at this breakpoint" });
- }
- columnCount = sectionLayout.width;
- }
-
- if (input.xOffset + input.width > columnCount || input.yOffset + input.height > 32767) {
+ throwIfBoardLayoutBoundsInvalid(getBoardPlacementBoundsIssue(board, input, section.id, `Item "${item.id}"`));
+ if (input.yOffset + input.height > 32767) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Item layout exceeds its section bounds" });
}
diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.ts
index 4d53c79fe..e891cfcfb 100644
--- a/packages/api/src/trpc.ts
+++ b/packages/api/src/trpc.ts
@@ -18,6 +18,7 @@ import type { DeviceType, RequestIdentity } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { db } from "@homarr/db";
import type { GroupPermissionKey, OnboardingStep } from "@homarr/definitions";
+import { BoardLayoutBoundsError } from "@homarr/validation/board-layout-bounds-error";
import { env } from "./env";
import { getOnboardingClaimTokenFromCookieHeader, isClaimOnlyOnboardingAccessAllowedAsync } from "./onboarding-claim";
@@ -84,6 +85,7 @@ const t = initTRPC
...shape.data,
zodError: error.cause instanceof ZodError ? error.cause.flatten() : null,
error: error.cause instanceof FlattenError ? error.cause.flatten() : null,
+ isBoardLayoutBoundsError: error.cause instanceof BoardLayoutBoundsError,
},
}),
});
diff --git a/packages/validation/src/board-layout-bounds-error.ts b/packages/validation/src/board-layout-bounds-error.ts
new file mode 100644
index 000000000..e97595a27
--- /dev/null
+++ b/packages/validation/src/board-layout-bounds-error.ts
@@ -0,0 +1 @@
+export class BoardLayoutBoundsError extends Error {}
diff --git a/packages/validation/src/board-layout-bounds.ts b/packages/validation/src/board-layout-bounds.ts
new file mode 100644
index 000000000..30bc0121c
--- /dev/null
+++ b/packages/validation/src/board-layout-bounds.ts
@@ -0,0 +1,82 @@
+import type { LayoutRole, SectionKind } from "@homarr/definitions";
+import { getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
+
+interface BoardLayoutBoundsContext {
+ layouts: readonly {
+ id: string;
+ name: string;
+ columnCount: number;
+ leftGutterColumnCount?: number | null;
+ rightGutterColumnCount?: number | null;
+ role?: LayoutRole;
+ }[];
+ sections: readonly {
+ id: string;
+ kind: SectionKind;
+ xOffset?: number | null;
+ layouts?: readonly { layoutId: string; width: number }[];
+ }[];
+}
+
+export const getBoardSectionColumnCount = (
+ board: BoardLayoutBoundsContext,
+ layoutId: string,
+ sectionId: string,
+): number | null => {
+ const layout = board.layouts.find((candidate) => candidate.id === layoutId);
+ const section = board.sections.find((candidate) => candidate.id === sectionId);
+ if (!layout || !section) return null;
+ if (section.kind === "empty") return getBoardLaneColumnCount(layout, getRootSectionLane(section.xOffset));
+ return section.layouts?.find((candidate) => candidate.layoutId === layoutId)?.width ?? null;
+};
+
+export const getBoardPlacementBoundsIssue = (
+ board: BoardLayoutBoundsContext,
+ placement: { layoutId: string; xOffset: number; width: number },
+ sectionId: string,
+ name: string,
+): string | null => {
+ const columnCount = getBoardSectionColumnCount(board, placement.layoutId, sectionId);
+ const layoutName = board.layouts.find((layout) => layout.id === placement.layoutId)?.name ?? placement.layoutId;
+ if (columnCount === null) {
+ return `${name} references an unknown layout or section in layout "${layoutName}"`;
+ }
+ if (placement.xOffset < 0 || placement.width < 1 || placement.xOffset + placement.width > columnCount) {
+ return `${name} exceeds section "${sectionId}" bounds in layout "${layoutName}": xOffset ${placement.xOffset} + width ${placement.width} must fit within ${columnCount} columns`;
+ }
+ return null;
+};
+
+export const getBoardLayoutBoundsIssue = (
+ board: BoardLayoutBoundsContext & {
+ items: readonly {
+ id: string;
+ layouts: readonly { layoutId: string; sectionId: string; xOffset: number; width: number }[];
+ }[];
+ sections: readonly {
+ id: string;
+ kind: SectionKind;
+ layouts?: readonly { layoutId: string; parentSectionId: string | null; xOffset: number; width: number }[];
+ }[];
+ },
+): string | null => {
+ for (const section of board.sections) {
+ if (section.kind !== "container") continue;
+ for (const placement of section.layouts ?? []) {
+ const issue = getBoardPlacementBoundsIssue(
+ board,
+ placement,
+ placement.parentSectionId ?? "",
+ `Section "${section.id}"`,
+ );
+ if (issue) return issue;
+ }
+ }
+ for (const item of board.items) {
+ for (const placement of item.layouts) {
+ const issue = getBoardPlacementBoundsIssue(board, placement, placement.sectionId, `Item "${item.id}"`);
+ if (issue) return issue;
+ }
+ }
+ return null;
+};