harden v2 custom widgets and workshop
This commit is contained in:
1 parent
e8a2c87c2d
commit
723b46926a
194 files changed
+44862
-1265
No files matched your search
@@ -10,6 +10,7 @@ import { WidgetCustomWidgetSelectInput } from "./widget-custom-widget-select-inp
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
available: [] as Array<Record<string, unknown>>,
|
||||
permissions: ["admin"] as string[],
|
||||
setFieldValue: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -62,6 +63,10 @@ vi.mock("@homarr/api/client", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/auth/client", () => ({
|
||||
useSession: () => ({ data: { user: { permissions: mocks.permissions } } }),
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/boards/context", () => ({
|
||||
useOptionalBoard: () => ({ id: "board-1" }),
|
||||
}));
|
||||
@@ -72,6 +77,7 @@ vi.mock("@homarr/translation/client", () => ({
|
||||
migrationRequired: "Migration required",
|
||||
migrationDescription: "Copy its redacted prompt to an LLM and import the returned v2 JSON.",
|
||||
manageMigration: "Open Manage custom widgets",
|
||||
contactAdmin: "Contact an administrator.",
|
||||
})[key] ?? key,
|
||||
}));
|
||||
|
||||
@@ -90,6 +96,7 @@ let host: HTMLDivElement;
|
||||
beforeEach(() => {
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
mocks.available = [];
|
||||
mocks.permissions = ["admin"];
|
||||
mocks.setFieldValue.mockReset();
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -137,4 +144,26 @@ describe("custom widget picker migration status", () => {
|
||||
expect(host.textContent).toContain("Copy its redacted prompt to an LLM");
|
||||
expect(host.querySelector('a[href="/manage/custom-widgets"]')?.textContent).toBe("Open Manage custom widgets");
|
||||
});
|
||||
|
||||
it("tells non-admins to contact an administrator without linking management", async () => {
|
||||
mocks.permissions = ["board-modify-all"];
|
||||
mocks.available = [
|
||||
{
|
||||
id: "legacy-widget",
|
||||
name: "Legacy status",
|
||||
description: "Old API widget",
|
||||
iconUrl: null,
|
||||
sources: [],
|
||||
requestCapabilities: [],
|
||||
defaultOptions: {},
|
||||
updatedAt: new Date(0),
|
||||
migrationRequired: true,
|
||||
},
|
||||
];
|
||||
|
||||
await renderInput();
|
||||
|
||||
expect(host.textContent).toContain("Contact an administrator.");
|
||||
expect(host.querySelector('a[href="/manage/custom-widgets"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { IconAlertTriangle, IconApi } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
@@ -32,6 +33,8 @@ export const WidgetCustomWidgetSelectInput = ({
|
||||
}: CommonWidgetInputProps<"customWidgetSelect">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const labels = useScopedI18n("widget.customApi.picker");
|
||||
const { data: session } = useSession();
|
||||
const isAdmin = session?.user.permissions.includes("admin") ?? false;
|
||||
const form = useFormContext();
|
||||
const board = useOptionalBoard();
|
||||
const currentValue = form.values.options[property] as string;
|
||||
@@ -153,9 +156,15 @@ export const WidgetCustomWidgetSelectInput = ({
|
||||
title={labels("migrationRequired")}
|
||||
>
|
||||
<Text size="xs">{labels("migrationDescription")}</Text>
|
||||
<Anchor component={Link} href="/manage/custom-widgets" size="xs" fw={600}>
|
||||
{labels("manageMigration")}
|
||||
</Anchor>
|
||||
{isAdmin ? (
|
||||
<Anchor component={Link} href="/manage/custom-widgets" size="xs" fw={600}>
|
||||
{labels("manageMigration")}
|
||||
</Anchor>
|
||||
) : (
|
||||
<Text size="xs" fw={600}>
|
||||
{labels("contactAdmin")}
|
||||
</Text>
|
||||
)}
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Button, Center, Loader, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
@@ -21,6 +22,8 @@ export default function CustomApiWidget({
|
||||
}: WidgetComponentProps<"customApi">) {
|
||||
const t = useScopedI18n("widget.customApi");
|
||||
const tCustomJsx = useScopedI18n("widget.customApi.customJsx");
|
||||
const { data: session } = useSession();
|
||||
const isAdmin = session?.user.permissions.includes("admin") ?? false;
|
||||
const definitionId = options.definitionId;
|
||||
const safeInterval = Number.isFinite(options.refreshInterval) ? options.refreshInterval : 30;
|
||||
const intervalMs = Math.max(1_000, safeInterval * 1_000);
|
||||
@@ -50,22 +53,26 @@ export default function CustomApiWidget({
|
||||
if (isEditMode && errorCode === "NOT_FOUND") {
|
||||
return <Unavailable message={t("editModePending")} />;
|
||||
}
|
||||
const isUnavailable = errorCode === "NOT_FOUND" || errorCode === "FORBIDDEN";
|
||||
const isFeatureDisabled = errorCode === "SERVICE_UNAVAILABLE";
|
||||
const isUnavailable = errorCode === "NOT_FOUND" || errorCode === "FORBIDDEN" || isFeatureDisabled;
|
||||
return (
|
||||
<Unavailable
|
||||
message={
|
||||
migrationRequired
|
||||
? t("migrationRequired")
|
||||
: isUnavailable
|
||||
? t("definitionNotFound")
|
||||
: errorCode === "PRECONDITION_FAILED"
|
||||
? t("configurationNeedsRepair")
|
||||
: tCustomJsx("requestFailed")
|
||||
: isFeatureDisabled
|
||||
? t("temporarilyDisabled")
|
||||
: isUnavailable
|
||||
? t("definitionNotFound")
|
||||
: errorCode === "PRECONDITION_FAILED"
|
||||
? t("configurationNeedsRepair")
|
||||
: tCustomJsx("requestFailed")
|
||||
}
|
||||
danger={!isUnavailable && !migrationRequired}
|
||||
removeLabel={isUnavailable ? t("removeFromBoard") : undefined}
|
||||
actionLabel={migrationRequired ? t("manageMigration") : undefined}
|
||||
actionHref={migrationRequired ? "/manage/custom-widgets" : undefined}
|
||||
removeLabel={isUnavailable && !isFeatureDisabled ? t("removeFromBoard") : undefined}
|
||||
actionLabel={migrationRequired && isAdmin ? t("manageMigration") : undefined}
|
||||
actionHref={migrationRequired && isAdmin ? "/manage/custom-widgets" : undefined}
|
||||
supplementaryMessage={migrationRequired && !isAdmin ? t("contactAdmin") : undefined}
|
||||
onRemove={removeItem}
|
||||
/>
|
||||
);
|
||||
@@ -78,6 +85,7 @@ export default function CustomApiWidget({
|
||||
...query.data,
|
||||
widgetDefinitionId: definitionId,
|
||||
widgetItemId: itemId,
|
||||
canInvalidateQueries: Boolean(session),
|
||||
isEditMode,
|
||||
}}
|
||||
/>
|
||||
@@ -90,6 +98,7 @@ function Unavailable({
|
||||
removeLabel,
|
||||
actionLabel,
|
||||
actionHref,
|
||||
supplementaryMessage,
|
||||
onRemove,
|
||||
}: {
|
||||
message: string;
|
||||
@@ -97,6 +106,7 @@ function Unavailable({
|
||||
removeLabel?: string;
|
||||
actionLabel?: string;
|
||||
actionHref?: string;
|
||||
supplementaryMessage?: string;
|
||||
onRemove?: () => void;
|
||||
}) {
|
||||
return (
|
||||
@@ -106,6 +116,11 @@ function Unavailable({
|
||||
<Text c="dimmed" size="sm" ta="center">
|
||||
{message}
|
||||
</Text>
|
||||
{supplementaryMessage && (
|
||||
<Text size="sm" fw={600} ta="center">
|
||||
{supplementaryMessage}
|
||||
</Text>
|
||||
)}
|
||||
{actionLabel && actionHref && (
|
||||
<Button component={Link} href={actionHref} size="compact-sm" color="yellow" variant="light">
|
||||
{actionLabel}
|
||||
|
||||
@@ -69,6 +69,7 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
||||
previewSessionId={previewSessionId}
|
||||
previewLiveActions={data.previewLiveActions === true}
|
||||
queriesDisabled={data.queriesDisabled === true}
|
||||
canInvalidateQueries={data.canInvalidateQueries === true}
|
||||
isEditMode={data.isEditMode === true}
|
||||
requestCapabilities={capabilities}
|
||||
setQueryState={publishQueryState}
|
||||
|
||||
@@ -15,12 +15,15 @@ import { showErrorNotification, showSuccessNotification } from "@homarr/notifica
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { resolveCustomWidgetInvalidationTargets } from "./widget-invalidation";
|
||||
|
||||
interface WidgetDefinitionProviderProps {
|
||||
itemId?: string;
|
||||
definitionId?: string;
|
||||
previewSessionId?: string;
|
||||
previewLiveActions?: boolean;
|
||||
queriesDisabled?: boolean;
|
||||
canInvalidateQueries?: boolean;
|
||||
isEditMode?: boolean;
|
||||
requestCapabilities?: readonly CustomJsxRequestCapability[];
|
||||
setQueryState?(requestId: string, value: CustomWidgetPublishedQueryState | null): void;
|
||||
@@ -64,6 +67,7 @@ export function InactiveWidgetDefinitionProvider({
|
||||
return (
|
||||
<CustomWidgetRuntimeProvider
|
||||
definitionId={definitionId}
|
||||
canInvalidateQueries={false}
|
||||
isEditMode={isEditMode ?? false}
|
||||
requestCapabilities={[]}
|
||||
port={INACTIVE_PORT}
|
||||
@@ -106,29 +110,85 @@ export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
|
||||
params: input.params,
|
||||
confirmed: input.confirmed,
|
||||
}),
|
||||
invalidate: async ({ itemId, previewSessionId, targets }) => {
|
||||
invalidate: async ({ itemId, previewSessionId, targets, refresh }) => {
|
||||
const invalidation = resolveCustomWidgetInvalidationTargets(props.requestCapabilities ?? [], targets);
|
||||
if (previewSessionId) {
|
||||
await queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey;
|
||||
return key[0] === "custom-widget" && key[1] === previewSessionId && targets.includes(String(key[2]));
|
||||
},
|
||||
});
|
||||
if (refresh && invalidation.requestIds.length > 0) {
|
||||
await fetchApi.customWidget.previewRefresh.mutate({
|
||||
sessionId: previewSessionId,
|
||||
requestIds: invalidation.requestIds,
|
||||
all: invalidation.all,
|
||||
});
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (invalidation.requestIds.length > 0) {
|
||||
tasks.push(
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey;
|
||||
return (
|
||||
key[0] === "custom-widget" &&
|
||||
key[1] === previewSessionId &&
|
||||
invalidation.requestIds.includes(String(key[2]))
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (invalidation.refreshParent) {
|
||||
tasks.push(
|
||||
...invalidation.loadRequestIds.map(async (requestId) => {
|
||||
try {
|
||||
const result = await fetchApi.customWidget.previewQuery.query({
|
||||
sessionId: previewSessionId,
|
||||
requestId,
|
||||
params: {},
|
||||
});
|
||||
props.setQueryState?.(requestId, {
|
||||
data: result.data,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
statusText: result.statusText,
|
||||
error: result.error,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
props.setQueryState?.(requestId, {
|
||||
data: null,
|
||||
status: { loading: false, ok: false, status: 0, error: messages.requestFailed },
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(tasks);
|
||||
return;
|
||||
}
|
||||
if (!itemId) return;
|
||||
if (targets.length === 0) return;
|
||||
const tasks: Promise<unknown>[] = [
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey;
|
||||
return key[0] === "custom-widget" && key[1] === itemId && targets.includes(String(key[2]));
|
||||
},
|
||||
}),
|
||||
];
|
||||
if (
|
||||
(props.requestCapabilities ?? []).some((request) => request.trigger === "load" && targets.includes(request.id))
|
||||
) {
|
||||
if (invalidation.requestIds.length === 0 && !invalidation.refreshParent) return;
|
||||
if (refresh && invalidation.requestIds.length > 0) {
|
||||
await fetchApi.widget.customApi.refreshQueries.mutate({
|
||||
itemId,
|
||||
requestIds: invalidation.requestIds,
|
||||
all: invalidation.all,
|
||||
});
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (invalidation.requestIds.length > 0) {
|
||||
tasks.push(
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
const key = query.queryKey;
|
||||
return (
|
||||
key[0] === "custom-widget" && key[1] === itemId && invalidation.requestIds.includes(String(key[2]))
|
||||
);
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (invalidation.refreshParent) {
|
||||
tasks.push(utils.widget.customApi.getData.invalidate({ itemId }));
|
||||
}
|
||||
await Promise.all(tasks);
|
||||
@@ -154,6 +214,7 @@ export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
|
||||
previewSessionId={props.previewSessionId}
|
||||
previewLiveActions={props.previewLiveActions}
|
||||
queriesDisabled={props.queriesDisabled}
|
||||
canInvalidateQueries={props.canInvalidateQueries ?? Boolean(props.previewSessionId)}
|
||||
isEditMode={props.isEditMode ?? false}
|
||||
requestCapabilities={props.requestCapabilities ?? []}
|
||||
port={port}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { CustomJsxRequestCapability } from "@homarr/custom-widgets/runtime";
|
||||
|
||||
import { resolveCustomWidgetInvalidationTargets } from "./widget-invalidation";
|
||||
|
||||
const capabilities: CustomJsxRequestCapability[] = [
|
||||
{
|
||||
id: "summary",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
trigger: "load",
|
||||
minimumBoardPermission: "view",
|
||||
},
|
||||
{
|
||||
id: "details",
|
||||
kind: "query",
|
||||
method: "GET",
|
||||
trigger: "manual",
|
||||
minimumBoardPermission: "view",
|
||||
},
|
||||
{
|
||||
id: "update",
|
||||
kind: "action",
|
||||
method: "POST",
|
||||
trigger: "manual",
|
||||
minimumBoardPermission: "modify",
|
||||
},
|
||||
];
|
||||
|
||||
describe("resolveCustomWidgetInvalidationTargets", () => {
|
||||
it("expands the refresh wildcard to every query and the parent load request", () => {
|
||||
expect(resolveCustomWidgetInvalidationTargets(capabilities, ["parent", "*"])).toEqual({
|
||||
all: true,
|
||||
requestIds: ["summary", "details"],
|
||||
loadRequestIds: ["summary"],
|
||||
refreshParent: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps action invalidation scoped to named query targets", () => {
|
||||
expect(resolveCustomWidgetInvalidationTargets(capabilities, ["details"])).toEqual({
|
||||
all: false,
|
||||
requestIds: ["details"],
|
||||
loadRequestIds: [],
|
||||
refreshParent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("refreshes the parent when a load query is invalidated by name", () => {
|
||||
expect(resolveCustomWidgetInvalidationTargets(capabilities, ["summary"])).toEqual({
|
||||
all: false,
|
||||
requestIds: ["summary"],
|
||||
loadRequestIds: ["summary"],
|
||||
refreshParent: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { CustomJsxRequestCapability } from "@homarr/custom-widgets/runtime";
|
||||
|
||||
export interface CustomWidgetInvalidationTargets {
|
||||
all: boolean;
|
||||
requestIds: string[];
|
||||
loadRequestIds: string[];
|
||||
refreshParent: boolean;
|
||||
}
|
||||
|
||||
export function resolveCustomWidgetInvalidationTargets(
|
||||
capabilities: readonly CustomJsxRequestCapability[],
|
||||
targets: readonly string[],
|
||||
): CustomWidgetInvalidationTargets {
|
||||
const queries = capabilities.filter((request) => request.kind === "query");
|
||||
const all = targets.includes("*");
|
||||
const requested = new Set(targets);
|
||||
const requestIds = queries.flatMap((request) => (all || requested.has(request.id) ? [request.id] : []));
|
||||
const loadRequestIds = queries.flatMap((request) =>
|
||||
request.trigger === "load" && (all || requested.has(request.id)) ? [request.id] : [],
|
||||
);
|
||||
return {
|
||||
all,
|
||||
requestIds,
|
||||
loadRequestIds,
|
||||
refreshParent: requested.has("parent") || all || loadRequestIds.length > 0,
|
||||
};
|
||||
}
|
||||
@@ -92,6 +92,7 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
const { openModal } = useModalAction(WidgetAdvancedOptionsModal);
|
||||
|
||||
const canModifyApps = session?.user.permissions.includes("app-modify-all") ?? false;
|
||||
const canConfigureWidget = innerProps.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
|
||||
const appId = innerProps.appId;
|
||||
const showAppTab = innerProps.kind === "app" && canModifyApps && Boolean(appId);
|
||||
|
||||
@@ -120,7 +121,7 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
|
||||
const widgetFormContent = (
|
||||
<Stack>
|
||||
{innerProps.integrationSupport && (
|
||||
{canConfigureWidget && innerProps.integrationSupport && (
|
||||
<WidgetIntegrationSelect
|
||||
label={t("item.edit.field.integrations.label")}
|
||||
data={innerProps.integrationData}
|
||||
@@ -131,32 +132,33 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
{...form.getInputProps("integrationIds")}
|
||||
/>
|
||||
)}
|
||||
{Object.entries(options).map(([key, value]) => {
|
||||
const Input = getInputForType(value.type);
|
||||
{canConfigureWidget &&
|
||||
Object.entries(options).map(([key, value]) => {
|
||||
const Input = getInputForType(value.type);
|
||||
|
||||
if (
|
||||
!Input ||
|
||||
value.shouldHide?.(
|
||||
form.values.options as never,
|
||||
innerProps.integrationData
|
||||
.filter(({ id }) => form.values.integrationIds.includes(id))
|
||||
.map(({ kind }) => kind),
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!Input ||
|
||||
value.shouldHide?.(
|
||||
form.values.options as never,
|
||||
innerProps.integrationData
|
||||
.filter(({ id }) => form.values.integrationIds.includes(id))
|
||||
.map(({ kind }) => kind),
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Input
|
||||
key={key}
|
||||
kind={innerProps.kind}
|
||||
property={key}
|
||||
options={value as never}
|
||||
initialOptions={innerProps.value.options}
|
||||
itemId={innerProps.itemId}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
return (
|
||||
<Input
|
||||
key={key}
|
||||
kind={innerProps.kind}
|
||||
property={key}
|
||||
options={value as never}
|
||||
initialOptions={innerProps.value.options}
|
||||
itemId={innerProps.itemId}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{showAppTab ? (
|
||||
<Button
|
||||
variant="subtle"
|
||||
|
||||
Reference in new issue
Block a user