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.

feat(custom-widgets): support multiple encrypted headers (#7241)

Thomasfd89940fa76c
diff --git a/.agents/skills/homarr-custom-widget/references/schema.md b/.agents/skills/homarr-custom-widget/references/schema.md
index df54e4edc..5cc9cfd8b 100644
--- a/.agents/skills/homarr-custom-widget/references/schema.md
+++ b/.agents/skills/homarr-custom-widget/references/schema.md
@@ -41,7 +41,9 @@ Key `default` is the required source ID, not a source property. Fields: `name?`,
Saved sources use `{"type":"integration","integrationKind":"sonarr","integrationId":"saved-id"}`. Discover and bind a full-access entry before preview. Omit URL/auth; paths append to its URL, non-GET requests are actions, and exports omit `integrationId`.
-Auth is `none`, `bearer`, `basic`, `apiKeyHeader`, or `apiKeyQuery`. Requests default to source `default`, query/GET/load, inherited auth, and view permission. Use `load` for initial/current display and `manual` only for explicit interactions or invocation params. Actions are manual/modify; DELETE requires full permission and confirmation.
+Auth is `none`, `bearer`, `basic`, `apiKeyHeader`, `apiKeyQuery`, or `headers`. Requests default to source `default`, query/GET/load, inherited auth, and view permission. Use `load` for initial/current display and `manual` only for explicit interactions or invocation params. Actions are manual/modify; DELETE requires full permission and confirmation.
+
+For multiple secret headers, use `auth: {"type":"headers","headers":[{"name":"X-Api-Key","slot":"key"},{"name":"X-Api-Secret","slot":"secret"}]}`. Up to 8 HTTP-token names are allowed, unique ignoring case, with distinct stable slot IDs of at most 57 characters. Homarr configures each slot separately and stores its value encrypted; the manifest contains only names and slots. Header name or slot changes require credential configuration again. Use `bearer` for Authorization; routing, proxy, forwarding, cookie and hop-by-hop headers remain reserved.
JSON responses become their decoded value. Responses with `application/x-ndjson` become an array with one decoded object per non-empty line.
diff --git a/apps/docs/src/components/workshop/DetailPage.tsx b/apps/docs/src/components/workshop/DetailPage.tsx
index f6b5c8c2e..0340c6da8 100644
--- a/apps/docs/src/components/workshop/DetailPage.tsx
+++ b/apps/docs/src/components/workshop/DetailPage.tsx
@@ -112,7 +112,9 @@ const sourceAuthLabel = (source: WidgetSource) => {
if (auth === "none") return "No credentials";
if (auth === "basic") return "Basic auth";
if (auth === "bearer") return "Bearer token";
- return auth.type === "apiKeyHeader" ? `API key header · ${auth.name}` : `API key query · ${auth.name}`;
+ if (auth.type === "headers") return `Authentication headers · ${auth.headers.map(({ name }) => name).join(", ")}`;
+ if (auth.type === "apiKeyHeader") return `API key header · ${auth.name}`;
+ return `API key query · ${auth.name}`;
};
const sourceNeedsSecret = (source: WidgetSource) => source.type !== "integration" && source.auth !== "none";
diff --git a/apps/nextjs/src/app/[locale]/custom-widget-configuration/[token]/configuration-entry.tsx b/apps/nextjs/src/app/[locale]/custom-widget-configuration/[token]/configuration-entry.tsx
index 04a9e6cea..b640721b3 100644
--- a/apps/nextjs/src/app/[locale]/custom-widget-configuration/[token]/configuration-entry.tsx
+++ b/apps/nextjs/src/app/[locale]/custom-widget-configuration/[token]/configuration-entry.tsx
@@ -4,8 +4,12 @@ import { useEffect, useState } from "react";
import { Alert, Button, Card, Center, PasswordInput, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
import { IconCheck, IconKey, IconLock } from "@tabler/icons-react";
-import { isCustomWidgetSourceUrlPlaceholder } from "@homarr/custom-widgets/core";
-import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
+import {
+ isCustomWidgetSourceUrlPlaceholder,
+ isCustomWidgetHeaderSecretKind,
+ getCustomWidgetSecretRequirements,
+} from "@homarr/custom-widgets/core";
+import type { CustomWidgetSource, CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
import { IntegrationSourceSelect } from "~/components/custom-widgets/integration-source-select";
import { useI18n } from "@homarr/translation/client";
@@ -13,7 +17,7 @@ import { useI18n } from "@homarr/translation/client";
interface RequestDetails {
widgetName: string;
sourceName: string;
- kinds: Array<"apiKey" | "username" | "password">;
+ kinds: CustomWidgetSecretKind[];
expiresAt: number;
status: "pending" | "applying" | "completed";
source: CustomWidgetSource;
@@ -116,10 +120,16 @@ export function CustomWidgetConfigurationEntry({ token }: { token: string }) {
)}
{details.kinds.map((kind) => {
const Input = kind === "username" ? TextInput : PasswordInput;
+ let label: string;
+ if (isCustomWidgetHeaderSecretKind(kind)) {
+ label =
+ getCustomWidgetSecretRequirements({ default: details.source }).find((field) => field.kind === kind)
+ ?.destination ?? kind.slice(7);
+ } else label = tSecret(kind);
return (
<Input
key={kind}
- label={tSecret(kind)}
+ label={label}
leftSection={<IconKey size={16} />}
value={values[kind] ?? ""}
onChange={(event) => {
diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form-utils.ts b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form-utils.ts
index ae153f6ff..57e2c898a 100644
--- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form-utils.ts
+++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-form-utils.ts
@@ -7,7 +7,7 @@ import {
parseCustomWidgetAiResponse,
validateCustomWidgetOptions,
} from "@homarr/custom-widgets/core";
-import type { CustomWidgetSource, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
+import type { CustomWidgetSource, HomarrCustomWidgetV2, CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
import type { CustomWidgetFormValues } from "@homarr/custom-widgets/workbench";
import type { UseFormReturnType } from "@mantine/form";
@@ -35,7 +35,7 @@ export function getChangedSecrets(values: Pick<CustomWidgetFormValues, "secrets"
.filter((secret) => secret.value.trim())
.map(({ sourceId, kind, value }) => ({
sourceId,
- kind: kind as "apiKey" | "username" | "password",
+ kind: kind as CustomWidgetSecretKind,
value,
}));
}
diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-source-field.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-source-field.tsx
index a742b64a1..66f0047ff 100644
--- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-source-field.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-source-field.tsx
@@ -1,13 +1,20 @@
"use client";
import { Button, Fieldset, Group, PasswordInput, Select, Stack, TextInput } from "@mantine/core";
-import { IconKey, IconTrash } from "@tabler/icons-react";
+import { IconKey, IconTrash, IconPlus } from "@tabler/icons-react";
-import { getCustomWidgetSourceUrlIssue } from "@homarr/custom-widgets/core";
+import {
+ getCustomWidgetSourceUrlIssue,
+ getCustomWidgetHeaderSecretKind,
+ MAX_CUSTOM_WIDGET_AUTH_HEADERS,
+} from "@homarr/custom-widgets/core";
import type {
CustomWidgetHttpSource,
CustomWidgetSource,
CustomWidgetSourceUrlIssue,
+ CustomWidgetSecretKind,
+ CustomWidgetLegacySecretKind,
+ CustomWidgetAuthenticationHeader,
} from "@homarr/custom-widgets/core";
import { useI18n } from "@homarr/translation/client";
@@ -16,9 +23,9 @@ import { IntegrationSourceSelect } from "~/components/custom-widgets/integration
import type { CustomWidgetWorkbenchForm } from "./_custom-widget-form-utils";
import { CustomWidgetIdentifierInput } from "./_custom-widget-identifier-input";
-type SecretKind = "apiKey" | "username" | "password";
+type SecretKind = CustomWidgetSecretKind;
-const secretFields: Record<string, Array<{ kind: SecretKind }>> = {
+const secretFields: Record<string, Array<{ kind: CustomWidgetLegacySecretKind }>> = {
bearer: [{ kind: "apiKey" }],
basic: [{ kind: "username" }, { kind: "password" }],
apiKeyHeader: [{ kind: "apiKey" }],
@@ -141,6 +148,12 @@ function CustomWidgetHttpSourceFields({
const tSecret = useI18n("customWidget.secret");
const baseUrlIssue = getCustomWidgetSourceUrlIssue(source.baseUrl);
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
+ let authHeaders: CustomWidgetAuthenticationHeader[] = [];
+ if (typeof source.auth === "object" && source.auth.type === "headers" && Array.isArray(source.auth.headers)) {
+ authHeaders = source.auth.headers.filter(
+ (header) => typeof header?.name === "string" && typeof header.slot === "string",
+ );
+ }
return (
<>
<TextInput
@@ -153,7 +166,7 @@ function CustomWidgetHttpSourceFields({
<Group grow align="start">
<Select
label={t("authentication")}
- data={["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery"]}
+ data={["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery", "headers"]}
value={authType}
onChange={(value) => onSetAuthentication(index, value ?? "none")}
allowDeselect={false}
@@ -173,6 +186,19 @@ function CustomWidgetHttpSourceFields({
onChange={(event) => onUpdate(index, { auth: { type: "apiKeyQuery", name: event.currentTarget.value } })}
/>
)}
+ {typeof source.auth === "object" && source.auth.type === "headers" && (
+ <CustomWidgetAuthHeaderFields
+ sourceId={source.id}
+ headers={authHeaders}
+ index={index}
+ form={form}
+ definitionId={definitionId}
+ clearSecretPending={clearSecretPending}
+ onUpdate={onUpdate}
+ onSetSecret={onSetSecret}
+ onClearSecret={onClearSecret}
+ />
+ )}
{(secretFields[authType] ?? []).map(({ kind }) => {
const secret = form.values.secrets.find((entry) => entry.sourceId === source.id && entry.kind === kind);
const Input = kind === "username" ? TextInput : PasswordInput;
@@ -203,3 +229,104 @@ function CustomWidgetHttpSourceFields({
</>
);
}
+
+function CustomWidgetAuthHeaderFields({
+ sourceId,
+ headers,
+ index,
+ form,
+ definitionId,
+ clearSecretPending,
+ onUpdate,
+ onSetSecret,
+ onClearSecret,
+}: Pick<
+ CustomWidgetSourceFieldProps,
+ "index" | "form" | "definitionId" | "clearSecretPending" | "onUpdate" | "onSetSecret" | "onClearSecret"
+> & {
+ sourceId: string;
+ headers: CustomWidgetAuthenticationHeader[];
+}) {
+ const t = useI18n("customWidget.workbench.sources");
+ const tSecret = useI18n("customWidget.secret");
+ const tCommon = useI18n("common");
+ const updateHeaders = (next: CustomWidgetAuthenticationHeader[]) =>
+ onUpdate(index, { auth: { type: "headers", headers: next } });
+ const addHeader = () => {
+ let suffix = 1;
+ while (
+ headers.some((header) => header.slot === `header${suffix}` || header.name.toLowerCase() === `x-header-${suffix}`)
+ )
+ suffix += 1;
+ updateHeaders([...headers, { name: `X-Header-${suffix}`, slot: `header${suffix}` }]);
+ };
+
+ return (
+ <Stack gap="sm">
+ {headers.map((header, headerIndex) => {
+ const kind = getCustomWidgetHeaderSecretKind(header.slot);
+ const secret = form.values.secrets.find((entry) => entry.sourceId === sourceId && entry.kind === kind);
+ return (
+ <Stack key={header.slot} gap="xs">
+ <Group grow align="start">
+ <TextInput
+ label={t("headerName")}
+ maxLength={256}
+ value={header.name}
+ onChange={(event) =>
+ updateHeaders(
+ headers.map((entry, entryIndex) => {
+ if (entryIndex !== headerIndex) return entry;
+ return { ...entry, name: event.currentTarget.value };
+ }),
+ )
+ }
+ />
+ <PasswordInput
+ label={header.name || tSecret("apiKey")}
+ value={secret?.value ?? ""}
+ maxLength={8192}
+ autoComplete="off"
+ placeholder={secret?.hasValue ? t("configured") : undefined}
+ leftSection={<IconKey size={15} />}
+ onChange={(event) => onSetSecret(sourceId, kind, event.currentTarget.value)}
+ />
+ </Group>
+ <Group justify="flex-end" gap="xs">
+ {definitionId && secret?.hasValue && (
+ <Button
+ type="button"
+ color="red"
+ variant="subtle"
+ loading={clearSecretPending}
+ onClick={() => void onClearSecret(sourceId, kind)}
+ >
+ {t("clear")}
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="subtle"
+ color="red"
+ leftSection={<IconTrash size={15} />}
+ disabled={headers.length === 1}
+ onClick={() => updateHeaders(headers.filter((_entry, entryIndex) => entryIndex !== headerIndex))}
+ >
+ {tCommon("action.remove")}
+ </Button>
+ </Group>
+ </Stack>
+ );
+ })}
+ <Button
+ type="button"
+ variant="light"
+ leftSection={<IconPlus size={15} />}
+ disabled={headers.length >= MAX_CUSTOM_WIDGET_AUTH_HEADERS}
+ onClick={addHeader}
+ >
+ {tCommon("action.add")}
+ </Button>
+ </Stack>
+ );
+}
diff --git a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-sources-editor.tsx b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-sources-editor.tsx
index adfe5e852..e0e2c3365 100644
--- a/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-sources-editor.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/custom-widgets/_custom-widget-sources-editor.tsx
@@ -4,7 +4,8 @@ import { Accordion, Button, List, Stack, Text } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
-import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
+import { hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
+import type { CustomWidgetSource, CustomWidgetHttpSource, CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
import { useConfirmModal } from "@homarr/modals";
import { showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
@@ -28,6 +29,23 @@ export function CustomWidgetSourcesEditor({
const clearSecretMutation = clientApi.customWidget.secretClear.useMutation();
const sources = parseSources(form.values.sources);
const update = (index: number, changes: Partial<CustomWidgetSource> & { id?: string }) => {
+ const previous = sources[index];
+ if (changes.auth !== undefined && previous) {
+ let secrets = filterSecretsForSourceAuthentication(form.values.secrets, previous.id, changes.auth);
+ if (
+ definitionId &&
+ previous.type !== "integration" &&
+ typeof changes.auth === "object" &&
+ changes.auth.type === "headers" &&
+ !hasSameCustomWidgetSourceAuthentication(previous, { ...previous, auth: changes.auth })
+ ) {
+ secrets = secrets.map((secret) => {
+ if (secret.sourceId !== previous.id) return secret;
+ return { ...secret, hasValue: false };
+ });
+ }
+ form.setFieldValue("secrets", secrets);
+ }
if (changes.type) {
form.setFieldValue(
"secrets",
@@ -76,17 +94,12 @@ export function CustomWidgetSourcesEditor({
}
};
const setAuth = (index: number, type: string) => {
- const auth =
- type === "apiKeyHeader" ? { type, name: "X-API-Key" } : type === "apiKeyQuery" ? { type, name: "api_key" } : type;
- update(index, { auth: auth as CustomWidgetSource["auth"] });
- form.setFieldValue(
- "secrets",
- filterSecretsForSourceAuthentication(
- form.values.secrets,
- sources[index]?.id ?? "",
- type as Parameters<typeof filterSecretsForSourceAuthentication>[2],
- ),
- );
+ let auth: CustomWidgetHttpSource["auth"];
+ if (type === "apiKeyHeader") auth = { type, name: "X-API-Key" };
+ else if (type === "apiKeyQuery") auth = { type, name: "api_key" };
+ else if (type === "headers") auth = { type, headers: [{ name: "X-API-Key", slot: "key" }] };
+ else auth = type as "none" | "basic" | "bearer";
+ update(index, { auth });
};
const setSecret = (sourceId: string, kind: string, value: string) => {
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
@@ -159,7 +172,7 @@ export function CustomWidgetSourcesEditor({
onConfirm: () => removeSourceAndDependents(index),
});
};
- const clearSecret = async (sourceId: string, kind: "apiKey" | "username" | "password") => {
+ const clearSecret = async (sourceId: string, kind: CustomWidgetSecretKind) => {
if (!definitionId) return;
await clearSecretMutation.mutateAsync({ definitionId, sourceId, kind });
const current = form.values.secrets.filter((secret) => !(secret.sourceId === sourceId && secret.kind === kind));
diff --git a/apps/nextjs/src/app/api/custom-widgets/configuration-request/[token]/route.ts b/apps/nextjs/src/app/api/custom-widgets/configuration-request/[token]/route.ts
index f32b25897..da6c7a97a 100644
--- a/apps/nextjs/src/app/api/custom-widgets/configuration-request/[token]/route.ts
+++ b/apps/nextjs/src/app/api/custom-widgets/configuration-request/[token]/route.ts
@@ -11,13 +11,19 @@ import {
releaseCustomWidgetConfigurationRequest,
retryCustomWidgetConfigurationRequest,
} from "@homarr/api/custom-widget-configuration";
-import { customWidgetSourceSchema, isCustomWidgetSourceUrlPlaceholder } from "@homarr/custom-widgets/core";
+import {
+ customWidgetSourceSchema,
+ customWidgetSecretInputSchema,
+ customWidgetAuthenticationHeadersSchema,
+ getCustomWidgetHeaderSecretKind,
+ isCustomWidgetSourceUrlPlaceholder,
+} from "@homarr/custom-widgets/core";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { db } from "@homarr/db";
import type { AdminSession } from "../../admin";
import { adminRouteWithSession } from "../../admin";
-import { readConfigurationRequestBody } from "../body";
+import { readConfigurationRequestBody, getHeaderConfigurationRequestBodyLimit } from "../body";
interface RouteContext {
params: Promise<{ token: string }>;
@@ -55,7 +61,33 @@ const completeConfigurationRequest = async (
if (!pending || pending.status !== "pending") {
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
}
- const parsedBody = await readConfigurationRequestBody(request);
+ let maximumBodyBytes: number | undefined;
+ let requestedHeaderKinds: Set<string> | undefined;
+ if (typeof pending.source.auth === "object" && pending.source.auth.type === "headers") {
+ const headers = customWidgetAuthenticationHeadersSchema.safeParse(pending.source.auth.headers);
+ if (!headers.success) {
+ return NextResponse.json(
+ { error: "This credential request is invalid. Request a new setup link." },
+ { status: 400 },
+ );
+ }
+ const declaredKinds = new Set<string>(headers.data.map(({ slot }) => getCustomWidgetHeaderSecretKind(slot)));
+ const requestedKinds = new Set<string>(pending.kinds);
+ const limit = getHeaderConfigurationRequestBodyLimit(requestedKinds.size);
+ if (
+ limit === null ||
+ requestedKinds.size !== pending.kinds.length ||
+ [...requestedKinds].some((kind) => !declaredKinds.has(kind))
+ ) {
+ return NextResponse.json(
+ { error: "This credential request is invalid. Request a new setup link." },
+ { status: 400 },
+ );
+ }
+ maximumBodyBytes = limit;
+ requestedHeaderKinds = requestedKinds;
+ }
+ const parsedBody = await readConfigurationRequestBody(request, maximumBodyBytes);
if (parsedBody.status === "too-large") {
return NextResponse.json({ error: "The configuration payload is too large." }, { status: 413 });
}
@@ -63,6 +95,9 @@ const completeConfigurationRequest = async (
return NextResponse.json({ error: "Enter a valid source configuration." }, { status: 400 });
}
const body = parsedBody.data;
+ if (requestedHeaderKinds && Object.keys(body.secrets).some((kind) => !requestedHeaderKinds.has(kind))) {
+ return NextResponse.json({ error: "Provide only the requested credential fields." }, { status: 400 });
+ }
let candidate: unknown;
if (pending.source.type === "integration") {
if (!body.integrationId || body.baseUrl !== undefined || Object.keys(body.secrets).length > 0) {
@@ -94,9 +129,9 @@ const completeConfigurationRequest = async (
}
const secrets = pending.kinds.flatMap((kind) => {
const value = body.secrets[kind];
- return typeof value === "string" && value.length > 0 && value.length <= 8192
- ? [{ sourceId: pending.sourceId, kind, value }]
- : [];
+ const result = customWidgetSecretInputSchema.safeParse({ sourceId: pending.sourceId, kind, value });
+ if (!result.success) return [];
+ return [result.data];
});
if (secrets.length !== pending.kinds.length) {
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
diff --git a/apps/nextjs/src/app/api/custom-widgets/configuration-request/body.ts b/apps/nextjs/src/app/api/custom-widgets/configuration-request/body.ts
index 8e1bd3791..ee1afa790 100644
--- a/apps/nextjs/src/app/api/custom-widgets/configuration-request/body.ts
+++ b/apps/nextjs/src/app/api/custom-widgets/configuration-request/body.ts
@@ -1,6 +1,19 @@
import { z } from "zod/v4";
+import { MAX_CUSTOM_WIDGET_AUTH_HEADERS } from "@homarr/custom-widgets/core";
export const MAX_CONFIGURATION_REQUEST_BODY_BYTES = 24 * 1024;
+
+export function getHeaderConfigurationRequestBodyLimit(requestedHeaderCount: number) {
+ if (
+ !Number.isInteger(requestedHeaderCount) ||
+ requestedHeaderCount < 1 ||
+ requestedHeaderCount > MAX_CUSTOM_WIDGET_AUTH_HEADERS
+ ) {
+ return null;
+ }
+ // JSON can escape each credential code unit to six bytes. Reserve bounded connection metadata and keys.
+ return requestedHeaderCount * 8192 * 6 + 16 * 1024;
+}
const configurationRequestBodySchema = z
.strictObject({
baseUrl: z.string().optional(),
@@ -15,11 +28,12 @@ const configurationRequestBodySchema = z
export async function readConfigurationRequestBody(
request: Request,
+ maximumBytes = MAX_CONFIGURATION_REQUEST_BODY_BYTES,
): Promise<
{ status: "ok"; data: z.infer<typeof configurationRequestBodySchema> } | { status: "invalid" | "too-large" }
> {
const contentLength = request.headers.get("content-length");
- if (contentLength && Number(contentLength) > MAX_CONFIGURATION_REQUEST_BODY_BYTES) {
+ if (contentLength && Number(contentLength) > maximumBytes) {
return { status: "too-large" };
}
if (!request.body) return { status: "invalid" };
@@ -32,7 +46,7 @@ export async function readConfigurationRequestBody(
const { done, value } = await reader.read();
if (done) break;
byteLength += value.byteLength;
- if (byteLength > MAX_CONFIGURATION_REQUEST_BODY_BYTES) {
+ if (byteLength > maximumBytes) {
await reader.cancel();
return { status: "too-large" };
}
diff --git a/packages/api/src/router/custom-widget/definition-update.ts b/packages/api/src/router/custom-widget/definition-update.ts
index 200b60e5f..4170406fd 100644
--- a/packages/api/src/router/custom-widget/definition-update.ts
+++ b/packages/api/src/router/custom-widget/definition-update.ts
@@ -7,7 +7,6 @@ import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync, notInArray } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
import type { CustomWidgetDefinition, CustomWidgetSecret } from "@homarr/db/schema";
-import { getCustomWidgetSourceAuthType } from "@homarr/custom-widgets/core";
import type { CustomWidgetCreateInput, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
@@ -119,7 +118,7 @@ export async function updateCustomWidgetDefinition(
);
}
for (const [sourceId, source] of Object.entries(input.definition.sources)) {
- const kinds = [...requiredSecretKinds(getCustomWidgetSourceAuthType(source))];
+ const kinds = [...requiredSecretKinds(source.auth)];
const where = and(
eq(schema.customWidgetSecrets.definitionId, input.id),
eq(schema.customWidgetSecrets.sourceId, sourceId),
@@ -179,7 +178,7 @@ export async function updateCustomWidgetDefinition(
.run();
}
for (const [sourceId, source] of Object.entries(input.definition.sources)) {
- const kinds = [...requiredSecretKinds(getCustomWidgetSourceAuthType(source))];
+ const kinds = [...requiredSecretKinds(source.auth)];
const where = and(
eq(customWidgetSecrets.definitionId, input.id),
eq(customWidgetSecrets.sourceId, sourceId),
diff --git a/packages/api/src/router/custom-widget/preview-base-procedures.ts b/packages/api/src/router/custom-widget/preview-base-procedures.ts
index 65871d81f..f86481c6d 100644
--- a/packages/api/src/router/custom-widget/preview-base-procedures.ts
+++ b/packages/api/src/router/custom-widget/preview-base-procedures.ts
@@ -1,5 +1,4 @@
import { assertCustomWidgetIntegrationBindings } from "./source-resolver";
-import { getCustomWidgetSourceAuthType } from "@homarr/custom-widgets/core";
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
@@ -97,8 +96,7 @@ const getRequiredSourceConfigurations = (
);
const sourceRequiresCredentials = sourceRequests.some((request) => request.auth !== "none");
const isMissingCredential =
- sourceRequiresCredentials &&
- requiredSecretKinds(getCustomWidgetSourceAuthType(source)).some((kind) => !configuredSecretKinds.has(kind));
+ sourceRequiresCredentials && requiredSecretKinds(source.auth).some((kind) => !configuredSecretKinds.has(kind));
if (!isCustomWidgetSourceUrlPlaceholder(source.baseUrl) && !isMissingCredential) return [];
return [
{
@@ -152,8 +150,7 @@ const previewCreateProcedure = permissionRequiredProcedure
const hasStoredSecrets = existing.secrets.some((secret) => secret.sourceId === sourceId);
if (!submittedSource || !hasStoredSecrets || hasSameSecretBinding(existingSource, submittedSource)) continue;
- const authType = getCustomWidgetSourceAuthType(submittedSource);
- const missingReplacement = requiredSecretKinds(authType).some(
+ const missingReplacement = requiredSecretKinds(submittedSource.auth).some(
(kind) => !secrets.some((secret) => secret.sourceId === sourceId && secret.kind === kind),
);
if (missingReplacement) {
@@ -179,13 +176,7 @@ const previewCreateProcedure = permissionRequiredProcedure
const invalid = secrets.find((secret) => {
const source = definition.sources[secret.sourceId];
- const authType = getCustomWidgetSourceAuthType(source);
- const kinds =
- authType === "basic"
- ? ["username", "password"]
- : source && authType && ["bearer", "apiKeyHeader", "apiKeyQuery"].includes(authType)
- ? ["apiKey"]
- : [];
+ const kinds = requiredSecretKinds(source?.auth);
return !source || !kinds.includes(secret.kind);
});
if (invalid) {
diff --git a/packages/api/src/router/custom-widget/preview-procedure-helpers.ts b/packages/api/src/router/custom-widget/preview-procedure-helpers.ts
index a0fb3249a..edc0d4ae3 100644
--- a/packages/api/src/router/custom-widget/preview-procedure-helpers.ts
+++ b/packages/api/src/router/custom-widget/preview-procedure-helpers.ts
@@ -56,9 +56,12 @@ export function getPreviewRequestSourceConfigurationFailure(
if (isCustomWidgetSourceUrlPlaceholder(source.baseUrl)) {
error = `Preview source '${request.source}' URL is a placeholder; complete secure source configuration before testing requests`;
} else if (request.auth !== "none") {
+ let headerSlots;
+ if (typeof source.auth === "object" && source.auth.type === "headers") headerSlots = source.auth.headers;
error = getCustomWidgetAuthConfigurationError({
type: getCustomWidgetSourceAuthType(source),
secrets: getPreviewSessionSecrets(session, request.source),
+ headerSlots,
});
}
if (error === null) return null;
diff --git a/packages/api/src/router/custom-widget/secret-policy.ts b/packages/api/src/router/custom-widget/secret-policy.ts
index fca1e446f..c6b4f68c3 100644
--- a/packages/api/src/router/custom-widget/secret-policy.ts
+++ b/packages/api/src/router/custom-widget/secret-policy.ts
@@ -3,11 +3,13 @@ import { TRPCError } from "@trpc/server";
import {
getCustomWidgetRequiredSecretKinds,
hasSameCustomWidgetSourceAuthentication,
+ customWidgetSecretInputSchema,
+ isCustomWidgetHeaderSecretKind,
} from "@homarr/custom-widgets/core";
-import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
+import type { CustomWidgetSource, CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
-export function requiredSecretKinds(authType: string) {
- return getCustomWidgetRequiredSecretKinds(authType as Parameters<typeof getCustomWidgetRequiredSecretKinds>[0]);
+export function requiredSecretKinds(auth: Parameters<typeof getCustomWidgetRequiredSecretKinds>[0]) {
+ return getCustomWidgetRequiredSecretKinds(auth);
}
/**
@@ -24,13 +26,18 @@ export function hasSameSecretBinding(left: CustomWidgetSource, right: CustomWidg
}
export function assertSecretSources(
- sources: Record<string, { auth?: string | { type: string }; type?: string }>,
- secrets: readonly { sourceId: string; kind: "apiKey" | "username" | "password" }[],
+ sources: Record<string, CustomWidgetSource>,
+ secrets: readonly { sourceId: string; kind: CustomWidgetSecretKind; value?: string }[],
) {
+ const headerIdentities = new Set<string>();
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 (!source || !new Set<string>(requiredSecretKinds(source.auth)).has(secret.kind)) return true;
+ if (!isCustomWidgetHeaderSecretKind(secret.kind)) return false;
+ const identity = `${secret.sourceId}:${secret.kind}`;
+ if (headerIdentities.has(identity) || !customWidgetSecretInputSchema.safeParse(secret).success) return true;
+ headerIdentities.add(identity);
+ return false;
});
if (invalid) {
throw new TRPCError({
diff --git a/packages/api/src/router/custom-widget/secret-procedures.ts b/packages/api/src/router/custom-widget/secret-procedures.ts
index 1f01f2192..43b332351 100644
--- a/packages/api/src/router/custom-widget/secret-procedures.ts
+++ b/packages/api/src/router/custom-widget/secret-procedures.ts
@@ -1,5 +1,4 @@
import { assertCustomWidgetIntegrationBindings } from "./source-resolver";
-import { getCustomWidgetSourceAuthType } from "@homarr/custom-widgets/core";
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
@@ -7,6 +6,7 @@ import { eq } from "@homarr/db";
import { customWidgetDefinitions } from "@homarr/db/schema";
import {
customWidgetSecretInputSchema,
+ customWidgetSecretKindSchema,
customWidgetSecretsInputSchema,
customWidgetSourceSchema,
} from "@homarr/custom-widgets/core";
@@ -192,7 +192,7 @@ export const secretProcedures = {
target = { type: "preview", id: preview.id };
}
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
- const kinds = [...requiredSecretKinds(getCustomWidgetSourceAuthType(source))];
+ const kinds = [...requiredSecretKinds(source.auth)];
const request = await createCustomWidgetConfigurationRequest({
userId: ctx.session.user.id,
target,
@@ -214,9 +214,7 @@ export const secretProcedures = {
secretClear: permissionRequiredProcedure
.requiresPermission("admin")
- .input(
- z.object({ definitionId: z.string(), sourceId: z.string(), kind: z.enum(["apiKey", "username", "password"]) }),
- )
+ .input(z.object({ definitionId: z.string(), sourceId: z.string(), kind: customWidgetSecretKindSchema }))
.mutation(async ({ ctx, input }) => {
const existing = await ctx.db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, input.definitionId),
diff --git a/packages/api/src/router/custom-widget/source-resolver.ts b/packages/api/src/router/custom-widget/source-resolver.ts
index e63215e57..a62f396ea 100644
--- a/packages/api/src/router/custom-widget/source-resolver.ts
+++ b/packages/api/src/router/custom-widget/source-resolver.ts
@@ -74,9 +74,14 @@ export async function resolveCustomWidgetSource(
let auth: CustomWidgetHttpRequest["auth"];
if (request.auth !== "none" && authType !== "none") {
auth = { type: authType, secrets: getSecrets() };
- if (typeof source.auth === "object") auth.headerName = source.auth.name;
+ if (typeof source.auth === "object") {
+ if (source.auth.type === "headers") auth.headerSlots = source.auth.headers;
+ else auth.headerName = source.auth.name;
+ }
}
- return { baseUrl: source.baseUrl, auth, cacheVersion: "" };
+ let redactSecrets: CustomWidgetHttpRequest["redactSecrets"];
+ if (auth?.type === "headers") redactSecrets = auth.secrets;
+ return { baseUrl: source.baseUrl, auth, redactSecrets, cacheVersion: "" };
}
const integration = await resolveIntegration(ctx, source);
return getIntegrationHttpConnection(integration, request.auth !== "none");
diff --git a/packages/api/src/router/custom-widget/transfer-procedures.ts b/packages/api/src/router/custom-widget/transfer-procedures.ts
index fbc5e15a4..207c6c0fd 100644
--- a/packages/api/src/router/custom-widget/transfer-procedures.ts
+++ b/packages/api/src/router/custom-widget/transfer-procedures.ts
@@ -96,7 +96,7 @@ export const transferProcedures = {
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 preservableKinds = new Set<string>(requiredSecretKinds(input.widget.sources.default?.auth));
const preservedSecrets = canPreserveLegacySecrets(legacy, input.widget)
? legacy.secrets.filter(({ kind }) => preservableKinds.has(kind) && !explicitKeys.has(`default:${kind}`))
: [];
diff --git a/packages/api/src/router/test/custom-widget/definition-persistence.spec.ts b/packages/api/src/router/test/custom-widget/definition-persistence.spec.ts
index ef6b5a750..05ef559c8 100644
--- a/packages/api/src/router/test/custom-widget/definition-persistence.spec.ts
+++ b/packages/api/src/router/test/custom-widget/definition-persistence.spec.ts
@@ -881,7 +881,12 @@ describe("custom widget definition persistence", () => {
const created = await createCaller(db).create({ ...jellyfin, secrets: [] });
const definition = customWidgetDefinitionSchema.parse(jellyfin);
const expectedSource = definition.sources.default;
- if (!expectedSource || expectedSource.type === "integration" || typeof expectedSource.auth === "string") {
+ if (
+ !expectedSource ||
+ expectedSource.type === "integration" ||
+ typeof expectedSource.auth === "string" ||
+ expectedSource.auth.type !== "apiKeyHeader"
+ ) {
throw new Error("Jellyfin default source must use header authentication");
}
await db
diff --git a/packages/custom-widgets/scripts/ai-evaluation.ts b/packages/custom-widgets/scripts/ai-evaluation.ts
index 81553cb51..eedfc930f 100644
--- a/packages/custom-widgets/scripts/ai-evaluation.ts
+++ b/packages/custom-widgets/scripts/ai-evaluation.ts
@@ -281,7 +281,7 @@ export const getExpectedWidgetCase = (
});
const getAuthName = (source: HomarrCustomWidgetV2["sources"][string] | undefined) =>
- typeof source?.auth === "object" ? source.auth.name : undefined;
+ typeof source?.auth === "object" && "name" in source.auth ? source.auth.name : undefined;
const requestMatchesExpectation = (
request: HomarrCustomWidgetV2["requests"][string],
diff --git a/packages/custom-widgets/src/core/ai-prompt.ts b/packages/custom-widgets/src/core/ai-prompt.ts
index 13a990769..117d39031 100644
--- a/packages/custom-widgets/src/core/ai-prompt.ts
+++ b/packages/custom-widgets/src/core/ai-prompt.ts
@@ -40,7 +40,7 @@ const CUSTOM_WIDGET_CONTEXT_BOUNDARY_INSTRUCTION = `Context security boundary:
const LEGACY_MIGRATION_AUTHORING_GUIDANCE = `Convert the supplied legacy widget to Homarr Custom JSX v2 for Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}. This is a migration, not a redesign: reuse the original JSX hierarchy, labels, interactions, and known component props. Change only what v2 compatibility, safe manual actions, null handling, and tile-width readability require. Do not inventory unrelated components or rediscover the supplied API.
-The importable manifest has "$schema":"${CUSTOM_WIDGET_SCHEMA}", name, optional description/iconUrl, keyed sources/requests/options, and a template string containing one JSX expression. Omit absent optional fields: iconUrl must be a valid URL string or omitted, never null. Use sources.default with baseUrl and credential-free auth: "none", "basic", "bearer", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Map legacy authType and headerName to that auth declaration, including authType:"none" to auth:"none". For authenticated sources, empty configuredSecretKinds means credentials need configuration, not removal of authentication; Homarr configures secrets separately.
+The importable manifest has "$schema":"${CUSTOM_WIDGET_SCHEMA}", name, optional description/iconUrl, keyed sources/requests/options, and a template string containing one JSX expression. Omit absent optional fields: iconUrl must be a valid URL string or omitted, never null. Use sources.default with baseUrl and credential-free auth: "none", "basic", "bearer", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Multiple encrypted headers use {"type":"headers","headers":[{"name":"X-Api-Key","slot":"key"},{"name":"X-Api-Secret","slot":"secret"}]}, with at most 8 unique HTTP header names and stable credential slots of at most 57 characters; configure values separately. Map legacy authType and headerName to that auth declaration, including authType:"none" to auth:"none". For authenticated sources, empty configuredSecretKinds means credentials need configuration, not removal of authentication; Homarr configures secrets separately.
Each request has source:"default", slash-prefixed path, method, query, optional body, kind, trigger, and permission. For GET use "kind":"query", "trigger":"load", "permission":"view". For non-GET use "kind":"action", "trigger":"manual", "permission":"modify" (DELETE: "full") with an appropriate confirmation string or {title,message,confirmLabel,destructive}. "load" is a trigger, never a kind; "auto" and "automatic" are not valid triggers. Preserve original path, query values, and body. Do not invent a replacement GET for a legacy POST. Legacy actionButton also preserves buttonLabel, buttonColor, confirmText, and successMessage using ActionButton label/children, color, request confirmation, and successMessage props; keep failure feedback.
@@ -129,7 +129,7 @@ ${leanShape}
${CUSTOM_WIDGET_MODE_GUIDANCE}
-Sources are keyed by name and must include "default". HTTP sources require a baseUrl plus optional auth: "none", "bearer", "basic", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Saved integrations use {"type":"integration","integrationKind":"..."} and omit baseUrl and auth; discover supported kinds with integration_getKinds and bind a matching integrationId from integration_all with permissions.hasFullAccess before preview. iCalendar feeds (iCal) and the TrueNAS WebSocket API cannot be used as generic HTTP sources. Exports omit integrationId, paths append to the saved URL, and non-GET integration requests must be manual actions. Use a stable public API URL when documented. When the user did not supply the exact URL for a self-hosted HTTP source, use an explicit placeholder host such as https://your-service.example.com rather than guessing a .local address; preview creation marks that source for URL configuration. Never put credentials in the manifest.
+Sources are keyed by name and must include "default". HTTP sources require a baseUrl plus optional auth: "none", "bearer", "basic", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Multiple encrypted headers use {"type":"headers","headers":[{"name":"X-Api-Key","slot":"key"},{"name":"X-Api-Secret","slot":"secret"}]}, with at most 8 unique HTTP header names and stable credential slots of at most 57 characters; configure values separately. Saved integrations use {"type":"integration","integrationKind":"..."} and omit baseUrl and auth; discover supported kinds with integration_getKinds and bind a matching integrationId from integration_all with permissions.hasFullAccess before preview. iCalendar feeds (iCal) and the TrueNAS WebSocket API cannot be used as generic HTTP sources. Exports omit integrationId, paths append to the saved URL, and non-GET integration requests must be manual actions. Use a stable public API URL when documented. When the user did not supply the exact URL for a self-hosted HTTP source, use an explicit placeholder host such as https://your-service.example.com rather than guessing a .local address; preview creation marks that source for URL configuration. Never put credentials in the manifest.
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. JSON responses become their decoded value; application/x-ndjson responses become an array of decoded lines. A request that supplies the widget's initial/current display, including one using a saved option in its path or query, is a load query: set \`trigger: "load"\` explicitly when the user asks for a load/current/automatic display. Set \`trigger: "manual"\` only when the user requests an explicit user-triggered query or the request uses invocation parameters with SubFetch, ActionButton, or ToggleSwitch. If the template reads \`data.requestId\`/\`status.requestId\` and uses \`RefreshButton requestId="requestId"\`, that request must be \`trigger: "load"\`; do not make it manual merely because it has an option binding. DELETE is valid only for actions and requires full permission. Set confirmation:"Retry?" or confirmation:{title:"Retry",message:"Retry?"}; DELETE gets a confirmation prompt by default. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Every request path must remain a literal slash-prefixed path after interpolation; never make a placeholder the entire path. If a migration path is unknown, omit its request (requests:{} if none); never guess /. Always include sources.default, even for static widgets. Paths and query values must be primitive; JSON bodies may bind structured options.
@@ -175,7 +175,7 @@ For a missing contract, research primary API docs with up to three targeted sear
Core schema/runtime/safety/lifecycle rules are bundled; do not call customWidget_getSkill or customWidget_getReference. Unknown edit: call customWidget_list once, then get the exact widget. Persisted follow-up: pass its id as definitionId to previewCreate. Preserve sources unless explicitly changed; style-only edits preserve requests/options. Never turn an edit into a create. Resolve uncertain components with customWidget_findComponents, then at most eight needed component documents in one getComponents batch. Reuse loaded context/contextAlreadyLoaded and follow nextStep. Inventory operations, paths, states, and count.
CONTRACT
-Build a credential-free v2 definition with object inputs and sources.default. Copy URL/auth. Without an exact self-hosted URL, use https://your-service.example.com so preview returns sourceConfigurations; never guess .local. API keys need a named header/query object; integration sources need exact integrationKind/integrationId. Never request, accept, or send secrets in chat/tool inputs. Static headers are request headers string maps. Sources never contain headers or header arrays.
+Build a credential-free v2 definition with object inputs and sources.default. Copy URL/auth. Without an exact self-hosted URL, use https://your-service.example.com so preview returns sourceConfigurations; never guess .local. API keys need a named header/query object; integration sources need exact integrationKind/integrationId. Never request, accept, or send secrets in chat/tool inputs. Static headers are request headers string maps. Sources never contain a top-level headers field; source.auth.headers is allowed for header authentication.
For a static widget, use \`sources:{default:{baseUrl:"https://example.com",auth:"none"}}\` and \`requests:{}\`. For the current local time, use the installed safe helper \`Date.toLocaleString(Date.now(), "en-US")\`; never use \`new Date()\`.
diff --git a/packages/custom-widgets/src/core/authoring-resources.ts b/packages/custom-widgets/src/core/authoring-resources.ts
index 5c9daaef2..649f877e2 100644
--- a/packages/custom-widgets/src/core/authoring-resources.ts
+++ b/packages/custom-widgets/src/core/authoring-resources.ts
@@ -80,7 +80,7 @@ export const CUSTOM_WIDGET_SKILL_SOURCE_URL =
"https://github.com/homarr-labs/homarr/tree/HEAD/.agents/skills/homarr-custom-widget";
export const CUSTOM_WIDGET_SKILL_INSTALL_COMMAND =
"npx skills add https://github.com/homarr-labs/homarr --skill homarr-custom-widget";
-export const CUSTOM_WIDGET_SKILL_VERSION = "2.10.8";
+export const CUSTOM_WIDGET_SKILL_VERSION = "2.10.9";
export const CUSTOM_WIDGET_SKILL_REFERENCE_NAMES = ["schema", "runtime", "security"] as const;
export type CustomWidgetSkillReferenceName = (typeof CUSTOM_WIDGET_SKILL_REFERENCE_NAMES)[number];
@@ -153,7 +153,9 @@ Key \`default\` is the required source ID, not a source property. Fields: \`name
Saved sources use \`{"type":"integration","integrationKind":"sonarr","integrationId":"saved-id"}\`. Discover and bind a full-access entry before preview. Omit URL/auth; paths append to its URL, non-GET requests are actions, and exports omit \`integrationId\`.
-Auth is \`none\`, \`bearer\`, \`basic\`, \`apiKeyHeader\`, or \`apiKeyQuery\`. Requests default to source \`default\`, query/GET/load, inherited auth, and view permission. Use \`load\` for initial/current display and \`manual\` only for explicit interactions or invocation params. Actions are manual/modify; DELETE requires full permission and confirmation.
+Auth is \`none\`, \`bearer\`, \`basic\`, \`apiKeyHeader\`, \`apiKeyQuery\`, or \`headers\`. Requests default to source \`default\`, query/GET/load, inherited auth, and view permission. Use \`load\` for initial/current display and \`manual\` only for explicit interactions or invocation params. Actions are manual/modify; DELETE requires full permission and confirmation.
+
+For multiple secret headers, use \`auth: {"type":"headers","headers":[{"name":"X-Api-Key","slot":"key"},{"name":"X-Api-Secret","slot":"secret"}]}\`. Up to 8 HTTP-token names are allowed, unique ignoring case, with distinct stable slot IDs of at most 57 characters. Homarr configures each slot separately and stores its value encrypted; the manifest contains only names and slots. Header name or slot changes require credential configuration again. Use \`bearer\` for Authorization; routing, proxy, forwarding, cookie and hop-by-hop headers remain reserved.
JSON responses become their decoded value. Responses with \`application/x-ndjson\` become an array with one decoded object per non-empty line.
diff --git a/packages/custom-widgets/src/core/custom-jsx-schema.ts b/packages/custom-widgets/src/core/custom-jsx-schema.ts
index 728fc9d0f..bf3b0f24f 100644
--- a/packages/custom-widgets/src/core/custom-jsx-schema.ts
+++ b/packages/custom-widgets/src/core/custom-jsx-schema.ts
@@ -11,7 +11,13 @@ import {
customWidgetSourcesSchema,
} from "./request-schema";
import type { CustomJsxRequest } from "./request-schema";
-import { customWidgetSecretKinds } from "./schema-types";
+import {
+ CUSTOM_WIDGET_HEADER_SECRET_KIND_PATTERN,
+ customWidgetSecretKinds,
+ isCustomWidgetHeaderSecretKind,
+} from "./schema-types";
+import type { CustomWidgetHeaderSecretKind } from "./schema-types";
+import { isCustomWidgetHeaderSecretValue } from "./request-header-policy";
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
export * from "./options-schema";
@@ -51,15 +57,33 @@ export const customJsxTemplateSchema = z
}),
);
-export const customWidgetSecretInputSchema = z.strictObject({
- sourceId: customWidgetIdentifierSchema,
- kind: z.enum(customWidgetSecretKinds),
- value: z.string().min(1).max(8_192),
-});
+export const customWidgetSecretKindSchema = z.union([
+ z.enum(customWidgetSecretKinds),
+ z
+ .string()
+ .regex(CUSTOM_WIDGET_HEADER_SECRET_KIND_PATTERN)
+ .transform((kind) => kind as CustomWidgetHeaderSecretKind),
+]);
+
+export const customWidgetSecretInputSchema = z
+ .strictObject({
+ sourceId: customWidgetIdentifierSchema,
+ kind: customWidgetSecretKindSchema,
+ value: z.string().min(1).max(8_192),
+ })
+ .superRefine((secret, ctx) => {
+ if (isCustomWidgetHeaderSecretKind(secret.kind) && !isCustomWidgetHeaderSecretValue(secret.value)) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["value"],
+ message: "Authentication header values must use Latin-1 characters without unsupported control characters",
+ });
+ }
+ });
export const customWidgetSecretsInputSchema = z
.array(customWidgetSecretInputSchema)
- .max(24)
+ .max(64)
.superRefine((secrets, ctx) => {
const identities = new Set<string>();
secrets.forEach((secret, index) => {
diff --git a/packages/custom-widgets/src/core/request-header-policy.ts b/packages/custom-widgets/src/core/request-header-policy.ts
new file mode 100644
index 000000000..27df96f29
--- /dev/null
+++ b/packages/custom-widgets/src/core/request-header-policy.ts
@@ -0,0 +1,34 @@
+export const CUSTOM_WIDGET_HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
+export const MAX_CUSTOM_WIDGET_AUTH_HEADERS = 8;
+
+const reservedRequestHeaders = new Set([
+ "authorization",
+ "connection",
+ "content-length",
+ "cookie",
+ "expect",
+ "forwarded",
+ "host",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailer",
+ "transfer-encoding",
+ "upgrade",
+ "via",
+]);
+
+export function isReservedCustomWidgetRequestHeader(name: string) {
+ const normalized = name.trim().toLowerCase();
+ return (
+ reservedRequestHeaders.has(normalized) ||
+ normalized.startsWith("proxy-") ||
+ normalized.startsWith("sec-") ||
+ normalized.startsWith("x-forwarded-")
+ );
+}
+
+export function isCustomWidgetHeaderSecretValue(value: string) {
+ return value.length > 0 && value.length <= 8_192 && /^[\t\x20-\x7e\x80-\xff]+$/u.test(value);
+}
diff --git a/packages/custom-widgets/src/core/request-schema.ts b/packages/custom-widgets/src/core/request-schema.ts
index cfdb48423..d08d4e784 100644
--- a/packages/custom-widgets/src/core/request-schema.ts
+++ b/packages/custom-widgets/src/core/request-schema.ts
@@ -2,7 +2,12 @@ import { z } from "zod/v4";
import { httpIntegrationKinds } from "@homarr/definitions/integration";
-import { customWidgetMethods } from "./schema-types";
+import { customWidgetMethods, MAX_CUSTOM_WIDGET_HEADER_SLOT_LENGTH } from "./schema-types";
+import {
+ CUSTOM_WIDGET_HEADER_NAME_PATTERN,
+ isReservedCustomWidgetRequestHeader,
+ MAX_CUSTOM_WIDGET_AUTH_HEADERS,
+} from "./request-header-policy";
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
export const customWidgetIdentifierSchema = z
@@ -15,12 +20,48 @@ const headerNameSchema = z
.string()
.min(1)
.max(256)
- .regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u, "Header names must be valid HTTP tokens");
+ .regex(CUSTOM_WIDGET_HEADER_NAME_PATTERN, "Header names must be valid HTTP tokens");
+
+export const customWidgetAuthenticationHeadersSchema = z
+ .array(
+ z.strictObject({
+ name: headerNameSchema,
+ slot: customWidgetIdentifierSchema.max(MAX_CUSTOM_WIDGET_HEADER_SLOT_LENGTH),
+ }),
+ )
+ .min(1)
+ .max(MAX_CUSTOM_WIDGET_AUTH_HEADERS)
+ .superRefine((headers, ctx) => {
+ const names = new Set<string>();
+ const slots = new Set<string>();
+ headers.forEach((header, index) => {
+ if (isReservedCustomWidgetRequestHeader(header.name)) {
+ ctx.addIssue({ code: "custom", path: [index, "name"], message: "This header is reserved" });
+ }
+ const name = header.name.toLowerCase();
+ if (names.has(name)) {
+ ctx.addIssue({ code: "custom", path: [index, "name"], message: "Authentication header names must be unique" });
+ }
+ if (slots.has(header.slot)) {
+ ctx.addIssue({
+ code: "custom",
+ path: [index, "slot"],
+ message: "Authentication credential slots must be unique",
+ });
+ }
+ names.add(name);
+ slots.add(header.slot);
+ });
+ });
+export type CustomWidgetAuthenticationHeader = z.infer<typeof customWidgetAuthenticationHeadersSchema>[number];
+
+export { MAX_CUSTOM_WIDGET_AUTH_HEADERS } from "./request-header-policy";
const authSchema = z.union([
z.enum(["none", "bearer", "basic"]),
z.strictObject({ type: z.literal("apiKeyHeader"), name: headerNameSchema }),
z.strictObject({ type: z.literal("apiKeyQuery"), name: z.string().trim().min(1).max(256) }),
+ z.strictObject({ type: z.literal("headers"), headers: customWidgetAuthenticationHeadersSchema }),
]);
export type CustomWidgetSourceUrlIssue = "invalid" | "protocol" | "credentials" | "queryOrFragment";
@@ -101,38 +142,11 @@ export const boundValueSchema: z.ZodType<unknown> = z.lazy(() =>
]),
);
-const reservedRequestHeaders = new Set([
- "authorization",
- "connection",
- "content-length",
- "cookie",
- "expect",
- "forwarded",
- "host",
- "keep-alive",
- "proxy-authenticate",
- "proxy-authorization",
- "te",
- "trailer",
- "transfer-encoding",
- "upgrade",
- "via",
-]);
-
const headersSchema = z
.record(headerNameSchema, z.string().max(8192))
.refine((headers) => Object.keys(headers).length <= 32, "A request can declare at most 32 headers")
.refine(
- (headers) =>
- Object.keys(headers).every((name) => {
- const normalized = name.toLowerCase();
- return (
- !reservedRequestHeaders.has(normalized) &&
- !normalized.startsWith("proxy-") &&
- !normalized.startsWith("sec-") &&
- !normalized.startsWith("x-forwarded-")
- );
- }),
+ (headers) => Object.keys(headers).every((name) => !isReservedCustomWidgetRequestHeader(name)),
"Headers cannot override authentication, cookies, routing, forwarding, proxy, or hop-by-hop headers",
)
.refine(
diff --git a/packages/custom-widgets/src/core/schema-types.ts b/packages/custom-widgets/src/core/schema-types.ts
index 2a0967843..12fc13a0e 100644
--- a/packages/custom-widgets/src/core/schema-types.ts
+++ b/packages/custom-widgets/src/core/schema-types.ts
@@ -1,8 +1,22 @@
-export const customWidgetAuthTypes = ["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery"] as const;
+export const customWidgetAuthTypes = ["none", "bearer", "basic", "apiKeyHeader", "apiKeyQuery", "headers"] as const;
export type CustomWidgetAuthType = (typeof customWidgetAuthTypes)[number];
export const customWidgetMethods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const;
export type CustomWidgetMethod = (typeof customWidgetMethods)[number];
export const customWidgetSecretKinds = ["apiKey", "username", "password"] as const;
-export type CustomWidgetSecretKind = (typeof customWidgetSecretKinds)[number];
+export type CustomWidgetLegacySecretKind = (typeof customWidgetSecretKinds)[number];
+export type CustomWidgetHeaderSecretKind = `header:${string}`;
+export type CustomWidgetSecretKind = CustomWidgetLegacySecretKind | CustomWidgetHeaderSecretKind;
+
+// The existing PostgreSQL kind column has 64 characters, including "header:".
+export const MAX_CUSTOM_WIDGET_HEADER_SLOT_LENGTH = 57;
+export const CUSTOM_WIDGET_HEADER_SECRET_KIND_PATTERN = /^header:[A-Za-z][A-Za-z0-9_-]{0,56}$/u;
+
+export function getCustomWidgetHeaderSecretKind(slot: string): CustomWidgetHeaderSecretKind {
+ return `header:${slot}`;
+}
+
+export function isCustomWidgetHeaderSecretKind(kind: string): kind is CustomWidgetHeaderSecretKind {
+ return CUSTOM_WIDGET_HEADER_SECRET_KIND_PATTERN.test(kind);
+}
diff --git a/packages/custom-widgets/src/core/secret-requirements.ts b/packages/custom-widgets/src/core/secret-requirements.ts
index 1439efe22..8d8e596a3 100644
--- a/packages/custom-widgets/src/core/secret-requirements.ts
+++ b/packages/custom-widgets/src/core/secret-requirements.ts
@@ -1,20 +1,25 @@
import { getCustomWidgetSourceAuthType } from "./request-schema";
-import type { CustomWidgetSource } from "./request-schema";
-import type { CustomWidgetSecretKind } from "./schema-types";
-
-type AuthType = "none" | "bearer" | "basic" | "apiKeyHeader" | "apiKeyQuery";
+import type { CustomWidgetHttpSource, CustomWidgetSource } from "./request-schema";
+import { getCustomWidgetHeaderSecretKind } from "./schema-types";
+import type { CustomWidgetAuthType, CustomWidgetSecretKind } from "./schema-types";
export interface CustomWidgetSecretRequirement {
sourceId: string;
sourceName: string;
- authType: AuthType;
+ authType: CustomWidgetAuthType;
kind: CustomWidgetSecretKind;
destination?: string;
}
-export function getCustomWidgetRequiredSecretKinds(authType: AuthType) {
+export function getCustomWidgetRequiredSecretKinds(
+ auth: CustomWidgetHttpSource["auth"] | Exclude<CustomWidgetAuthType, "headers"> | undefined,
+): readonly CustomWidgetSecretKind[] {
+ if (typeof auth === "object" && auth.type === "headers") {
+ return auth.headers.map(({ slot }) => getCustomWidgetHeaderSecretKind(slot));
+ }
+ const authType = typeof auth === "object" ? auth.type : auth;
if (authType === "basic") return ["username", "password"] as const;
- if (["bearer", "apiKeyHeader", "apiKeyQuery"].includes(authType)) return ["apiKey"] as const;
+ if (authType && ["bearer", "apiKeyHeader", "apiKeyQuery"].includes(authType)) return ["apiKey"] as const;
return [] as const;
}
@@ -23,12 +28,23 @@ export function getCustomWidgetSecretRequirements(
): CustomWidgetSecretRequirement[] {
return Object.entries(sources).flatMap(([sourceId, source]) => {
const authType = getCustomWidgetSourceAuthType(source);
- return getCustomWidgetRequiredSecretKinds(authType).map((kind) => ({
+ if (typeof source.auth === "object" && source.auth.type === "headers") {
+ return source.auth.headers.map(({ name, slot }) => ({
+ sourceId,
+ sourceName: source.name ?? sourceId,
+ authType,
+ kind: getCustomWidgetHeaderSecretKind(slot),
+ destination: name,
+ }));
+ }
+ let destination: string | undefined;
+ if (typeof source.auth === "object" && "name" in source.auth) destination = source.auth.name;
+ return getCustomWidgetRequiredSecretKinds(source.auth).map((kind) => ({
sourceId,
sourceName: source.name ?? sourceId,
authType,
kind,
- destination: typeof source.auth === "object" ? source.auth.name : undefined,
+ destination,
}));
});
}
diff --git a/packages/custom-widgets/src/core/source-setup.ts b/packages/custom-widgets/src/core/source-setup.ts
index e510d6a0f..da4573319 100644
--- a/packages/custom-widgets/src/core/source-setup.ts
+++ b/packages/custom-widgets/src/core/source-setup.ts
@@ -1,7 +1,7 @@
import { getCustomWidgetSourceAuthType } from "./request-schema";
-import type { CustomWidgetSource } from "./request-schema";
+import type { CustomWidgetSource, CustomWidgetAuthenticationHeader } from "./request-schema";
import { getCustomWidgetSourceUrlIssue } from "./request-schema";
-import type { CustomWidgetSecretKind } from "./schema-types";
+import type { CustomWidgetAuthType, CustomWidgetSecretKind } from "./schema-types";
import { getCustomWidgetSecretRequirements } from "./secret-requirements";
export interface CustomWidgetConfiguredSecret {
@@ -18,7 +18,7 @@ export interface CustomWidgetSourceSetup {
baseUrl: string;
integrationKind?: string;
integrationId?: string;
- authType: "none" | "bearer" | "basic" | "apiKeyHeader" | "apiKeyQuery";
+ authType: CustomWidgetAuthType;
credentialFields: Array<{
kind: CustomWidgetSecretKind;
destination?: string;
@@ -55,9 +55,22 @@ export function hasSameCustomWidgetSourceAuthentication(left: CustomWidgetSource
);
}
if (typeof left.auth === "string" || typeof right.auth === "string") return left.auth === right.auth;
+ if (left.auth.type === "headers" || right.auth.type === "headers") {
+ if (left.auth.type !== "headers" || right.auth.type !== "headers") return false;
+ return (
+ JSON.stringify(canonicalAuthHeaders(left.auth.headers)) ===
+ JSON.stringify(canonicalAuthHeaders(right.auth.headers))
+ );
+ }
return left.auth.type === right.auth.type && left.auth.name === right.auth.name;
}
+function canonicalAuthHeaders(headers: CustomWidgetAuthenticationHeader[]) {
+ return headers
+ .map(({ name, slot }) => ({ slot, name }))
+ .toSorted((leftHeader, rightHeader) => leftHeader.slot.localeCompare(rightHeader.slot));
+}
+
export function getCustomWidgetSourceSetups(
sources: Record<string, CustomWidgetSource>,
configuredSecrets: readonly CustomWidgetConfiguredSecret[] = [],
diff --git a/packages/custom-widgets/src/server/auth.ts b/packages/custom-widgets/src/server/auth.ts
index 210ce15e2..2f45a6108 100644
--- a/packages/custom-widgets/src/server/auth.ts
+++ b/packages/custom-widgets/src/server/auth.ts
@@ -1,4 +1,8 @@
import { getCustomWidgetRequiredSecretKinds } from "../core/secret-requirements";
+import { customWidgetAuthenticationHeadersSchema } from "../core/request-schema";
+import type { CustomWidgetAuthenticationHeader } from "../core/request-schema";
+import { getCustomWidgetHeaderSecretKind } from "../core/schema-types";
+import { isCustomWidgetHeaderSecretValue } from "../core/request-header-policy";
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "./request-types";
import { CustomWidgetDomainError } from "./errors";
import { assertCustomWidgetPathScope, resolveSameOriginTarget } from "./network-policy";
@@ -29,6 +33,26 @@ export function buildSecretMap(secrets: Array<{ kind: string; value: string }>):
}
export function getCustomWidgetAuthConfigurationError(auth: CustomWidgetHttpRequest["auth"]): string | null {
+ if (auth?.type === "headers") {
+ if (Object.keys(auth.headers ?? {}).length > 0 || Object.keys(auth.query ?? {}).length > 0 || auth.body) {
+ return "Custom widget authentication headers must use their declared credential slots";
+ }
+ const declarations = customWidgetAuthenticationHeadersSchema.safeParse(auth.headerSlots);
+ if (!declarations.success) return "Custom widget authentication header declarations are invalid";
+ const required = new Set<string>(declarations.data.map(({ slot }) => getCustomWidgetHeaderSecretKind(slot)));
+ const supplied = new Set<string>();
+ for (const secret of auth.secrets) {
+ if (!required.has(secret.kind) || supplied.has(secret.kind)) {
+ return "Custom widget credentials do not match the declared authentication headers";
+ }
+ if (!isCustomWidgetHeaderSecretValue(secret.value)) return "Custom widget authentication header value is invalid";
+ supplied.add(secret.kind);
+ }
+ if ([...required].some((kind) => !auth.secrets.some((secret) => secret.kind === kind && secret.value.trim()))) {
+ return "Custom widget source credentials are missing; complete secure source configuration before running requests";
+ }
+ return null;
+ }
if (
!auth ||
(auth.type !== "basic" && auth.type !== "bearer" && auth.type !== "apiKeyHeader" && auth.type !== "apiKeyQuery")
@@ -52,10 +76,19 @@ export function applyAuth(
authType: string,
secrets: Array<{ kind: string; value: string }>,
headerName?: string | null,
+ headerSlots?: CustomWidgetAuthenticationHeader[],
): void {
- assertAuthCredentials({ type: authType, secrets });
+ assertAuthCredentials({ type: authType, secrets, headerSlots });
const secretMap = buildSecretMap(secrets);
+ if (authType === "headers") {
+ for (const { name, slot } of headerSlots ?? []) {
+ const value = secretMap[getCustomWidgetHeaderSecretKind(slot)];
+ if (value !== undefined) headers.set(name, value);
+ }
+ return;
+ }
+
if (authType === "basic" && secretMap.username && secretMap.password) {
const credentials = Buffer.from(`${secretMap.username}:${secretMap.password}`).toString("base64");
headers.set("Authorization", `Basic ${credentials}`);
diff --git a/packages/custom-widgets/src/server/network-policy.ts b/packages/custom-widgets/src/server/network-policy.ts
index bd1b698ff..6b2743429 100644
--- a/packages/custom-widgets/src/server/network-policy.ts
+++ b/packages/custom-widgets/src/server/network-policy.ts
@@ -1,31 +1,10 @@
import type { ConnectionOptions } from "node:tls";
import { Agent } from "undici";
+import { isReservedCustomWidgetRequestHeader } from "../core/request-header-policy";
import { CustomWidgetDomainError } from "./errors";
import { MAX_RESPONSE_BODY_BYTES } from "./response";
-const RESERVED_HEADERS = new Set([
- "authorization",
- "connection",
- "content-length",
- "cookie",
- "expect",
- "forwarded",
- "host",
- "keep-alive",
- "proxy-authenticate",
- "proxy-authorization",
- "te",
- "trailer",
- "transfer-encoding",
- "upgrade",
- "via",
- "x-forwarded-for",
- "x-forwarded-host",
- "x-forwarded-port",
- "x-forwarded-proto",
-]);
-
export function validateCustomWidgetUrl(value: string | URL): URL {
let url: URL;
try {
@@ -54,13 +33,7 @@ export function resolveSameOriginTarget(baseValue: string, targetValue?: string
export function assertSafeStaticHeaders(headers: Record<string, string> | undefined): void {
for (const name of Object.keys(headers ?? {})) {
- const value = name.trim().toLowerCase();
- if (
- RESERVED_HEADERS.has(value) ||
- value.startsWith("proxy-") ||
- value.startsWith("sec-") ||
- value.startsWith("x-forwarded-")
- ) {
+ if (isReservedCustomWidgetRequestHeader(name)) {
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: `Header '${name}' is reserved` });
}
}
diff --git a/packages/custom-widgets/src/server/preview-sessions.ts b/packages/custom-widgets/src/server/preview-sessions.ts
index 3bcdab99f..d79d81925 100644
--- a/packages/custom-widgets/src/server/preview-sessions.ts
+++ b/packages/custom-widgets/src/server/preview-sessions.ts
@@ -4,10 +4,13 @@ import { z } from "zod/v4";
import {
customWidgetOptionsSchema,
customWidgetRequestsSchema,
- customWidgetSecretKinds,
+ customWidgetSecretKindSchema,
customWidgetSourcesSchema,
+ getCustomWidgetRequiredSecretKinds,
+ isCustomWidgetHeaderSecretKind,
} from "../core";
-import type { CustomJsxRequest, CustomWidgetOptions, CustomWidgetSource } from "../core";
+import type { CustomJsxRequest, CustomWidgetOptions, CustomWidgetSource, CustomWidgetSecretKind } from "../core";
+import { isCustomWidgetHeaderSecretValue } from "../core/request-header-policy";
import { CustomWidgetDomainError } from "./errors";
import {
getPreviewEvidenceKey,
@@ -25,7 +28,7 @@ const MAX_UPDATE_ATTEMPTS = 8;
const encryptedSecretSchema = z.object({
sourceId: z.string(),
- kind: z.enum(customWidgetSecretKinds),
+ kind: customWidgetSecretKindSchema,
value: z.string(),
});
@@ -54,7 +57,7 @@ export type { CustomWidgetPreviewJournalEntry } from "./preview-session-evidence
export interface CreatePreviewSessionInput {
userId: string;
sources: Record<string, CustomWidgetSource>;
- secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>;
+ secrets: Array<{ sourceId: string; kind: CustomWidgetSecretKind; value: string }>;
requests: Record<string, CustomJsxRequest>;
name: string;
description?: string;
@@ -96,6 +99,7 @@ export class CustomWidgetPreviewSessionService {
}
public async create(input: CreatePreviewSessionInput) {
+ assertHeaderSecretSlots(input.sources, input.secrets);
const sourceIds = new Set(Object.keys(input.sources));
if (input.secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
throw new CustomWidgetDomainError({
@@ -211,9 +215,10 @@ export class CustomWidgetPreviewSessionService {
public async setSecrets(
id: string,
userId: string,
- secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>,
+ secrets: Array<{ sourceId: string; kind: CustomWidgetSecretKind; value: string }>,
) {
const next = await this.update(id, userId, (session) => {
+ assertHeaderSecretSlots(session.sources, secrets);
const sourceIds = new Set(Object.keys(session.sources));
if (secrets.some((secret) => !sourceIds.has(secret.sourceId))) {
throw new CustomWidgetDomainError({
@@ -238,7 +243,7 @@ export class CustomWidgetPreviewSessionService {
userId: string,
sourceId: string,
source: CustomWidgetSource,
- secrets: Array<{ sourceId: string; kind: (typeof customWidgetSecretKinds)[number]; value: string }>,
+ secrets: Array<{ sourceId: string; kind: CustomWidgetSecretKind; value: string }>,
) {
const next = await this.update(id, userId, (session) => {
const currentSource = session.sources[sourceId];
@@ -251,6 +256,7 @@ export class CustomWidgetPreviewSessionService {
message: "Preview source authentication changed; create a new configuration request",
});
}
+ assertHeaderSecretSlots({ ...session.sources, [sourceId]: source }, secrets);
const replacements = new Set(secrets.map((secret) => `${secret.sourceId}:${secret.kind}`));
return {
...session,
@@ -301,3 +307,27 @@ export class CustomWidgetPreviewSessionService {
else this.sessions.set(session.id, session);
}
}
+
+function assertHeaderSecretSlots(
+ sources: Record<string, CustomWidgetSource>,
+ secrets: Array<{ sourceId: string; kind: CustomWidgetSecretKind; value: string }>,
+) {
+ const supplied = new Set<string>();
+ for (const secret of secrets) {
+ const auth = sources[secret.sourceId]?.auth;
+ const usesHeaders = typeof auth === "object" && auth.type === "headers";
+ if (!usesHeaders && !isCustomWidgetHeaderSecretKind(secret.kind)) continue;
+ const identity = `${secret.sourceId}:${secret.kind}`;
+ if (
+ supplied.has(identity) ||
+ !getCustomWidgetRequiredSecretKinds(auth).includes(secret.kind) ||
+ !isCustomWidgetHeaderSecretValue(secret.value)
+ ) {
+ throw new CustomWidgetDomainError({
+ code: "BAD_REQUEST",
+ message: "Preview credentials do not match declared authentication headers",
+ });
+ }
+ supplied.add(identity);
+ }
+}
diff --git a/packages/custom-widgets/src/server/request-executor.ts b/packages/custom-widgets/src/server/request-executor.ts
index dfd6bb463..7bfe80411 100644
--- a/packages/custom-widgets/src/server/request-executor.ts
+++ b/packages/custom-widgets/src/server/request-executor.ts
@@ -240,7 +240,7 @@ function buildHeaders(input: CustomWidgetHttpRequest, url: URL, body: string | u
if (body === undefined) headers.delete("Content-Type");
if (input.auth) {
if (input.auth.type === "apiKeyHeader") assertSafeStaticHeaders({ [input.auth.headerName ?? "X-API-Key"]: "" });
- applyAuth(headers, url, input.auth.type, input.auth.secrets, input.auth.headerName);
+ applyAuth(headers, url, input.auth.type, input.auth.secrets, input.auth.headerName, input.auth.headerSlots);
for (const [name, value] of Object.entries(input.auth.headers ?? {})) headers.set(name, value);
for (const [name, value] of Object.entries(input.auth.query ?? {})) url.searchParams.set(name, value);
}
diff --git a/packages/custom-widgets/src/server/request-types.ts b/packages/custom-widgets/src/server/request-types.ts
index b62f66cee..e0cf02b00 100644
--- a/packages/custom-widgets/src/server/request-types.ts
+++ b/packages/custom-widgets/src/server/request-types.ts
@@ -1,12 +1,13 @@
import type { ConnectionOptions } from "node:tls";
import type { IntegrationHttpBodyAuth } from "@homarr/definitions";
-import type { CustomWidgetMethod } from "../core";
+import type { CustomWidgetMethod, CustomWidgetAuthenticationHeader } from "../core";
export interface CustomWidgetAuthConfig {
type: string;
secrets: Array<{ kind: string; value: string }>;
headerName?: string | null;
+ headerSlots?: CustomWidgetAuthenticationHeader[];
headers?: Record<string, string>;
query?: Record<string, string>;
body?: IntegrationHttpBodyAuth;
diff --git a/packages/custom-widgets/src/test/authoring-resources.spec.ts b/packages/custom-widgets/src/test/authoring-resources.spec.ts
index 97715f5f1..677d60a81 100644
--- a/packages/custom-widgets/src/test/authoring-resources.spec.ts
+++ b/packages/custom-widgets/src/test/authoring-resources.spec.ts
@@ -22,7 +22,7 @@ const skillSourceDirectory = path.resolve(import.meta.dirname, "../../../../.age
describe("authoring resources", () => {
it("returns the complete portable skill and keeps every bundled source file in sync", () => {
const skill = getCustomWidgetSkill();
- expect(skill).toMatchObject({ name: "homarr-custom-widget", version: "2.10.8" });
+ expect(skill).toMatchObject({ name: "homarr-custom-widget", version: "2.10.9" });
expect(skill.skillsShUrl).toContain("skills.sh/homarr-labs/homarr");
expect(skill.sourceUrl).toContain("/tree/HEAD/.agents/skills/homarr-custom-widget");
expect(skill.installCommand).toContain("--skill homarr-custom-widget");
diff --git a/packages/custom-widgets/src/workbench/source-setup.tsx b/packages/custom-widgets/src/workbench/source-setup.tsx
index 70a34b3aa..56cc9b8ef 100644
--- a/packages/custom-widgets/src/workbench/source-setup.tsx
+++ b/packages/custom-widgets/src/workbench/source-setup.tsx
@@ -2,8 +2,13 @@ import type { ReactNode } from "react";
import { Alert, Badge, Checkbox, Group, PasswordInput, Stack, Text, TextInput } from "@mantine/core";
import { IconCheck, IconKey, IconServer, IconX } from "@tabler/icons-react";
-import type { CustomWidgetSecretKind, CustomWidgetSourceSetup, CustomWidgetSourceUrlIssue } from "../core";
-import { getCustomWidgetSourceSetupIssue } from "../core";
+import type {
+ CustomWidgetSecretKind,
+ CustomWidgetLegacySecretKind,
+ CustomWidgetSourceSetup,
+ CustomWidgetSourceUrlIssue,
+} from "../core";
+import { getCustomWidgetSourceSetupIssue, isCustomWidgetHeaderSecretKind } from "../core";
export interface CustomWidgetSourceSetupValue {
baseUrl: string;
@@ -24,7 +29,7 @@ export interface CustomWidgetSourceSetupMessages {
credentialsMissing: string;
credentialsOptional: string;
configured: string;
- secret(kind: CustomWidgetSecretKind): string;
+ secret(kind: CustomWidgetLegacySecretKind): string;
urlError(issue: CustomWidgetSourceUrlIssue): string;
}
@@ -159,10 +164,13 @@ export function CustomWidgetSourceSetupPanel({
)}
{setup.credentialFields.map((field) => {
const Input = field.kind === "username" ? TextInput : PasswordInput;
+ let label: string;
+ if (isCustomWidgetHeaderSecretKind(field.kind)) label = field.destination ?? field.kind.slice(7);
+ else label = messages.secret(field.kind);
return (
<Input
key={field.kind}
- label={messages.secret(field.kind)}
+ label={label}
description={field.destination}
value={value.secrets[field.kind] ?? ""}
placeholder={field.configured ? messages.configured : undefined}