feat: configure custom widget sources
This commit is contained in:
43 files changed
+2361
-394
No files matched your search
@@ -93,6 +93,6 @@ Custom JSX v2 provides four HTTP discovery endpoints:
|
||||
- `GET /api/custom-widgets/components` returns the release-matched static component catalog.
|
||||
- `GET /api/custom-widgets/skill` returns the concise live `SKILL.md` plus skills.sh, source, and install metadata. Retrieve the schema, component catalog, and examples through their dedicated resources only when needed.
|
||||
|
||||
Call `customWidget_secretRequestUser` to create a temporary credential entry URL. Do not construct or save this URL.
|
||||
Call `customWidget_configurationRequestUser` to create a temporary API source setup URL where the user can confirm their server URL and enter credentials. Do not construct or save this URL.
|
||||
|
||||
Authenticated tRPC and MCP procedures support definition management, validation, previews, template patches, and credential writes. An exported definition does not contain credentials.
|
||||
@@ -60,14 +60,23 @@ These interfaces do not return an archive URL or archive hash.
|
||||
5. Create a preview session.
|
||||
6. Test the queries and actions.
|
||||
7. Open the preview URL with browser tools.
|
||||
8. Set the credential if the user supplied it.
|
||||
9. Otherwise, ask the user for the credential with the ten-minute Homarr credential URL.
|
||||
10. Inspect the redacted journal.
|
||||
11. Patch the definition until it is valid.
|
||||
12. Create the widget.
|
||||
8. Inspect the redacted journal and revise the local candidate until it is valid.
|
||||
9. Create the widget, including any source URLs and credentials the user already supplied.
|
||||
10. Otherwise, ask the user to configure the saved definition with the ten-minute Homarr source-setup URL.
|
||||
11. Create a final preview with the saved definition ID so Homarr loads its stored credentials, then test it again.
|
||||
12. Update the saved definition if the final verification finds a problem.
|
||||
13. Repeat the procedure for the next widget.
|
||||
|
||||
Each credential URL applies to one definition or preview, one source, and the required fields. The agent receives only the request status.
|
||||
Each source-configuration URL applies to one definition or preview and one source. The user confirms the server URL, network scope, and required credential fields directly in Homarr. The agent receives only request status and never receives plaintext credentials. Preview-scoped values expire with that preview; definition-scoped values persist.
|
||||
|
||||
Agents can install existing widgets without regenerating them:
|
||||
|
||||
1. Search with `customWidget_workshopSearch`.
|
||||
2. Inspect and validate a result with `customWidget_workshopGet`.
|
||||
3. Install it with `customWidget_workshopInstall`.
|
||||
4. Configure deployment-specific URLs and supplied credentials with `customWidget_sourceConfigure`.
|
||||
5. If the agent does not have those values, call `customWidget_configurationRequestUser` and wait for completion.
|
||||
6. Test the installed definition, then use `board_addItem` with kind `customApi` and the returned definition ID.
|
||||
|
||||
Homarr encrypts the plaintext immediately. Homarr does not return the plaintext.
|
||||
|
||||
|
||||
@@ -61,9 +61,17 @@ The workbench keeps one continuous layout with visual source, request, and optio
|
||||
|
||||
Exports, imports, Workshop, MCP, and storage all validate the same schema. Old formats are rejected. A missing definition only renders **Custom widget unavailable** inside its tile.
|
||||
|
||||
When adding widgets while editing a board, the Custom Widgets section always includes **Install from Workshop**. The Workshop and API source review open above the widget picker without closing it. After import, the new definition appears in the picker. Its tile waits for the board to be saved before server requests run and loads automatically after a successful save; no page reload is required.
|
||||
|
||||
## Import and Workshop
|
||||
|
||||
Import review shows origins, authentication modes, network scopes, methods, actions, and permissions. It also lets the user supply each required credential before import. Workshop publishes technically valid widgets immediately; users can vote or report them, and administrators can delete submissions.
|
||||
Import review shows origins, authentication modes, network scopes, methods, actions, and permissions. Every source has a suggested URL, but private and loopback sources must be confirmed or replaced for the current Homarr installation. The same screen accepts API keys, tokens, usernames, and passwords; credentials remain optional at install time and missing values stay visible on the Custom Widgets page.
|
||||
|
||||
For example, installing **Tautulli Activity** asks for both the user's Tautulli URL and API key. A stable public source such as PokéAPI keeps its published URL without creating unnecessary setup work.
|
||||
|
||||
Workshop publishes technically valid widgets immediately; users can vote or report them, and administrators can delete submissions. Publishers should replace personal private-network hosts with a clear service placeholder before publishing.
|
||||
|
||||
Connected agents can search, inspect, and install Workshop widgets with `customWidget_workshopSearch`, `customWidget_workshopGet`, and `customWidget_workshopInstall`. After installation they can set a source URL and credentials with `customWidget_sourceConfigure`, or create a secure user-facing setup URL with `customWidget_configurationRequestUser`. Secret values are never returned through MCP.
|
||||
|
||||
## Bundled examples
|
||||
|
||||
|
||||
@@ -177,13 +177,14 @@ Then, read the live schema and component resources. These resources describe the
|
||||
5. Test named requests with `customWidget_previewQuery` and `customWidget_previewAction`.
|
||||
6. Open the returned preview URL.
|
||||
7. Examine `customWidget_previewJournal`.
|
||||
8. Change the definition with `customWidget_templatePatch` or `customWidget_update`.
|
||||
9. Set a supplied credential with `customWidget_secretSet`.
|
||||
10. Otherwise, call `customWidget_secretRequestUser` to create a ten-minute Homarr entry URL.
|
||||
11. Call `customWidget_create`.
|
||||
12. Repeat this procedure for the next Custom Widget.
|
||||
8. Revise the local candidate and create another preview session until it is ready.
|
||||
9. Call `customWidget_create`, supplying any credentials and deployment-specific source URLs the user already provided.
|
||||
10. If the user must enter the source URL or credentials, call `customWidget_configurationRequestUser` with the new definition ID and wait for completion.
|
||||
11. Create a final preview with that definition ID so Homarr loads its stored credentials, then test it again.
|
||||
12. Use `customWidget_update` or `customWidget_templatePatch` for any final saved-definition corrections.
|
||||
13. Repeat this procedure for the next Custom Widget.
|
||||
|
||||
The agent receives the credential request status. The agent does not receive the plaintext credential.
|
||||
The agent receives the configuration-request status. The agent does not receive plaintext credentials. A preview-scoped setup URL configures only that temporary preview; use a definition-scoped URL when the values must persist.
|
||||
|
||||
Discovery resources:
|
||||
|
||||
@@ -210,7 +211,11 @@ The Custom Widget tools are:
|
||||
- `customWidget_previewAction`
|
||||
- `customWidget_previewJournal`
|
||||
- `customWidget_secretSet`
|
||||
- `customWidget_secretRequestUser`
|
||||
- `customWidget_sourceConfigure`
|
||||
- `customWidget_configurationRequestUser`
|
||||
- `customWidget_workshopSearch`
|
||||
- `customWidget_workshopGet`
|
||||
- `customWidget_workshopInstall`
|
||||
- `customWidget_getAuthoringPrompt`
|
||||
- `customWidget_getSkill`
|
||||
|
||||
|
||||
+22
-6
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Alert, Button, Card, Center, PasswordInput, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
|
||||
import { Alert, Button, Card, Center, PasswordInput, Select, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
|
||||
import { IconCheck, IconKey, IconLock } from "@tabler/icons-react";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
@@ -12,22 +12,30 @@ interface RequestDetails {
|
||||
kinds: Array<"apiKey" | "username" | "password">;
|
||||
expiresAt: number;
|
||||
status: "pending" | "completed";
|
||||
source: {
|
||||
baseUrl: string;
|
||||
networkScope: "public" | "private" | "loopback";
|
||||
};
|
||||
}
|
||||
|
||||
export function CustomWidgetSecretEntry({ token }: { token: string }) {
|
||||
export function CustomWidgetConfigurationEntry({ token }: { token: string }) {
|
||||
const t = useScopedI18n("customWidget.secretEntry");
|
||||
const [details, setDetails] = useState<RequestDetails | null>(null);
|
||||
const [values, setValues] = useState<Record<string, string>>({});
|
||||
const [baseUrl, setBaseUrl] = useState("");
|
||||
const [networkScope, setNetworkScope] = useState<"public" | "private" | "loopback">("public");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void fetch(`/api/custom-widgets/secret-request/${encodeURIComponent(token)}`)
|
||||
void fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`)
|
||||
.then(async (response) => {
|
||||
const body = (await response.json()) as RequestDetails | { error: string };
|
||||
if (!response.ok || "error" in body) throw new Error("error" in body ? body.error : t("unavailable"));
|
||||
setDetails(body);
|
||||
setBaseUrl(body.source.baseUrl);
|
||||
setNetworkScope(body.source.networkScope);
|
||||
})
|
||||
.catch((cause: unknown) => setError(cause instanceof Error ? cause.message : t("unavailable")))
|
||||
.finally(() => setLoading(false));
|
||||
@@ -37,10 +45,10 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/custom-widgets/secret-request/${encodeURIComponent(token)}`, {
|
||||
const response = await fetch(`/api/custom-widgets/configuration-request/${encodeURIComponent(token)}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ secrets: values }),
|
||||
body: JSON.stringify({ baseUrl, networkScope, secrets: values }),
|
||||
});
|
||||
const body = (await response.json()) as { status?: string; error?: string };
|
||||
if (!response.ok) throw new Error(body.error ?? t("saveError"));
|
||||
@@ -81,6 +89,14 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
|
||||
{t("source", { name: details.sourceName })}
|
||||
</Text>
|
||||
</Card>
|
||||
<TextInput label={t("baseUrl")} type="url" value={baseUrl} onChange={(event) => setBaseUrl(event.currentTarget.value)} required />
|
||||
<Select
|
||||
label={t("networkScope")}
|
||||
data={["public", "private", "loopback"]}
|
||||
value={networkScope}
|
||||
allowDeselect={false}
|
||||
onChange={(value) => value && setNetworkScope(value as typeof networkScope)}
|
||||
/>
|
||||
{details.kinds.map((kind) => {
|
||||
const Input = kind === "username" ? TextInput : PasswordInput;
|
||||
return (
|
||||
@@ -97,7 +113,7 @@ export function CustomWidgetSecretEntry({ token }: { token: string }) {
|
||||
})}
|
||||
<Button
|
||||
loading={saving}
|
||||
disabled={details.kinds.some((kind) => !values[kind])}
|
||||
disabled={!URL.canParse(baseUrl) || details.kinds.some((kind) => !values[kind])}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{t("save")}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { CustomWidgetConfigurationEntry } from "./configuration-entry";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Configure custom widget API source",
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
export default async function CustomWidgetConfigurationPage({ params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
return <CustomWidgetConfigurationEntry token={token} />;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { CustomWidgetSecretEntry } from "./secret-entry";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Configure custom widget credential",
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
export default async function CustomWidgetSecretPage({ params }: { params: Promise<{ token: string }> }) {
|
||||
const { token } = await params;
|
||||
return <CustomWidgetSecretEntry token={token} />;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import {
|
||||
claimCustomWidgetConfigurationRequest,
|
||||
completeCustomWidgetConfigurationRequest,
|
||||
configurePreviewSessionSource,
|
||||
getCustomWidgetConfigurationRequest,
|
||||
parseStoredCustomWidgetDefinition,
|
||||
releaseCustomWidgetConfigurationRequest,
|
||||
serializeCustomWidgetDefinition,
|
||||
} from "@homarr/api/custom-widget-configuration";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
|
||||
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
|
||||
import { and, db, eq, handleTransactionsAsync } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ token: string }>;
|
||||
}
|
||||
|
||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||
const { token } = await context.params;
|
||||
const request = await getCustomWidgetConfigurationRequest(token);
|
||||
if (!request)
|
||||
return NextResponse.json({ error: "This source configuration request is invalid or expired." }, { status: 404 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
widgetName: request.widgetName,
|
||||
sourceName: request.sourceName,
|
||||
kinds: request.kinds,
|
||||
source: request.source,
|
||||
expiresAt: request.expiresAt,
|
||||
status: request.status,
|
||||
},
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest, context: RouteContext) {
|
||||
const { token } = await context.params;
|
||||
const pending = await getCustomWidgetConfigurationRequest(token);
|
||||
if (!pending || pending.status !== "pending") {
|
||||
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
|
||||
}
|
||||
const body = (await request.json().catch(() => null)) as {
|
||||
baseUrl?: unknown;
|
||||
networkScope?: unknown;
|
||||
secrets?: Record<string, unknown>;
|
||||
} | null;
|
||||
const sourceResult = customWidgetSourceSchema.safeParse({
|
||||
...pending.source,
|
||||
baseUrl: body?.baseUrl,
|
||||
networkScope: body?.networkScope,
|
||||
});
|
||||
if (!sourceResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: sourceResult.error.issues[0]?.message ?? "Enter a valid server URL." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
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 }]
|
||||
: [];
|
||||
});
|
||||
if (secrets.length !== pending.kinds.length) {
|
||||
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
|
||||
}
|
||||
|
||||
const claimed = await claimCustomWidgetConfigurationRequest(token);
|
||||
if (!claimed) {
|
||||
return NextResponse.json(
|
||||
{ error: "This source configuration request is already being completed." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
if (claimed.target.type === "preview") {
|
||||
await configurePreviewSessionSource(
|
||||
claimed.target.id,
|
||||
claimed.userId,
|
||||
claimed.sourceId,
|
||||
sourceResult.data,
|
||||
secrets,
|
||||
);
|
||||
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
|
||||
} else {
|
||||
const definition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, claimed.target.id),
|
||||
});
|
||||
if (!definition) return NextResponse.json({ error: "The custom widget no longer exists." }, { status: 404 });
|
||||
const parsed = parseStoredCustomWidgetDefinition(definition);
|
||||
const currentSource = parsed.sources[claimed.sourceId];
|
||||
if (!currentSource) {
|
||||
return NextResponse.json(
|
||||
{ error: "This API source changed after the setup link was created. Request a new setup link." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (!hasSameCustomWidgetSourceAuthentication(currentSource, claimed.source)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "This API source authentication changed after the setup link was created. Request a new setup link.",
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
const configuredSource = customWidgetSourceSchema.parse({
|
||||
...currentSource,
|
||||
baseUrl: sourceResult.data.baseUrl,
|
||||
networkScope: sourceResult.data.networkScope,
|
||||
});
|
||||
const definitionChanges = {
|
||||
...serializeCustomWidgetDefinition({
|
||||
...parsed,
|
||||
sources: { ...parsed.sources, [claimed.sourceId]: configuredSource },
|
||||
}),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
const secretRows = secrets.map((secret) => ({
|
||||
definitionId: claimed.target.id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
}));
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set(definitionChanges)
|
||||
.where(eq(schema.customWidgetDefinitions.id, claimed.target.id));
|
||||
for (const secret of secretRows) {
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, claimed.target.id),
|
||||
eq(schema.customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await transaction.insert(schema.customWidgetSecrets).values(secret);
|
||||
}
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set(definitionChanges)
|
||||
.where(eq(customWidgetDefinitions.id, claimed.target.id))
|
||||
.run();
|
||||
for (const secret of secretRows) {
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, claimed.target.id),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
transaction.insert(customWidgetSecrets).values(secret).run();
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await completeCustomWidgetConfigurationRequest(token);
|
||||
return NextResponse.json({ status: "completed" }, { headers: { "Cache-Control": "no-store" } });
|
||||
} finally {
|
||||
await releaseCustomWidgetConfigurationRequest(token);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import {
|
||||
claimCustomWidgetSecretRequest,
|
||||
completeCustomWidgetSecretRequest,
|
||||
getCustomWidgetSecretRequest,
|
||||
releaseCustomWidgetSecretRequest,
|
||||
setPreviewSessionSecrets,
|
||||
} from "@homarr/api/custom-widget-secrets";
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
|
||||
import { and, db, eq } from "@homarr/db";
|
||||
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ token: string }>;
|
||||
}
|
||||
|
||||
export async function GET(_request: NextRequest, context: RouteContext) {
|
||||
const { token } = await context.params;
|
||||
const request = await getCustomWidgetSecretRequest(token);
|
||||
if (!request) return NextResponse.json({ error: "This credential request is invalid or expired." }, { status: 404 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
widgetName: request.widgetName,
|
||||
sourceName: request.sourceName,
|
||||
kinds: request.kinds,
|
||||
expiresAt: request.expiresAt,
|
||||
status: request.status,
|
||||
},
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest, context: RouteContext) {
|
||||
const { token } = await context.params;
|
||||
const pending = await getCustomWidgetSecretRequest(token);
|
||||
if (!pending || pending.status !== "pending") {
|
||||
return NextResponse.json({ error: "This credential request is invalid, completed, or expired." }, { status: 404 });
|
||||
}
|
||||
const body = (await request.json().catch(() => null)) as { secrets?: Record<string, unknown> } | null;
|
||||
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 }]
|
||||
: [];
|
||||
});
|
||||
if (secrets.length !== pending.kinds.length) {
|
||||
return NextResponse.json({ error: "Enter every requested credential field." }, { status: 400 });
|
||||
}
|
||||
|
||||
const claimed = await claimCustomWidgetSecretRequest(token);
|
||||
if (!claimed) {
|
||||
return NextResponse.json({ error: "This credential request is already being completed." }, { status: 409 });
|
||||
}
|
||||
|
||||
try {
|
||||
if (claimed.target.type === "preview") {
|
||||
await setPreviewSessionSecrets(claimed.target.id, claimed.userId, secrets);
|
||||
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
|
||||
} else {
|
||||
const definition = await db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, claimed.target.id),
|
||||
});
|
||||
if (!definition) return NextResponse.json({ error: "The custom widget no longer exists." }, { status: 404 });
|
||||
for (const secret of secrets) {
|
||||
await db
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, claimed.target.id),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
await db.insert(customWidgetSecrets).values({
|
||||
definitionId: claimed.target.id,
|
||||
sourceId: secret.sourceId,
|
||||
kind: secret.kind,
|
||||
encryptedValue: encryptSecret(secret.value),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
}
|
||||
await db
|
||||
.update(customWidgetDefinitions)
|
||||
.set({ updatedAt: new Date() })
|
||||
.where(eq(customWidgetDefinitions.id, claimed.target.id));
|
||||
}
|
||||
|
||||
await completeCustomWidgetSecretRequest(token);
|
||||
return NextResponse.json({ status: "completed" }, { headers: { "Cache-Control": "no-store" } });
|
||||
} finally {
|
||||
await releaseCustomWidgetSecretRequest(token);
|
||||
}
|
||||
}
|
||||
@@ -2,35 +2,64 @@
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Alert, PasswordInput, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { IconKey } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { getCustomWidgetSecretRequirements, getImportReview } from "@homarr/custom-widgets/core";
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import { ImportReviewDialog } from "@homarr/custom-widgets/workbench";
|
||||
import { applyCustomWidgetSourceSetup, getCustomWidgetSourceSetups, getImportReview } from "@homarr/custom-widgets/core";
|
||||
import type { CustomWidgetSecretKind, HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
import {
|
||||
createCustomWidgetSourceSetupValues,
|
||||
CustomWidgetSourceSetupPanel,
|
||||
ImportReviewDialog,
|
||||
isCustomWidgetSourceSetupReady,
|
||||
} from "@homarr/custom-widgets/workbench";
|
||||
import type { CustomWidgetSourceSetupValue } from "@homarr/custom-widgets/workbench";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
interface CustomWidgetImportDialogProps {
|
||||
opened: boolean;
|
||||
widget: HomarrCustomWidgetV2 | null;
|
||||
stackId?: string;
|
||||
zIndex?: number;
|
||||
onClose(): void;
|
||||
onImported?(result: { id: string }): void;
|
||||
}
|
||||
|
||||
export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }: CustomWidgetImportDialogProps) {
|
||||
export function CustomWidgetImportDialog({
|
||||
opened,
|
||||
widget,
|
||||
stackId,
|
||||
zIndex,
|
||||
onClose,
|
||||
onImported,
|
||||
}: CustomWidgetImportDialogProps) {
|
||||
const t = useScopedI18n("customWidget");
|
||||
const router = useRouter();
|
||||
const utils = clientApi.useUtils();
|
||||
const [values, setValues] = useState<Record<string, string>>({});
|
||||
const review = useMemo(() => getImportReview(widget), [widget]);
|
||||
const requirements = useMemo(() => getCustomWidgetSecretRequirements(widget?.sources ?? {}), [widget]);
|
||||
const setups = useMemo(() => getCustomWidgetSourceSetups(widget?.sources ?? {}), [widget]);
|
||||
const [values, setValues] = useState<Record<string, CustomWidgetSourceSetupValue>>({});
|
||||
const configuredWidget = useMemo(() => {
|
||||
if (!widget) return null;
|
||||
return {
|
||||
...widget,
|
||||
sources: applyCustomWidgetSourceSetup(
|
||||
widget.sources,
|
||||
Object.fromEntries(
|
||||
Object.entries(values).map(([sourceId, value]) => [
|
||||
sourceId,
|
||||
{ baseUrl: value.baseUrl, networkScope: value.networkScope },
|
||||
]),
|
||||
),
|
||||
),
|
||||
};
|
||||
}, [values, widget]);
|
||||
const review = useMemo(() => getImportReview(configuredWidget), [configuredWidget]);
|
||||
const mutation = clientApi.customWidget.import.useMutation({
|
||||
onSuccess: (result) => {
|
||||
showSuccessNotification({ title: t("action.import"), message: t("notification.imported") });
|
||||
void utils.customWidget.list.invalidate();
|
||||
void utils.customWidget.available.invalidate();
|
||||
void revalidatePathActionAsync("/manage/custom-widgets").then(() => router.refresh());
|
||||
onImported?.(result);
|
||||
onClose();
|
||||
@@ -41,27 +70,27 @@ export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (opened) setValues({});
|
||||
}, [opened, widget]);
|
||||
|
||||
const setValue = (sourceId: string, kind: string, value: string) => {
|
||||
setValues((current) => ({ ...current, [`${sourceId}:${kind}`]: value }));
|
||||
};
|
||||
if (opened) setValues(createCustomWidgetSourceSetupValues(setups));
|
||||
}, [opened, setups]);
|
||||
|
||||
const importWidget = () => {
|
||||
if (!widget) return;
|
||||
const secrets = requirements.flatMap((requirement) => {
|
||||
const value = values[`${requirement.sourceId}:${requirement.kind}`] ?? "";
|
||||
return value.trim() ? [{ sourceId: requirement.sourceId, kind: requirement.kind, value }] : [];
|
||||
});
|
||||
mutation.mutate({ widget, secrets });
|
||||
if (!configuredWidget) return;
|
||||
const secrets = Object.entries(values).flatMap(([sourceId, value]) =>
|
||||
Object.entries(value.secrets).flatMap(([kind, secret]) =>
|
||||
secret?.trim() ? [{ sourceId, kind: kind as CustomWidgetSecretKind, value: secret }] : [],
|
||||
),
|
||||
);
|
||||
mutation.mutate({ widget: configuredWidget, secrets });
|
||||
};
|
||||
|
||||
return (
|
||||
<ImportReviewDialog
|
||||
opened={opened}
|
||||
stackId={stackId}
|
||||
zIndex={zIndex}
|
||||
review={review}
|
||||
pending={mutation.isPending}
|
||||
confirmDisabled={!isCustomWidgetSourceSetupReady(setups, values)}
|
||||
onClose={onClose}
|
||||
onConfirm={importWidget}
|
||||
messages={{
|
||||
@@ -80,39 +109,27 @@ export function CustomWidgetImportDialog({ opened, widget, onClose, onImported }
|
||||
permission: (permission) => t(`preview.request.permission.${permission}` as never),
|
||||
}}
|
||||
>
|
||||
{requirements.length > 0 && (
|
||||
<Stack gap="sm">
|
||||
<Alert color="yellow" icon={<IconKey size={16} />}>
|
||||
<Text fw={600} size="sm">
|
||||
{t("importReview.credentials.title")}
|
||||
</Text>
|
||||
<Text size="sm">{t("importReview.credentials.description")}</Text>
|
||||
</Alert>
|
||||
{requirements.map((requirement) => {
|
||||
const key = `${requirement.sourceId}:${requirement.kind}`;
|
||||
const label = `${requirement.sourceName} · ${t(`importReview.credentials.field.${requirement.kind}`)}`;
|
||||
const description = requirement.destination
|
||||
? t(
|
||||
requirement.authType === "apiKeyHeader"
|
||||
? "importReview.credentials.header"
|
||||
: "importReview.credentials.query",
|
||||
{ name: requirement.destination },
|
||||
)
|
||||
: undefined;
|
||||
const Input = requirement.kind === "username" ? TextInput : PasswordInput;
|
||||
return (
|
||||
<Input
|
||||
key={key}
|
||||
label={label}
|
||||
description={description}
|
||||
value={values[key] ?? ""}
|
||||
onChange={(event) => setValue(requirement.sourceId, requirement.kind, event.currentTarget.value)}
|
||||
autoComplete="off"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
)}
|
||||
<CustomWidgetSourceSetupPanel
|
||||
setups={setups}
|
||||
values={values}
|
||||
onChange={(sourceId, value) => setValues((current) => ({ ...current, [sourceId]: value }))}
|
||||
messages={{
|
||||
title: t("importReview.sourceSetup.title"),
|
||||
description: t("importReview.sourceSetup.description"),
|
||||
suggestedUrl: t("importReview.sourceSetup.suggestedUrl"),
|
||||
baseUrl: t("workbench.sources.baseUrl"),
|
||||
networkScope: t("workbench.sources.networkScope"),
|
||||
authentication: t("workbench.sources.authentication"),
|
||||
confirmUrl: t("importReview.sourceSetup.confirmUrl"),
|
||||
ready: t("importReview.sourceSetup.ready"),
|
||||
needsUrl: t("importReview.sourceSetup.needsUrl"),
|
||||
credentialsMissing: t("importReview.sourceSetup.credentialsMissing"),
|
||||
credentialsOptional: t("importReview.sourceSetup.credentialsOptional"),
|
||||
configured: t("workbench.sources.configured"),
|
||||
secret: (kind) => t(`importReview.credentials.field.${kind}`),
|
||||
urlError: (issue) => t(`workbench.sources.baseUrlError.${issue}`),
|
||||
}}
|
||||
/>
|
||||
</ImportReviewDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { WorkshopClient, WORKSHOP_API_URL } from "@homarr/workshop";
|
||||
import { WorkshopBackend } from "@homarr/workshop/backend";
|
||||
import { WORKSHOP_API_URL } from "@homarr/workshop/schema";
|
||||
|
||||
let browserClient: WorkshopClient | undefined;
|
||||
let browserClient: WorkshopBackend | undefined;
|
||||
|
||||
export function createWorkshopClient() {
|
||||
if (typeof document === "undefined") return new WorkshopClient(WORKSHOP_API_URL);
|
||||
if (typeof document === "undefined") return new WorkshopBackend(WORKSHOP_API_URL);
|
||||
if (browserClient) return browserClient;
|
||||
|
||||
const runtimeUrl = document.querySelector<HTMLMetaElement>('meta[name="homarr-workshop-api-url"]')?.content;
|
||||
|
||||
browserClient = new WorkshopClient(runtimeUrl || WORKSHOP_API_URL);
|
||||
browserClient = new WorkshopBackend(runtimeUrl || WORKSHOP_API_URL);
|
||||
return browserClient;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useState } from "react";
|
||||
import { Button, Modal } from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { Button, getDefaultZIndex, Modal, useModalsStack } from "@mantine/core";
|
||||
import { IconBuildingStore } from "@tabler/icons-react";
|
||||
|
||||
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
|
||||
@@ -11,33 +11,52 @@ import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
|
||||
import { WorkshopBrowser } from "./workshop-browser";
|
||||
|
||||
export function WorkshopInstallButton() {
|
||||
interface WorkshopInstallButtonProps {
|
||||
children?: ReactNode;
|
||||
fullWidth?: boolean;
|
||||
}
|
||||
|
||||
export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallButtonProps = {}) {
|
||||
const t = useScopedI18n("workshop");
|
||||
const [opened, controls] = useDisclosure(false);
|
||||
const [reviewOpened, reviewControls] = useDisclosure(false);
|
||||
const stack = useModalsStack(["workshop", "review"]);
|
||||
const [pendingWidget, setPendingWidget] = useState<HomarrCustomWidgetV2 | null>(null);
|
||||
const zIndex = getDefaultZIndex("modal") + 10;
|
||||
|
||||
const closeReview = () => {
|
||||
stack.close("review");
|
||||
setPendingWidget(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="default" leftSection={<IconBuildingStore size={16} />} onClick={controls.open}>
|
||||
{t("title")}
|
||||
<Button
|
||||
variant="default"
|
||||
leftSection={<IconBuildingStore size={16} />}
|
||||
onClick={() => stack.open("workshop")}
|
||||
fullWidth={fullWidth}
|
||||
>
|
||||
{children ?? t("title")}
|
||||
</Button>
|
||||
<Modal opened={opened} onClose={controls.close} title={t("installDialog")} size="90%">
|
||||
<WorkshopBrowser
|
||||
onInstall={async (widget) => {
|
||||
setPendingWidget(widget);
|
||||
reviewControls.open();
|
||||
<Modal.Stack>
|
||||
<Modal {...stack.register("workshop")} title={t("installDialog")} size="90%" zIndex={zIndex}>
|
||||
<WorkshopBrowser
|
||||
onInstall={async (widget) => {
|
||||
setPendingWidget(widget);
|
||||
stack.open("review");
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
<CustomWidgetImportDialog
|
||||
{...stack.register("review")}
|
||||
widget={pendingWidget}
|
||||
zIndex={zIndex + 1}
|
||||
onClose={closeReview}
|
||||
onImported={() => {
|
||||
stack.closeAll();
|
||||
setPendingWidget(null);
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
<CustomWidgetImportDialog
|
||||
opened={reviewOpened}
|
||||
widget={pendingWidget}
|
||||
onClose={() => {
|
||||
reviewControls.close();
|
||||
setPendingWidget(null);
|
||||
}}
|
||||
onImported={controls.close}
|
||||
/>
|
||||
</Modal.Stack>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Alert, Button, FileInput, Group, Modal, Stack, Textarea, TextInput } from "@mantine/core";
|
||||
import { Alert, Button, Checkbox, FileInput, Group, Modal, Stack, Textarea, TextInput } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import type { WorkshopUser } from "@homarr/workshop";
|
||||
import { useWorkshopCreateMutation } from "@homarr/workshop/backend";
|
||||
import type { WorkshopUser } from "@homarr/workshop/schema";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { createWorkshopClient } from "./workshop-client";
|
||||
@@ -26,9 +27,14 @@ export function WorkshopPublishModal({
|
||||
const [title, setTitle] = useState(widget.name);
|
||||
const [description, setDescription] = useState("");
|
||||
const [screenshots, setScreenshots] = useState<File[]>([]);
|
||||
const [pending, setPending] = useState(false);
|
||||
const createSubmission = useWorkshopCreateMutation(client);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [published, setPublished] = useState(false);
|
||||
const [sourceUrlsReviewed, setSourceUrlsReviewed] = useState(false);
|
||||
const definition = clientApi.customWidget.get.useQuery({ id: widget.id }, { enabled: opened });
|
||||
const privateSources = Object.entries(definition.data?.sources ?? {}).filter(
|
||||
([, source]) => source.networkScope !== "public",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = client.subscribeToAuth(setUser);
|
||||
@@ -42,22 +48,20 @@ export function WorkshopPublishModal({
|
||||
setScreenshots([]);
|
||||
setError(null);
|
||||
setPublished(false);
|
||||
setSourceUrlsReviewed(false);
|
||||
}, [opened, widget.name]);
|
||||
|
||||
const publish = async () => {
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const definition = await utils.customWidget.export.fetch({ id: widget.id });
|
||||
await client.create(
|
||||
{ type: "customWidget", title, description, content: JSON.stringify(definition) },
|
||||
await createSubmission.mutateAsync({
|
||||
input: { type: "customWidget", title, description, content: JSON.stringify(definition) },
|
||||
screenshots,
|
||||
);
|
||||
});
|
||||
setPublished(true);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : t("publish.error"));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -109,8 +113,25 @@ export function WorkshopPublishModal({
|
||||
value={screenshots}
|
||||
onChange={setScreenshots}
|
||||
/>
|
||||
{privateSources.length > 0 && (
|
||||
<Alert color="yellow">
|
||||
{t("publish.privateSourceWarning", {
|
||||
sources: privateSources.map(([sourceId, source]) => source.name ?? sourceId).join(", "),
|
||||
})}
|
||||
<Checkbox
|
||||
mt="sm"
|
||||
checked={sourceUrlsReviewed}
|
||||
onChange={(event) => setSourceUrlsReviewed(event.currentTarget.checked)}
|
||||
label={t("publish.privateSourceConfirmation")}
|
||||
/>
|
||||
</Alert>
|
||||
)}
|
||||
{error && <Alert color="red">{error}</Alert>}
|
||||
<Button loading={pending} disabled={!user || title.trim().length < 3} onClick={() => void publish()}>
|
||||
<Button
|
||||
loading={createSubmission.isPending}
|
||||
disabled={!user || title.trim().length < 3 || (privateSources.length > 0 && !sourceUrlsReviewed)}
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
{t("publish.action")}
|
||||
</Button>
|
||||
</>
|
||||
|
||||
Reference in new issue
Block a user