fix(custom-widgets): configure secrets during import
This commit is contained in:
16 files changed
+331
-93
No files matched your search
@@ -4,6 +4,7 @@ import { z } from "zod/v4";
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { eq, or } from "@homarr/db";
|
||||
import { boards, customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { getCustomWidgetSecretRequirements } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure, protectedProcedure } from "../../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "../board/board-access";
|
||||
@@ -21,9 +22,11 @@ export const managementQueryProcedures = {
|
||||
.query(async ({ ctx }) => {
|
||||
const definitions = await ctx.db.query.customWidgetDefinitions.findMany({
|
||||
orderBy: (table, { asc }) => asc(table.name),
|
||||
with: { secrets: true },
|
||||
});
|
||||
return definitions.map((definition) => {
|
||||
const widget = parseStoredCustomWidgetDefinition(definition);
|
||||
const configuredSecrets = new Set(definition.secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
|
||||
return {
|
||||
id: definition.id,
|
||||
name: widget.name,
|
||||
@@ -37,6 +40,9 @@ export const managementQueryProcedures = {
|
||||
authType: auth.type,
|
||||
})),
|
||||
requestCount: widget.requests.length,
|
||||
missingSecrets: getCustomWidgetSecretRequirements(widget.sources).filter(
|
||||
(requirement) => !configuredSecrets.has(`${requirement.sourceId}:${requirement.kind}`),
|
||||
),
|
||||
defaultOptions: widget.defaultOptions,
|
||||
updatedAt: definition.updatedAt,
|
||||
enabled: definition.enabled,
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { getCustomWidgetRequiredSecretKinds } from "@homarr/custom-widgets/core";
|
||||
|
||||
export function requiredSecretKinds(authType: string) {
|
||||
if (authType === "basic") return ["username", "password"] as const;
|
||||
if (authType === "bearer" || authType === "apiKeyHeader" || authType === "apiKeyQuery") {
|
||||
return ["apiKey"] as const;
|
||||
}
|
||||
return [] as const;
|
||||
return getCustomWidgetRequiredSecretKinds(authType as Parameters<typeof getCustomWidgetRequiredSecretKinds>[0]);
|
||||
}
|
||||
|
||||
export function assertSecretSources(
|
||||
|
||||
@@ -2,12 +2,14 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
import { customWidgetImportSchema, customWidgetSecretsInputSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { assertSecretSources } from "./secret-policy";
|
||||
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
const manageProcedure = permissionRequiredProcedure.requiresPermission("custom-widget-manage");
|
||||
@@ -22,14 +24,34 @@ export const transferProcedures = {
|
||||
return parseStoredCustomWidgetDefinition(definition);
|
||||
}),
|
||||
|
||||
import: manageProcedure.input(customWidgetImportSchema).mutation(async ({ ctx, input }) => {
|
||||
const id = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
...serializeCustomWidgetDefinition(input),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
logger.info("Imported custom widget definition", { id, name: input.name });
|
||||
return { id };
|
||||
}),
|
||||
import: manageProcedure
|
||||
.input(z.object({ widget: customWidgetImportSchema, secrets: customWidgetSecretsInputSchema.default([]) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.secrets.length > 0 && !ctx.session.user.permissions.includes("custom-widget-secret-write")) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Writing imported widget secrets requires dedicated permission",
|
||||
});
|
||||
}
|
||||
assertSecretSources(input.widget.sources, input.secrets);
|
||||
const id = createId();
|
||||
await ctx.db.insert(customWidgetDefinitions).values({
|
||||
id,
|
||||
...serializeCustomWidgetDefinition(input.widget),
|
||||
creatorId: ctx.session.user.id,
|
||||
});
|
||||
if (input.secrets.length > 0) {
|
||||
await ctx.db.insert(customWidgetSecrets).values(
|
||||
input.secrets.map((secret) => ({
|
||||
definitionId: id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
logger.info("Imported custom widget definition", { id, name: input.widget.name });
|
||||
return { id };
|
||||
}),
|
||||
};
|
||||
@@ -208,7 +208,7 @@ export function formatCustomWidgetImportIssues(issues: readonly CustomWidgetImpo
|
||||
return `${visible.join(" ")}${remaining > 0 ? ` (+${remaining} more)` : ""}`;
|
||||
}
|
||||
|
||||
export function getImportReview(value: Record<string, unknown> | null): ImportReview | null {
|
||||
export function getImportReview(value: unknown): ImportReview | null {
|
||||
const parsed = customWidgetImportSchema.safeParse(value);
|
||||
if (!parsed.success) return null;
|
||||
const widget = parsed.data;
|
||||
|
||||
@@ -7,4 +7,5 @@ export * from "./import";
|
||||
export * from "./options";
|
||||
export * from "./schema";
|
||||
export * from "./schema-references";
|
||||
export * from "./secret-requirements";
|
||||
export * from "./tabler-icons";
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { CustomWidgetSource } from "./request-schema";
|
||||
import type { CustomWidgetSecretKind } from "./schema-types";
|
||||
|
||||
export interface CustomWidgetSecretRequirement {
|
||||
sourceId: string;
|
||||
sourceName: string;
|
||||
authType: CustomWidgetSource["auth"]["type"];
|
||||
kind: CustomWidgetSecretKind;
|
||||
destination?: string;
|
||||
}
|
||||
|
||||
export function getCustomWidgetRequiredSecretKinds(authType: CustomWidgetSource["auth"]["type"]) {
|
||||
if (authType === "basic") return ["username", "password"] as const;
|
||||
if (authType === "bearer" || authType === "apiKeyHeader" || authType === "apiKeyQuery") {
|
||||
return ["apiKey"] as const;
|
||||
}
|
||||
return [] as const;
|
||||
}
|
||||
|
||||
export function getCustomWidgetSecretRequirements(
|
||||
sources: readonly CustomWidgetSource[],
|
||||
): CustomWidgetSecretRequirement[] {
|
||||
return sources.flatMap((source) =>
|
||||
getCustomWidgetRequiredSecretKinds(source.auth.type).map((kind) => ({
|
||||
sourceId: source.id,
|
||||
sourceName: source.name,
|
||||
authType: source.auth.type,
|
||||
kind,
|
||||
destination:
|
||||
source.auth.type === "apiKeyHeader"
|
||||
? source.auth.headerName
|
||||
: source.auth.type === "apiKeyQuery"
|
||||
? source.auth.parameterName
|
||||
: undefined,
|
||||
})),
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ export const CUSTOM_JSX_LIMITS = Object.freeze({
|
||||
templateLength: 50_000,
|
||||
astDepth: 64,
|
||||
operations: 25_000,
|
||||
collectionItems: 2_000,
|
||||
collectionItems: 4_000,
|
||||
renderedNodes: 10_000,
|
||||
stringLength: 200_000,
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import { BUNDLED_CUSTOM_WIDGETS } from "../core/bundled-widgets";
|
||||
import { customJsxExamples, CUSTOM_WIDGET_STARTER } from "../core/examples";
|
||||
import { getCustomWidgetSecretRequirements } from "../core/secret-requirements";
|
||||
import { customJsxRequestSchema, customWidgetCreateSchema, customWidgetDefinitionSchema } from "../core/schema";
|
||||
import { validateCustomWidgetOptions } from "../core/options";
|
||||
|
||||
@@ -27,6 +28,39 @@ describe("Custom JSX v2 validation", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("derives every credential required by widget sources", () => {
|
||||
expect(
|
||||
getCustomWidgetSecretRequirements([
|
||||
{
|
||||
id: "default",
|
||||
name: "Example API",
|
||||
baseUrl: "https://api.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "bearer" },
|
||||
},
|
||||
{
|
||||
id: "portainer",
|
||||
name: "Portainer",
|
||||
baseUrl: "https://portainer.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "apiKeyHeader", headerName: "X-API-Key" },
|
||||
},
|
||||
{
|
||||
id: "basic",
|
||||
name: "Basic API",
|
||||
baseUrl: "https://basic.example.com",
|
||||
networkScope: "public",
|
||||
auth: { type: "basic" },
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
expect.objectContaining({ sourceId: "default", kind: "apiKey", authType: "bearer" }),
|
||||
expect.objectContaining({ sourceId: "portainer", kind: "apiKey", destination: "X-API-Key" }),
|
||||
expect.objectContaining({ sourceId: "basic", kind: "username" }),
|
||||
expect.objectContaining({ sourceId: "basic", kind: "password" }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects every legacy schema", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, $schema: "homarr-custom-widget-v3" }).success,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Alert, Badge, Button, Code, Group, Modal, Paper, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
@@ -24,6 +25,7 @@ export interface ImportReviewDialogProps {
|
||||
review: ImportReview | null;
|
||||
pending: boolean;
|
||||
messages: ImportReviewMessages;
|
||||
children?: ReactNode;
|
||||
onClose(): void;
|
||||
onConfirm(): void;
|
||||
}
|
||||
@@ -39,7 +41,15 @@ function ImportFact({ label, value }: { label: string; value: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ImportReviewDialog({ opened, review, pending, messages, onClose, onConfirm }: ImportReviewDialogProps) {
|
||||
export function ImportReviewDialog({
|
||||
opened,
|
||||
review,
|
||||
pending,
|
||||
messages,
|
||||
children,
|
||||
onClose,
|
||||
onConfirm,
|
||||
}: ImportReviewDialogProps) {
|
||||
return (
|
||||
<Modal opened={opened} onClose={onClose} title={messages.title} centered size="lg">
|
||||
{review && (
|
||||
@@ -89,6 +99,7 @@ export function ImportReviewDialog({ opened, review, pending, messages, onClose,
|
||||
<Text size="sm">{messages.actionWarningDescription}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
{children}
|
||||
<Group justify="flex-end">
|
||||
<Button type="button" variant="default" onClick={onClose} disabled={pending}>
|
||||
{messages.cancel}
|
||||
|
||||
@@ -722,7 +722,9 @@
|
||||
"list": {
|
||||
"title": "Custom Widgets",
|
||||
"noResults": "No custom widgets yet. Create your first one!",
|
||||
"loading": "Loading..."
|
||||
"loading": "Loading...",
|
||||
"missingCredentials": "{count, plural, one {Credential missing} other {# credentials missing}}",
|
||||
"missingCredentialsDescription": "{count, plural, one {This widget still needs one credential.} other {This widget still needs # credentials.}} Edit it to configure the encrypted values."
|
||||
},
|
||||
"create": {
|
||||
"title": "Create Custom Widget",
|
||||
@@ -973,6 +975,17 @@
|
||||
"networkScope": "Network scope",
|
||||
"methods": "HTTP methods",
|
||||
"permissions": "Required board permissions",
|
||||
"credentials": {
|
||||
"title": "Configure credentials now",
|
||||
"description": "Secrets are encrypted locally and never added to the imported widget. You can leave a field blank and configure it later.",
|
||||
"header": "Sent through the {name} header",
|
||||
"query": "Sent through the {name} query parameter",
|
||||
"field": {
|
||||
"apiKey": "API key or token",
|
||||
"username": "Username",
|
||||
"password": "Password"
|
||||
}
|
||||
},
|
||||
"actionWarning": {
|
||||
"title": "This widget can change remote data",
|
||||
"description": "Review every named action, inherited credential, and destructive confirmation after import. Secrets are not included in the file."
|
||||
|
||||
Reference in new issue
Block a user