chore(custom-widgets): fix formatting and dependency order
This commit is contained in:
1 parent
19aa92ec25
commit
505032bd21
20 files changed
+630
-1502
No files matched your search
@@ -3,7 +3,12 @@ import { z } from "zod/v4";
|
||||
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { eq, or } from "@homarr/db";
|
||||
import { boards, customWidgetDefinitions, legacyCustomWidgetDefinitions, customWidgetInstallations } from "@homarr/db/schema";
|
||||
import {
|
||||
boards,
|
||||
customWidgetDefinitions,
|
||||
legacyCustomWidgetDefinitions,
|
||||
customWidgetInstallations,
|
||||
} from "@homarr/db/schema";
|
||||
import { collectCustomWidgetRequestReferences, getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { getArtifact, parseBindings } from "./package/records";
|
||||
@@ -118,16 +123,32 @@ export const managementQueryProcedures = {
|
||||
? or(eq(customWidgetInstallations.enabled, true), eq(customWidgetInstallations.id, input.currentId))
|
||||
: eq(customWidgetInstallations.enabled, true),
|
||||
});
|
||||
const packages = await Promise.all(installations.flatMap((installation) => {
|
||||
if (!installation.activeArtifactId) return [];
|
||||
return [getArtifact(ctx, installation.activeArtifactId).then(({ source }) => ({
|
||||
id: installation.id, name: installation.name, description: source.manifest.description ?? null,
|
||||
iconUrl: source.manifest.icon ?? null, options: source.options, defaultOptions: getCustomWidgetDefaultOptions(source.options),
|
||||
template: "", sources: [], requestCapabilities: [], optionRequests: [], updatedAt: installation.updatedAt,
|
||||
migrationRequired: false as const, packageVersion: 3 as const, connections: source.connections,
|
||||
installationBindings: parseBindings(installation.bindings),
|
||||
})).catch(() => null)];
|
||||
}));
|
||||
const packages = await Promise.all(
|
||||
installations.flatMap((installation) => {
|
||||
if (!installation.activeArtifactId) return [];
|
||||
return [
|
||||
getArtifact(ctx, installation.activeArtifactId)
|
||||
.then(({ source }) => ({
|
||||
id: installation.id,
|
||||
name: installation.name,
|
||||
description: source.manifest.description ?? null,
|
||||
iconUrl: source.manifest.icon ?? null,
|
||||
options: source.options,
|
||||
defaultOptions: getCustomWidgetDefaultOptions(source.options),
|
||||
template: "",
|
||||
sources: [],
|
||||
requestCapabilities: [],
|
||||
optionRequests: [],
|
||||
updatedAt: installation.updatedAt,
|
||||
migrationRequired: false as const,
|
||||
packageVersion: 3 as const,
|
||||
connections: source.connections,
|
||||
installationBindings: parseBindings(installation.bindings),
|
||||
}))
|
||||
.catch(() => null),
|
||||
];
|
||||
}),
|
||||
);
|
||||
const result = [...available, ...packages.filter((entry) => entry !== null)];
|
||||
if (!input.currentId || result.some(({ id }) => id === input.currentId)) return result;
|
||||
const legacy = await ctx.db.query.legacyCustomWidgetDefinitions.findFirst({
|
||||
|
||||
@@ -19,7 +19,12 @@ import { customWidgetDefinitions } from "@homarr/db/schema";
|
||||
|
||||
import { permissionRequiredProcedure } from "../../trpc";
|
||||
import { parseCustomWidgetAuthoringInput } from "./authoring-validation";
|
||||
import { createPreviewSession, discardPreviewSession, getPreviewSession, revisePreviewSessionTemplate } from "./preview-sessions";
|
||||
import {
|
||||
createPreviewSession,
|
||||
discardPreviewSession,
|
||||
getPreviewSession,
|
||||
revisePreviewSessionTemplate,
|
||||
} from "./preview-sessions";
|
||||
import { hasSameSecretBinding, requiredSecretKinds } from "./secret-policy";
|
||||
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
|
||||
|
||||
@@ -179,7 +184,8 @@ const previewCreateProcedure = permissionRequiredProcedure
|
||||
});
|
||||
|
||||
export const previewBaseProcedures = {
|
||||
previewDiscard: permissionRequiredProcedure.requiresPermission("admin")
|
||||
previewDiscard: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(z.object({ sessionId: z.string().min(1) }))
|
||||
.mutation(({ ctx, input }) => discardPreviewSession(input.sessionId, ctx.session.user.id)),
|
||||
previewCreate: previewCreateProcedure,
|
||||
|
||||
@@ -16,55 +16,100 @@ const admin = permissionRequiredProcedure.requiresPermission("admin");
|
||||
export const repairProcedures = {
|
||||
getRaw: admin.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {
|
||||
const row = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id), with: { secrets: true },
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!row) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const result = safeParseStoredCustomWidgetDefinition(row);
|
||||
return {
|
||||
id: row.id, name: row.name, description: row.description, iconUrl: row.iconUrl,
|
||||
sources: row.sources, requests: row.requests, options: row.options, template: row.template,
|
||||
enabled: row.enabled, issues: result.success ? [] : result.issues,
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
iconUrl: row.iconUrl,
|
||||
sources: row.sources,
|
||||
requests: row.requests,
|
||||
options: row.options,
|
||||
template: row.template,
|
||||
enabled: row.enabled,
|
||||
issues: result.success ? [] : result.issues,
|
||||
secrets: row.secrets.map(({ sourceId, kind, updatedAt }) => ({ sourceId, kind, updatedAt, hasValue: true })),
|
||||
};
|
||||
}),
|
||||
repair: admin.input(z.object({ id: z.string(), widget: customWidgetDefinitionSchema })).mutation(async ({ ctx, input }) => {
|
||||
const row = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id), with: { secrets: true },
|
||||
});
|
||||
if (!row) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
let oldSources: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed: unknown = parse(row.sources);
|
||||
if (isRecord(parsed)) oldSources = parsed;
|
||||
} catch { /* Unreadable source bindings cannot safely retain credentials. */ }
|
||||
const removedSources = new Set<string>();
|
||||
const removedSecrets = row.secrets.filter((secret) => {
|
||||
const next = input.widget.sources[secret.sourceId];
|
||||
const previous = customWidgetDefinitionSchema.shape.sources.safeParse({ [secret.sourceId]: oldSources[secret.sourceId] });
|
||||
let oldSource;
|
||||
if (previous.success) oldSource = previous.data[secret.sourceId];
|
||||
if (!next || !oldSource || !hasSameSecretBinding(oldSource, next)) {
|
||||
removedSources.add(secret.sourceId);
|
||||
return true;
|
||||
repair: admin
|
||||
.input(z.object({ id: z.string(), widget: customWidgetDefinitionSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const row = await ctx.db.query.customWidgetDefinitions.findFirst({
|
||||
where: eq(customWidgetDefinitions.id, input.id),
|
||||
with: { secrets: true },
|
||||
});
|
||||
if (!row) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
let oldSources: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed: unknown = parse(row.sources);
|
||||
if (isRecord(parsed)) oldSources = parsed;
|
||||
} catch {
|
||||
/* Unreadable source bindings cannot safely retain credentials. */
|
||||
}
|
||||
const type = typeof next.auth === "string" ? next.auth : next.auth.type;
|
||||
return !new Set<string>(requiredSecretKinds(type)).has(secret.kind);
|
||||
});
|
||||
const changes = { ...serializeCustomWidgetDefinition(input.widget), updatedAt: new Date() };
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction.update(schema.customWidgetDefinitions).set(changes).where(eq(schema.customWidgetDefinitions.id, input.id));
|
||||
for (const secret of removedSecrets) await transaction.delete(schema.customWidgetSecrets).where(and(eq(schema.customWidgetSecrets.definitionId, input.id), eq(schema.customWidgetSecrets.sourceId, secret.sourceId), eq(schema.customWidgetSecrets.kind, secret.kind)));
|
||||
const removedSources = new Set<string>();
|
||||
const removedSecrets = row.secrets.filter((secret) => {
|
||||
const next = input.widget.sources[secret.sourceId];
|
||||
const previous = customWidgetDefinitionSchema.shape.sources.safeParse({
|
||||
[secret.sourceId]: oldSources[secret.sourceId],
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction.update(customWidgetDefinitions).set(changes).where(eq(customWidgetDefinitions.id, input.id)).run();
|
||||
for (const secret of removedSecrets) transaction.delete(customWidgetSecrets).where(and(eq(customWidgetSecrets.definitionId, input.id), eq(customWidgetSecrets.sourceId, secret.sourceId), eq(customWidgetSecrets.kind, secret.kind))).run();
|
||||
});
|
||||
},
|
||||
});
|
||||
return { id: input.id, managementPath: `/manage/custom-widgets/edit/${input.id}`, credentialsRequired: [...removedSources] };
|
||||
}),
|
||||
let oldSource;
|
||||
if (previous.success) oldSource = previous.data[secret.sourceId];
|
||||
if (!next || !oldSource || !hasSameSecretBinding(oldSource, next)) {
|
||||
removedSources.add(secret.sourceId);
|
||||
return true;
|
||||
}
|
||||
const type = typeof next.auth === "string" ? next.auth : next.auth.type;
|
||||
return !new Set<string>(requiredSecretKinds(type)).has(secret.kind);
|
||||
});
|
||||
const changes = { ...serializeCustomWidgetDefinition(input.widget), updatedAt: new Date() };
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(database, schema) {
|
||||
await database.transaction(async (transaction) => {
|
||||
await transaction
|
||||
.update(schema.customWidgetDefinitions)
|
||||
.set(changes)
|
||||
.where(eq(schema.customWidgetDefinitions.id, input.id));
|
||||
for (const secret of removedSecrets)
|
||||
await transaction
|
||||
.delete(schema.customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.customWidgetSecrets.definitionId, input.id),
|
||||
eq(schema.customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(schema.customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
handleSync(database) {
|
||||
database.transaction((transaction) => {
|
||||
transaction
|
||||
.update(customWidgetDefinitions)
|
||||
.set(changes)
|
||||
.where(eq(customWidgetDefinitions.id, input.id))
|
||||
.run();
|
||||
for (const secret of removedSecrets)
|
||||
transaction
|
||||
.delete(customWidgetSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(customWidgetSecrets.definitionId, input.id),
|
||||
eq(customWidgetSecrets.sourceId, secret.sourceId),
|
||||
eq(customWidgetSecrets.kind, secret.kind),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
});
|
||||
},
|
||||
});
|
||||
return {
|
||||
id: input.id,
|
||||
managementPath: `/manage/custom-widgets/edit/${input.id}`,
|
||||
credentialsRequired: [...removedSources],
|
||||
};
|
||||
}),
|
||||
};
|
||||
@@ -215,39 +215,37 @@ export const customApiRouter = createTRPCRouter({
|
||||
const loadRequests = Object.entries(resolved.definition.requests).filter(
|
||||
([, request]) => request.kind === "query" && request.trigger === "load",
|
||||
);
|
||||
const entries = await mapCustomWidgetRequests(
|
||||
loadRequests, 4, async ([requestId, request]) => {
|
||||
try {
|
||||
const response = await executeRequest(ctx, resolved, { id: requestId, ...request }, {});
|
||||
return [
|
||||
requestId,
|
||||
{
|
||||
data: response.data,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
},
|
||||
const entries = await mapCustomWidgetRequests(loadRequests, 4, async ([requestId, request]) => {
|
||||
try {
|
||||
const response = await executeRequest(ctx, resolved, { id: requestId, ...request }, {});
|
||||
return [
|
||||
requestId,
|
||||
{
|
||||
data: response.data,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
|
||||
},
|
||||
] as const;
|
||||
} catch (error) {
|
||||
return [
|
||||
requestId,
|
||||
{
|
||||
data: null,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: false,
|
||||
status: 0,
|
||||
error: error instanceof Error ? error.message : "Request failed",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
} catch (error) {
|
||||
return [
|
||||
requestId,
|
||||
{
|
||||
data: null,
|
||||
status: {
|
||||
loading: false,
|
||||
ok: false,
|
||||
status: 0,
|
||||
error: error instanceof Error ? error.message : "Request failed",
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
type: "customJsx" as const,
|
||||
|
||||
@@ -60,11 +60,13 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
|
||||
return {
|
||||
session,
|
||||
deviceType: userAgent(opts.headers).device.type,
|
||||
crossSiteRequest: opts.headers.get("sec-fetch-site") === "cross-site" || (() => {
|
||||
const origin = opts.headers.get("origin");
|
||||
if (!origin) return false;
|
||||
return origin !== extractBaseUrlFromHeaders(opts.headers);
|
||||
})(),
|
||||
crossSiteRequest:
|
||||
opts.headers.get("sec-fetch-site") === "cross-site" ||
|
||||
(() => {
|
||||
const origin = opts.headers.get("origin");
|
||||
if (!origin) return false;
|
||||
return origin !== extractBaseUrlFromHeaders(opts.headers);
|
||||
})(),
|
||||
baseUrl: extractBaseUrlFromHeaders(opts.headers),
|
||||
onboardingClaimToken: getOnboardingClaimTokenFromCookieHeader(opts.headers.get("cookie")),
|
||||
db,
|
||||
|
||||
Reference in new issue
Block a user