refactor: trim v2 release hardening

This commit is contained in:
ajnart committed 2026-07-30 16:24:11 +02:00
1 parent 3cf1dc8341
commit 657704340c
79 files changed
+405 -3378

No files matched your search

-1
View File
@@ -63,7 +63,6 @@
},
"devDependencies": {
"@homarr/tsconfig": "workspace:^0.1.0",
"ioredis": "catalog:",
"typescript": "catalog:"
}
}
@@ -1,6 +1,5 @@
export * from "./router/custom-widget/configuration-requests";
export { configurePreviewSessionSource } from "./router/custom-widget/preview-sessions";
export { invalidateCustomWidgetResponseCache } from "./router/custom-widget/request-executor";
export {
parseStoredCustomWidgetDefinition,
serializeCustomWidgetDefinition,
@@ -1,4 +0,0 @@
export function useProcessLocalCustomWidgetState(runtime: { CI?: string; NODE_ENV?: string } = process.env): boolean {
if (runtime.NODE_ENV === "production") return false;
return runtime.NODE_ENV === "test" || runtime.CI === "true";
}
@@ -4,8 +4,6 @@ import type { RedisClient } from "@homarr/core/infrastructure/redis";
import type { CustomWidgetSecretKind } from "@homarr/custom-widgets/core";
import type { CustomWidgetSource } from "@homarr/custom-widgets/core";
import { useProcessLocalCustomWidgetState } from "../../custom-widget-state-mode";
const CONFIGURATION_REQUEST_TTL_MS = 10 * 60_000;
const CONFIGURATION_REQUEST_PREFIX = "custom-widget:configuration-request:";
const CONFIGURATION_REQUEST_LOCK_PREFIX = "custom-widget:configuration-request-lock:";
@@ -28,7 +26,7 @@ const localLocks = new Set<string>();
let redis: RedisClient | undefined;
function getRedis() {
if (useProcessLocalCustomWidgetState()) return undefined;
if (process.env.CI !== undefined || process.env.NODE_ENV === "test") return undefined;
redis ??= createRedisClient();
return redis;
}
@@ -12,9 +12,8 @@ import {
customWidgetUpdateSchema,
} from "@homarr/custom-widgets/core";
import { createTRPCRouter } from "../../trpc";
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
import { insertCustomWidgetDefinition } from "./definition-insert";
import { permissionRequiredProcedure } from "../../trpc";
import { managementQueryProcedures } from "./management-queries";
import { metadataProcedures } from "./metadata-procedures";
import { previewActionProcedures } from "./preview-action-procedures";
@@ -6,8 +6,8 @@ import { eq, or } from "@homarr/db";
import { boards, customWidgetDefinitions, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
import { collectCustomWidgetRequestReferences } from "@homarr/custom-widgets/core";
import { throwIfActionForbiddenAsync } from "../board/board-access";
import { permissionRequiredProcedure } from "../../trpc";
import { throwIfActionForbiddenAsync } from "../board/board-access";
import { parseStoredCustomWidgetDefinition } from "./stored-definition";
import { executeCustomWidgetRequest } from "./request-executor";
import {
@@ -143,10 +143,16 @@ export const managementQueryProcedures = {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), request.permission);
const source = definition.sources[request.source];
if (!source) throw new TRPCError({ code: "NOT_FOUND", message: "Option query source not found" });
const values = resolveOptionRequestValues(request, input.params);
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
const response = await executeCustomWidgetRequest(
{
const release = await acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session.user.id,
itemId: `configuration:${input.boardId}`,
definitionId: input.definitionId,
});
try {
const values = resolveOptionRequestValues(request, input.params);
const authType = typeof source.auth === "string" ? source.auth : source.auth.type;
const response = await executeCustomWidgetRequest({
baseUrl: source.baseUrl,
targetUrl: renderRequestTarget(source.baseUrl, request, values),
method: request.method,
@@ -171,23 +177,16 @@ export const managementQueryProcedures = {
kind: "query",
cacheKey: `custom-widget:options:${input.definitionId}:${getCustomWidgetCacheVersion(stored)}:${request.id}:${hashRuntimeParams(values)}`,
cacheTtlSeconds: request.cacheSeconds ?? 30,
},
{
acquireRequestLimit: () =>
acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session.user.id,
itemId: `configuration:${input.boardId}`,
definitionId: input.definitionId,
}),
},
);
return {
ok: response.ok,
status: response.status,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
};
});
return {
ok: response.ok,
status: response.status,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
};
} finally {
await release();
}
}),
};
@@ -45,9 +45,15 @@ export const previewActionProcedures = {
if ((request.confirmation || request.method === "DELETE") && input.confirmed !== true) {
throw new TRPCError({ code: "PRECONDITION_FAILED", message: "This action requires confirmation" });
}
const release = await acquireCustomWidgetRequestLimit({
category: request.method === "DELETE" ? "delete" : "action",
userId: ctx.session.user.id,
itemId: `preview:${session.id}`,
definitionId: session.definitionId ?? `preview:${session.id}`,
});
const startedAt = Date.now();
const response = await executeCustomWidgetRequest(
{
try {
const response = await executeCustomWidgetRequest({
baseUrl: resolved.source.baseUrl,
targetUrl,
method: request.method,
@@ -56,38 +62,31 @@ export const previewActionProcedures = {
auth: request.auth === "none" ? undefined : resolved.auth,
networkScope: resolved.source.networkScope,
kind: "action",
},
{
acquireRequestLimit: () =>
acquireCustomWidgetRequestLimit({
category: request.method === "DELETE" ? "delete" : "action",
userId: ctx.session.user.id,
itemId: `preview:${session.id}`,
definitionId: session.definitionId ?? `preview:${session.id}`,
}),
},
);
if (response.ok && request.invalidates?.length) {
await invalidateCustomWidgetResponseCache(
request.invalidates.map((requestId) => `custom-jsx:preview:${session.id}:${requestId}:`),
);
});
if (response.ok && request.invalidates?.length) {
invalidateCustomWidgetResponseCache(
request.invalidates.map((requestId) => `custom-jsx:preview:${session.id}:${requestId}:`),
);
}
await recordPreviewJournal(session, {
requestId: request.id,
kind: "action",
method: request.method,
path: request.path,
status: response.status,
durationMs: Date.now() - startedAt,
simulated: false,
});
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
simulated: false as const,
};
} finally {
await release();
}
await recordPreviewJournal(session, {
requestId: request.id,
kind: "action",
method: request.method,
path: request.path,
status: response.status,
durationMs: Date.now() - startedAt,
simulated: false,
});
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
simulated: false as const,
};
}),
};
@@ -9,7 +9,6 @@ import {
resolvePreviewRequestParams,
} from "./preview-procedure-helpers";
import { executeCustomWidgetRequest } from "./request-executor";
import { invalidateCustomWidgetResponseCache } from "./request-executor";
import { hashRuntimeParams, renderRequestBody, renderRequestTarget } from "./request-manifest";
import { acquireCustomWidgetRequestLimit } from "./request-limits";
import { getPreviewJournal, getPreviewSession, setPreviewSessionLiveActions } from "./preview-sessions";
@@ -35,9 +34,15 @@ export const previewQueryProcedures = {
const params = resolvePreviewRequestParams(request, session.options, input.params);
const targetUrl = renderRequestTarget(resolved.source.baseUrl, request, params);
const body = renderRequestBody(request, params);
const release = await acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session.user.id,
itemId: `preview:${session.id}`,
definitionId: session.definitionId ?? `preview:${session.id}`,
});
const startedAt = Date.now();
const response = await executeCustomWidgetRequest(
{
try {
const response = await executeCustomWidgetRequest({
baseUrl: resolved.source.baseUrl,
targetUrl,
method: request.method,
@@ -48,67 +53,26 @@ export const previewQueryProcedures = {
kind: "query",
cacheKey: `custom-jsx:preview:${session.id}:${request.id}:${hashRuntimeParams(params)}`,
cacheTtlSeconds: request.cacheSeconds,
},
{
acquireRequestLimit: () =>
acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session.user.id,
itemId: `preview:${session.id}`,
definitionId: session.definitionId ?? `preview:${session.id}`,
}),
},
);
await recordPreviewJournal(session, {
requestId: request.id,
kind: "query",
method: request.method,
path: request.path,
status: response.status,
durationMs: Date.now() - startedAt,
simulated: false,
});
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
};
}),
previewRefresh: permissionRequiredProcedure
.requiresPermission("admin")
.input(
z.object({
sessionId: z.string().min(1),
requestIds: z.array(z.string().min(1).max(64)).max(64).default([]),
all: z.boolean().default(false),
}),
)
.mutation(async ({ ctx, input }) => {
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
const queryRequestIds = Object.entries(session.requests).flatMap(([requestId, request]) =>
request.kind === "query" ? [requestId] : [],
);
const requested = new Set(input.all ? queryRequestIds : input.requestIds);
const requestIds = queryRequestIds.filter((requestId) => requested.has(requestId));
if (requestIds.length === 0) return { requestIds };
const release = await acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session.user.id,
itemId: `preview:${session.id}`,
definitionId: session.definitionId ?? `preview:${session.id}`,
});
try {
await invalidateCustomWidgetResponseCache(
requestIds.map((requestId) => `custom-jsx:preview:${session.id}:${requestId}:`),
);
});
await recordPreviewJournal(session, {
requestId: request.id,
kind: "query",
method: request.method,
path: request.path,
status: response.status,
durationMs: Date.now() - startedAt,
simulated: false,
});
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: response.data,
error: response.ok ? undefined : `HTTP ${response.status}: ${response.statusText}`,
};
} finally {
await release();
}
return { requestIds };
}),
setPreviewLiveActions: permissionRequiredProcedure
@@ -10,7 +10,6 @@ import type {
PreviewSessionStore,
} from "@homarr/custom-widgets/server";
import { useProcessLocalCustomWidgetState } from "../../custom-widget-state-mode";
import { toTrpcError } from "./domain-error";
const SESSION_PREFIX = "custom-widget:preview-session:";
@@ -70,7 +69,7 @@ class RedisPreviewSessionStore implements PreviewSessionStore {
let service: CustomWidgetPreviewSessionService | undefined;
function getService() {
if (service) return service;
const useLocal = useProcessLocalCustomWidgetState();
const useLocal = process.env.CI !== undefined || process.env.NODE_ENV === "test";
service = new CustomWidgetPreviewSessionService({
createId,
encrypt: encryptSecret,
@@ -1,11 +1,10 @@
import { TRPCError } from "@trpc/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import {
assertJsonBudget as assertDomainJsonBudget,
assertSafeStaticHeaders as assertDomainSafeStaticHeaders,
classifyAddress,
executeCustomWidgetRequest as executeDomainRequest,
invalidateCustomWidgetResponseCache as invalidateDomainResponseCache,
MAX_REQUEST_BODY_BYTES,
MAX_RESPONSE_BODY_BYTES,
MAX_RESPONSE_JSON_DEPTH,
@@ -15,10 +14,8 @@ import {
validateCustomWidgetUrl as validateDomainUrl,
} from "@homarr/custom-widgets/server";
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "@homarr/custom-widgets/server";
import { CustomWidgetDomainError } from "@homarr/custom-widgets/server";
import { toTrpcError } from "./domain-error";
import { invalidateCustomWidgetResponseCache, withCustomWidgetResponseCache } from "./response-cache";
export type {
CustomWidgetAuthConfig,
@@ -35,10 +32,6 @@ export {
const logger = createLogger({ module: "custom-widget:http" });
export interface CustomWidgetRequestExecutionOptions {
acquireRequestLimit?: () => Promise<() => Promise<void>>;
}
export function assertJsonBudget(value: unknown): void {
try {
assertDomainJsonBudget(value);
@@ -79,64 +72,16 @@ export async function resolveAndValidateHost(hostname: string, scope: CustomWidg
}
}
export async function executeCustomWidgetRequest(
input: CustomWidgetHttpRequest,
options: CustomWidgetRequestExecutionOptions = {},
): Promise<CustomWidgetHttpResponse> {
export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
try {
return await withCustomWidgetResponseCache(input, async () => {
const release = await options.acquireRequestLimit?.();
try {
return await executeDomainRequest({
...input,
cacheKey: undefined,
cacheTtlSeconds: undefined,
logError: (event) => {
if (event.reason === "timeout") return;
logger.error("Custom widget request failed", {
event: "custom_widget_request_failed",
...event,
});
},
});
} finally {
await release?.();
}
return await executeDomainRequest({
...input,
logError: (event) => logger.error("Custom widget request failed", event),
});
} catch (error) {
if (error instanceof CustomWidgetDomainError) {
logger.warn("Custom widget request rejected", {
event:
error.reason === "timeout"
? "custom_widget_request_timeout"
: error.code === "FORBIDDEN"
? "custom_widget_network_scope_rejected"
: error.code === "BAD_GATEWAY"
? "custom_widget_upstream_failed"
: "custom_widget_request_rejected",
code: error.code,
origin: safeOrigin(input.baseUrl),
method: input.method,
});
toTrpcError(error);
}
if (error instanceof TRPCError) throw error;
logger.error("Custom widget request failed", {
event: "custom_widget_request_failed",
errorName: "UnexpectedTransportError",
origin: safeOrigin(input.baseUrl),
method: input.method,
});
throw new TRPCError({ code: "BAD_GATEWAY", message: "External request failed" });
toTrpcError(error);
}
}
export { invalidateCustomWidgetResponseCache };
function safeOrigin(value: string): string {
try {
return new URL(value).origin;
} catch {
return "invalid";
}
}
export const invalidateCustomWidgetResponseCache = (prefixes: readonly string[]) =>
invalidateDomainResponseCache(prefixes);
@@ -1,10 +1,9 @@
import { createLogger } from "@homarr/core/infrastructure/logs";
import { createRedisClient } from "@homarr/core/infrastructure/redis";
import type { RedisClient } from "@homarr/core/infrastructure/redis";
import { CustomWidgetDomainError, CustomWidgetRequestLimiter } from "@homarr/custom-widgets/server";
import { CustomWidgetRequestLimiter } from "@homarr/custom-widgets/server";
import type { RequestLimitInput, RequestLimitStore } from "@homarr/custom-widgets/server";
import { useProcessLocalCustomWidgetState } from "../../custom-widget-state-mode";
import { toTrpcError } from "./domain-error";
const logger = createLogger({ module: "custom-widget:limits" });
@@ -46,13 +45,12 @@ class RedisRequestLimitStore implements RequestLimitStore {
let limiter: CustomWidgetRequestLimiter | undefined;
function getLimiter() {
if (limiter) return limiter;
const useLocal = useProcessLocalCustomWidgetState();
const useLocal = process.env.CI !== undefined || process.env.NODE_ENV === "test";
const store = useLocal ? undefined : new RedisRequestLimitStore(createRedisClient());
limiter = new CustomWidgetRequestLimiter({
store,
onStoreError: (error) =>
logger.error("Custom widget rate limiter is unavailable", {
event: "custom_widget_rate_limit_store_unavailable",
errorName: error instanceof Error ? error.name : "UnknownError",
}),
});
@@ -72,14 +70,6 @@ export async function acquireCustomWidgetRequestLimit(input: RequestLimitInput):
}
};
} catch (error) {
if (error instanceof CustomWidgetDomainError && error.code === "TOO_MANY_REQUESTS") {
logger.warn("Rejected custom widget request at rate or concurrency limit", {
event: "custom_widget_rate_limit_rejected",
category: input.category,
authenticated: Boolean(input.userId),
retryAfterMs: error.retryAfterMs,
});
}
toTrpcError(error);
}
}
@@ -1,296 +0,0 @@
import { Buffer } from "node:buffer";
import { createHash } from "node:crypto";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { createRedisClient } from "@homarr/core/infrastructure/redis";
import type { RedisClient } from "@homarr/core/infrastructure/redis";
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "@homarr/custom-widgets/server";
import { useProcessLocalCustomWidgetState } from "../../custom-widget-state-mode";
const CACHE_KEY_PREFIX = "homarr:custom-widget:response:v1:";
const VERSION_KEY_PREFIX = "homarr:custom-widget:response-version:v1:";
const CACHE_INDEX_KEY = "homarr:custom-widget:response-index:v1";
const MAX_CACHE_ENTRIES = 1_000;
const MAX_CACHE_TTL_SECONDS = 3_600;
const MAX_CACHE_VALUE_BYTES = 1024 * 1024 + 1024;
const VERSION_TTL_SECONDS = MAX_CACHE_TTL_SECONDS * 2;
const logger = createLogger({ module: "custom-widget:response-cache" });
interface ResponseCacheStore {
getVersions(namespaces: readonly string[]): Promise<number[]>;
incrementVersion(namespace: string): Promise<void>;
get(key: string): Promise<string | null>;
set(key: string, namespace: string, value: string, ttlSeconds: number): Promise<void>;
}
class RedisResponseCacheStore implements ResponseCacheStore {
public constructor(private readonly redis: RedisClient) {}
public async getVersions(namespaces: readonly string[]): Promise<number[]> {
const values = await this.redis.mget(...namespaces.map(getVersionKey));
return values.map((value) => {
const parsed = Number(value ?? 0);
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
});
}
public async incrementVersion(namespace: string): Promise<void> {
const key = getVersionKey(namespace);
await this.redis.multi().incr(key).expire(key, VERSION_TTL_SECONDS).exec();
}
public get(key: string): Promise<string | null> {
return this.redis.get(key);
}
public async set(key: string, _namespace: string, value: string, ttlSeconds: number): Promise<void> {
await this.redis.eval(
`
redis.call("SET", KEYS[1], ARGV[1], "EX", ARGV[2])
redis.call("ZADD", KEYS[2], ARGV[3] + (ARGV[2] * 1000), KEYS[1])
redis.call("ZREMRANGEBYSCORE", KEYS[2], "-inf", ARGV[3])
local count = redis.call("ZCARD", KEYS[2])
local maximum = tonumber(ARGV[4])
if count > maximum then
local victims = redis.call("ZRANGE", KEYS[2], 0, count - maximum - 1)
for _, victim in ipairs(victims) do
redis.call("DEL", victim)
redis.call("ZREM", KEYS[2], victim)
end
end
redis.call("EXPIRE", KEYS[2], ARGV[5])
return 1
`,
2,
key,
CACHE_INDEX_KEY,
value,
ttlSeconds,
Date.now(),
MAX_CACHE_ENTRIES,
VERSION_TTL_SECONDS,
);
}
}
class LocalResponseCacheStore implements ResponseCacheStore {
private readonly versions = new Map<string, number>();
private readonly responses = new Map<string, { namespace: string; value: string; expiresAt: number }>();
public async getVersions(namespaces: readonly string[]): Promise<number[]> {
return namespaces.map((namespace) => this.versions.get(namespace) ?? 0);
}
public async incrementVersion(namespace: string): Promise<void> {
this.versions.set(namespace, (this.versions.get(namespace) ?? 0) + 1);
}
public async get(key: string): Promise<string | null> {
const response = this.responses.get(key);
if (!response) return null;
if (response.expiresAt <= Date.now()) {
this.responses.delete(key);
return null;
}
return response.value;
}
public async set(key: string, namespace: string, value: string, ttlSeconds: number): Promise<void> {
for (const [candidate, response] of this.responses) {
if (response.expiresAt <= Date.now()) this.responses.delete(candidate);
}
while (this.responses.size >= MAX_CACHE_ENTRIES) {
const oldest = this.responses.keys().next().value as string | undefined;
if (!oldest) break;
this.responses.delete(oldest);
}
this.responses.set(key, {
namespace,
value,
expiresAt: Date.now() + ttlSeconds * 1000,
});
}
}
let defaultStore: ResponseCacheStore | undefined;
let defaultController: CustomWidgetResponseCacheController | undefined;
function getDefaultStore(): ResponseCacheStore {
if (defaultStore) return defaultStore;
const useLocal = useProcessLocalCustomWidgetState();
defaultStore = useLocal ? new LocalResponseCacheStore() : new RedisResponseCacheStore(createRedisClient());
return defaultStore;
}
export interface CustomWidgetResponseCacheController {
withCache(
input: CustomWidgetHttpRequest,
execute: () => Promise<CustomWidgetHttpResponse>,
): Promise<CustomWidgetHttpResponse>;
invalidate(prefixes: readonly string[]): Promise<void>;
}
class ResponseCacheController implements CustomWidgetResponseCacheController {
private readonly inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
private readonly pendingInvalidations = new Set<string>();
public constructor(private readonly store: ResponseCacheStore) {}
public async withCache(
input: CustomWidgetHttpRequest,
execute: () => Promise<CustomWidgetHttpResponse>,
): Promise<CustomWidgetHttpResponse> {
const ttlSeconds = Math.min(Math.max(input.cacheTtlSeconds ?? 0, 0), MAX_CACHE_TTL_SECONDS);
if (input.kind !== "query" || !input.cacheKey || ttlSeconds <= 0) return execute();
const namespace = getCacheNamespace(input.cacheKey);
if (!namespace) {
logger.warn("Rejected malformed custom widget response cache key", {
event: "custom_widget_cache_key_rejected",
});
return execute();
}
let responseKey: string;
let pending: Promise<CustomWidgetHttpResponse> | undefined;
let cached: CustomWidgetHttpResponse | null = null;
try {
await this.flushPendingInvalidations();
const invalidationNamespaces = getInvalidationNamespaces(namespace);
const versions = await this.store.getVersions(invalidationNamespaces);
responseKey = getResponseKey(input.cacheKey, versions);
pending = this.inFlight.get(responseKey);
if (!pending) {
cached = parseCachedResponse(await this.store.get(responseKey));
if (!cached) pending = this.inFlight.get(responseKey);
}
} catch (error) {
logger.warn("Custom widget response cache unavailable; executing without cache", {
event: "custom_widget_cache_unavailable",
errorName: error instanceof Error ? error.name : "UnknownError",
});
return execute();
}
if (pending) return pending;
if (cached) return cached;
let request: Promise<CustomWidgetHttpResponse>;
request = Promise.resolve()
.then(execute)
.then(async (response) => {
if (!response.ok) return response;
try {
const serialized = JSON.stringify(response);
if (Buffer.byteLength(serialized, "utf8") > MAX_CACHE_VALUE_BYTES) {
logger.warn("Skipped oversized custom widget response cache entry", {
event: "custom_widget_cache_entry_rejected",
cacheNamespace: namespace,
});
return response;
}
await this.store.set(responseKey, namespace, serialized, ttlSeconds);
} catch (error) {
logger.warn("Failed to store custom widget response cache entry", {
event: "custom_widget_cache_write_failed",
errorName: error instanceof Error ? error.name : "UnknownError",
});
}
return response;
})
.finally(() => {
if (this.inFlight.get(responseKey) === request) this.inFlight.delete(responseKey);
});
this.inFlight.set(responseKey, request);
return request;
}
public async invalidate(prefixes: readonly string[]): Promise<void> {
const namespaces = [...new Set(prefixes.filter((prefix) => prefix.length > 0))];
if (namespaces.length === 0) return;
try {
await Promise.all(namespaces.map((namespace) => this.store.incrementVersion(namespace)));
for (const namespace of namespaces) this.pendingInvalidations.delete(namespace);
} catch (error) {
namespaces.forEach((namespace) => this.pendingInvalidations.add(namespace));
logger.error("Failed to invalidate custom widget response cache", {
event: "custom_widget_cache_invalidation_failed",
invalidationCount: namespaces.length,
errorName: error instanceof Error ? error.name : "UnknownError",
});
}
}
private async flushPendingInvalidations(): Promise<void> {
if (this.pendingInvalidations.size === 0) return;
const namespaces = [...this.pendingInvalidations];
await Promise.all(namespaces.map((namespace) => this.store.incrementVersion(namespace)));
namespaces.forEach((namespace) => this.pendingInvalidations.delete(namespace));
}
}
function getDefaultController(): CustomWidgetResponseCacheController {
defaultController ??= new ResponseCacheController(getDefaultStore());
return defaultController;
}
export function createRedisCustomWidgetResponseCache(redis: RedisClient): CustomWidgetResponseCacheController {
return new ResponseCacheController(new RedisResponseCacheStore(redis));
}
export function withCustomWidgetResponseCache(
input: CustomWidgetHttpRequest,
execute: () => Promise<CustomWidgetHttpResponse>,
): Promise<CustomWidgetHttpResponse> {
return getDefaultController().withCache(input, execute);
}
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): Promise<void> {
return getDefaultController().invalidate(prefixes);
}
function getCacheNamespace(key: string): string | null {
const separator = key.lastIndexOf(":");
if (separator <= 0 || separator === key.length - 1) return null;
return key.slice(0, separator + 1);
}
function getInvalidationNamespaces(namespace: string): string[] {
const namespaces: string[] = [];
for (let separator = namespace.indexOf(":"); separator >= 0; separator = namespace.indexOf(":", separator + 1)) {
namespaces.push(namespace.slice(0, separator + 1));
}
return namespaces;
}
function getResponseKey(key: string, versions: readonly number[]): string {
return `${CACHE_KEY_PREFIX}${hash(`${versions.join(".")}:${key}`)}`;
}
function getVersionKey(namespace: string): string {
return `${VERSION_KEY_PREFIX}${hash(namespace)}`;
}
function hash(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
function parseCachedResponse(value: string | null): CustomWidgetHttpResponse | null {
if (!value) return null;
try {
const parsed = JSON.parse(value) as Partial<CustomWidgetHttpResponse>;
if (
typeof parsed.ok !== "boolean" ||
typeof parsed.status !== "number" ||
typeof parsed.statusText !== "string" ||
!("data" in parsed)
) {
return null;
}
return parsed as CustomWidgetHttpResponse;
} catch {
return null;
}
}
@@ -1,118 +0,0 @@
import { createId } from "@homarr/common";
import type * as CustomWidgetServer from "@homarr/custom-widgets/server";
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
executeDomainRequest: vi.fn(async () => ({
ok: true,
status: 200,
statusText: "OK",
data: { value: 42 },
})),
logger: {
debug: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
},
}));
vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => mocks.logger,
}));
vi.mock("@homarr/custom-widgets/server", async (importOriginal) => {
const actual = await importOriginal<typeof CustomWidgetServer>();
return {
...actual,
executeCustomWidgetRequest: mocks.executeDomainRequest,
};
});
import { executeCustomWidgetRequest } from "../../custom-widget/request-executor";
describe("custom widget request execution limits", () => {
beforeEach(() => {
mocks.executeDomainRequest.mockClear();
mocks.logger.error.mockClear();
});
test("acquires capacity only for a query cache miss", async () => {
const release = vi.fn(async () => undefined);
const acquireRequestLimit = vi.fn(async () => release);
const input = {
baseUrl: "https://example.com",
targetUrl: "https://example.com/status",
method: "GET" as const,
networkScope: "public" as const,
kind: "query" as const,
cacheKey: `custom-jsx:${createId()}:version:status:params`,
cacheTtlSeconds: 60,
};
await executeCustomWidgetRequest(input, { acquireRequestLimit });
await executeCustomWidgetRequest(input, { acquireRequestLimit });
expect(mocks.executeDomainRequest).toHaveBeenCalledOnce();
expect(acquireRequestLimit).toHaveBeenCalledOnce();
expect(release).toHaveBeenCalledOnce();
});
test("keeps every action inside request accounting", async () => {
const release = vi.fn(async () => undefined);
const acquireRequestLimit = vi.fn(async () => release);
const input = {
baseUrl: "https://example.com",
targetUrl: "https://example.com/action",
method: "POST" as const,
networkScope: "public" as const,
kind: "action" as const,
};
await executeCustomWidgetRequest(input, { acquireRequestLimit });
await executeCustomWidgetRequest(input, { acquireRequestLimit });
expect(mocks.executeDomainRequest).toHaveBeenCalledTimes(2);
expect(acquireRequestLimit).toHaveBeenCalledTimes(2);
expect(release).toHaveBeenCalledTimes(2);
});
test("replaces an unexpected apiKeyQuery transport error with safe public and loggable metadata", async () => {
const apiKey = "api-key-query-secret";
const tokenizedUrl = `https://example.com/status?access_token=${apiKey}`;
const transportFailure = new Error(`Transport failed for ${tokenizedUrl}`);
transportFailure.name = `SocketError:${tokenizedUrl}`;
mocks.executeDomainRequest.mockRejectedValueOnce(transportFailure);
const error = await executeCustomWidgetRequest({
baseUrl: "https://example.com",
targetUrl: "https://example.com/status",
method: "GET",
networkScope: "public",
kind: "query",
auth: {
type: "apiKeyQuery",
headerName: "access_token",
secrets: [{ kind: "apiKey", value: apiKey }],
},
}).then(
() => undefined,
(cause: unknown) => cause,
);
expect(error).toMatchObject({
code: "BAD_GATEWAY",
message: "External request failed",
});
expect((error as Error).cause).toBeUndefined();
expect(mocks.logger.error).toHaveBeenCalledWith("Custom widget request failed", {
event: "custom_widget_request_failed",
errorName: "UnexpectedTransportError",
origin: "https://example.com",
method: "GET",
});
expect(JSON.stringify(mocks.logger.error.mock.calls)).not.toContain(apiKey);
expect(JSON.stringify(mocks.logger.error.mock.calls)).not.toContain("access_token");
expect(String(error)).not.toContain(apiKey);
});
});
@@ -1,58 +0,0 @@
import { randomUUID } from "node:crypto";
import { RedisContainer } from "@testcontainers/redis";
import type { StartedRedisContainer } from "@testcontainers/redis";
import { Redis } from "ioredis";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { createRedisCustomWidgetResponseCache } from "../../custom-widget/response-cache";
describe("custom widget response cache across replicas", () => {
let container: StartedRedisContainer | undefined;
let redisA: Redis | undefined;
let redisB: Redis | undefined;
beforeAll(async () => {
container = await new RedisContainer("redis:7.4-alpine").start();
redisA = new Redis(container.getConnectionUrl());
redisB = new Redis(container.getConnectionUrl());
await Promise.all([redisA.ping(), redisB.ping()]);
}, 60_000);
afterAll(async () => {
await Promise.all([redisA?.quit(), redisB?.quit()]);
await container?.stop();
}, 30_000);
test("an action on one replica invalidates a query cached by another replica", async () => {
if (!redisA || !redisB) throw new Error("Redis test clients were not initialized");
const cacheA = createRedisCustomWidgetResponseCache(redisA);
const cacheB = createRedisCustomWidgetResponseCache(redisB);
const itemNamespace = `custom-jsx:${randomUUID()}:`;
const namespace = `${itemNamespace}definition-v1:status:`;
const input = {
baseUrl: "https://example.com",
method: "GET" as const,
networkScope: "public" as const,
kind: "query" as const,
cacheKey: `${namespace}same-options`,
cacheTtlSeconds: 60,
};
let calls = 0;
const execute = async () => ({
ok: true,
status: 200,
statusText: "OK",
data: { calls: ++calls },
});
await expect(cacheA.withCache(input, execute)).resolves.toMatchObject({ data: { calls: 1 } });
await expect(cacheB.withCache(input, execute)).resolves.toMatchObject({ data: { calls: 1 } });
expect(calls).toBe(1);
await cacheB.invalidate([itemNamespace]);
await expect(cacheA.withCache(input, execute)).resolves.toMatchObject({ data: { calls: 2 } });
expect(calls).toBe(2);
});
});
@@ -1,91 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import { invalidateCustomWidgetResponseCache, withCustomWidgetResponseCache } from "../../custom-widget/response-cache";
const response = (calls: number) => ({
ok: true,
status: 200,
statusText: "OK",
data: { calls },
});
describe("custom widget shared response cache", () => {
test("deduplicates queries and invalidates them with a versioned namespace", async () => {
const itemNamespace = "custom-jsx:test-item:";
const namespace = `${itemNamespace}test-version:status:`;
const input = {
baseUrl: "https://example.com",
method: "GET" as const,
networkScope: "public" as const,
kind: "query" as const,
cacheKey: `${namespace}test-params`,
cacheTtlSeconds: 60,
};
let calls = 0;
const execute = async () => response(++calls);
await expect(
Promise.all([withCustomWidgetResponseCache(input, execute), withCustomWidgetResponseCache(input, execute)]),
).resolves.toEqual([response(1), response(1)]);
await expect(withCustomWidgetResponseCache(input, execute)).resolves.toEqual(response(1));
await invalidateCustomWidgetResponseCache([itemNamespace]);
await expect(withCustomWidgetResponseCache(input, execute)).resolves.toEqual(response(2));
});
test("does not cache actions or zero-TTL queries", async () => {
let calls = 0;
const execute = async () => response(++calls);
const baseInput = {
baseUrl: "https://example.com",
method: "GET" as const,
networkScope: "public" as const,
cacheKey: "custom-jsx:no-cache:version:status:params",
cacheTtlSeconds: 0,
};
await withCustomWidgetResponseCache({ ...baseInput, kind: "query" }, execute);
await withCustomWidgetResponseCache({ ...baseInput, kind: "query" }, execute);
await withCustomWidgetResponseCache({ ...baseInput, kind: "action" }, execute);
await withCustomWidgetResponseCache({ ...baseInput, kind: "action" }, execute);
expect(calls).toBe(4);
});
test("does not retry a rejected query execution", async () => {
const failure = new Error("upstream failed");
const execute = vi.fn(async () => {
throw failure;
});
const input = {
baseUrl: "https://example.com",
method: "GET" as const,
networkScope: "public" as const,
kind: "query" as const,
cacheKey: "custom-jsx:rejected:version:status:params",
cacheTtlSeconds: 60,
};
await expect(withCustomWidgetResponseCache(input, execute)).rejects.toBe(failure);
expect(execute).toHaveBeenCalledOnce();
});
test("does not retry a synchronous query execution failure", async () => {
const failure = new Error("failed before returning a promise");
const execute = vi.fn(() => {
throw failure;
});
const input = {
baseUrl: "https://example.com",
method: "GET" as const,
networkScope: "public" as const,
kind: "query" as const,
cacheKey: "custom-jsx:synchronous-failure:version:status:params",
cacheTtlSeconds: 60,
};
await expect(withCustomWidgetResponseCache(input, execute)).rejects.toBe(failure);
expect(execute).toHaveBeenCalledOnce();
});
});
@@ -1,16 +0,0 @@
import { describe, expect, test } from "vitest";
import { useProcessLocalCustomWidgetState } from "../../../custom-widget-state-mode";
describe("Custom Widget shared-state selection", () => {
test.each([
[{ NODE_ENV: "test", CI: undefined }, true],
[{ NODE_ENV: "development", CI: "true" }, true],
[{ NODE_ENV: "development", CI: "false" }, false],
[{ NODE_ENV: "production", CI: "true" }, false],
[{ NODE_ENV: "production", CI: "false" }, false],
[{ NODE_ENV: "production", CI: undefined }, false],
])("uses process-local state only in tests: %o", (runtime, expected) => {
expect(useProcessLocalCustomWidgetState(runtime)).toBe(expected);
});
});
@@ -1,46 +0,0 @@
import { describe, expect, test } from "vitest";
import { ipAddressFromHeaders, rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createTRPCContext } from "../../trpc";
describe("tRPC client address context", () => {
test("does not use a forged forwarded address as the anonymous rate-limit identity", () => {
const headers = new Headers({
"user-agent": "vitest",
"x-forwarded-for": " 198.51.100.10, 10.0.0.2 ",
"x-real-ip": "203.0.113.20",
});
expect(ipAddressFromHeaders(headers)).toBe("198.51.100.10");
expect(rateLimitAddressFromHeaders(headers)).toBe("203.0.113.20");
expect(createTRPCContext({ headers, session: null }).clientAddress).toBe("203.0.113.20");
});
test("canonicalizes a trusted IPv6 address", () => {
const headers = new Headers({
"user-agent": "vitest",
"x-real-ip": " 2001:0DB8:0000:0000:0000:0000:0000:0001 ",
});
expect(rateLimitAddressFromHeaders(headers)).toBe("2001:db8::1");
expect(createTRPCContext({ headers, session: null }).clientAddress).toBe("2001:db8::1");
});
test("uses a shared anonymous bucket without a valid trusted address", () => {
const headers = new Headers({
"user-agent": "vitest",
"x-forwarded-for": "198.51.100.10",
"x-real-ip": "not-an-ip",
});
expect(rateLimitAddressFromHeaders(headers)).toBeNull();
expect(createTRPCContext({ headers, session: null }).clientAddress).toBeUndefined();
});
test("retains the general client-address helper for existing API-key behavior", () => {
const headers = new Headers({ "user-agent": "vitest", "x-real-ip": " 203.0.113.20 " });
expect(ipAddressFromHeaders(headers)).toBe("203.0.113.20");
});
});
@@ -3,47 +3,22 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import type { Session } from "@homarr/auth";
import { createId } from "@homarr/common";
import { encryptSecret } from "@homarr/common/server";
import { eq } from "@homarr/db";
import {
boardUserPermissions,
boards,
customWidgetDefinitions,
customWidgetSecrets,
items,
legacyCustomWidgetDefinitions,
users,
} from "@homarr/db/schema";
import { boardUserPermissions, boards, customWidgetDefinitions, items, users } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
const mocks = vi.hoisted(() => {
const executeRequestImplementation = async (
_input: unknown,
options?: { acquireRequestLimit?: () => Promise<() => Promise<void>> },
) => {
const release = await options?.acquireRequestLimit?.();
try {
return { ok: true, status: 200, statusText: "OK", data: { value: 42 } };
} finally {
await release?.();
}
};
return {
acquireRequestLimit: vi.fn(async () => async () => undefined),
invalidateCache: vi.fn(async () => undefined),
executeRequestImplementation,
executeRequest: vi.fn(executeRequestImplementation),
};
});
const mocks = vi.hoisted(() => ({
executeRequest: vi.fn(async () => ({ ok: true, status: 200, statusText: "OK", data: { value: 42 } })),
}));
vi.mock("../../custom-widget/request-executor", () => ({
executeCustomWidgetRequest: mocks.executeRequest,
invalidateCustomWidgetResponseCache: mocks.invalidateCache,
invalidateCustomWidgetResponseCache: vi.fn(),
}));
vi.mock("../../custom-widget/request-limits", () => ({
acquireCustomWidgetRequestLimit: mocks.acquireRequestLimit,
acquireCustomWidgetRequestLimit: vi.fn(async () => async () => undefined),
}));
import { serializeCustomWidgetDefinition } from "../../custom-widget/stored-definition";
@@ -79,15 +54,6 @@ const definition: HomarrCustomWidgetV2 = {
permission: "view",
trigger: "manual",
},
"private-status": {
source: "default",
kind: "query",
method: "GET",
path: "/private-status",
auth: "inherit",
permission: "modify",
trigger: "manual",
},
toggle: {
source: "default",
kind: "action",
@@ -118,7 +84,7 @@ const createSession = (userId: string): Session => ({
expires: new Date(Date.now() + 60_000).toISOString(),
});
async function setup(isPublic = true, customDefinition = definition, apiKey?: string) {
async function setup(isPublic = true) {
const db = createDb();
const ownerId = createId();
const boardId = createId();
@@ -128,18 +94,9 @@ async function setup(isPublic = true, customDefinition = definition, apiKey?: st
await db.insert(boards).values({ id: boardId, name: createId(), creatorId: ownerId, isPublic });
await db.insert(customWidgetDefinitions).values({
id: definitionId,
...serializeCustomWidgetDefinition(customDefinition),
...serializeCustomWidgetDefinition(definition),
creatorId: ownerId,
});
if (apiKey) {
await db.insert(customWidgetSecrets).values({
definitionId,
sourceId: "default",
kind: "apiKey",
encryptedValue: encryptSecret(apiKey),
updatedAt: new Date(),
});
}
await db.insert(items).values({
id: itemId,
boardId,
@@ -150,21 +107,11 @@ async function setup(isPublic = true, customDefinition = definition, apiKey?: st
}
describe("Custom JSX v2 board router", () => {
beforeEach(() => {
mocks.acquireRequestLimit.mockClear();
mocks.executeRequest.mockReset();
mocks.executeRequest.mockImplementation(mocks.executeRequestImplementation);
mocks.invalidateCache.mockClear();
});
beforeEach(() => mocks.executeRequest.mockClear());
test("allows public queries only through the definition placed on an accessible board", async () => {
const { db, itemId } = await setup();
const caller = customApiRouter.createCaller({
db,
deviceType: undefined,
session: null,
clientAddress: "198.51.100.10",
});
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
await expect(caller.queryRequest({ itemId, requestId: "status", params: { name: "homarr" } })).resolves.toEqual(
expect.objectContaining({ ok: true, data: { value: 42 } }),
@@ -173,156 +120,6 @@ describe("Custom JSX v2 board router", () => {
code: "NOT_FOUND",
});
expect(mocks.executeRequest).toHaveBeenCalledOnce();
expect(mocks.acquireRequestLimit).toHaveBeenCalledWith(
expect.objectContaining({ userId: undefined, anonymousId: "198.51.100.10" }),
);
});
test("redacts apiKeyQuery transport details from anonymous load and manual query results", async () => {
const apiKey = "api-key-query-secret";
const credentialedDefinition: HomarrCustomWidgetV2 = {
...definition,
sources: {
default: {
name: "API",
baseUrl: "https://example.com",
networkScope: "public",
auth: { type: "apiKeyQuery", name: "access_token" },
},
},
};
const { db, itemId } = await setup(true, credentialedDefinition, apiKey);
mocks.executeRequest.mockImplementation(async (input) => {
const request = input as {
targetUrl: URL;
auth?: { headerName?: string | null; secrets: Array<{ kind: string; value: string }> };
};
const secret = request.auth?.secrets.find(({ kind }) => kind === "apiKey")?.value;
const tokenizedUrl = new URL(request.targetUrl);
tokenizedUrl.searchParams.set(request.auth?.headerName ?? "api_key", secret ?? "");
const failure = new Error(`Transport failed for ${tokenizedUrl.toString()}`);
failure.name = `SocketError:${tokenizedUrl.toString()}`;
throw failure;
});
const caller = customApiRouter.createCaller({
db,
deviceType: undefined,
session: null,
clientAddress: "198.51.100.10",
});
const loadResult = await caller.getData({ itemId });
const queryError = await caller.queryRequest({ itemId, requestId: "status", params: { name: "homarr" } }).then(
() => undefined,
(cause: unknown) => cause,
);
expect(loadResult.status["load-status"]).toMatchObject({
ok: false,
status: 0,
error: "Request failed",
});
expect(queryError).toMatchObject({
code: "BAD_GATEWAY",
message: "External request failed",
});
expect((queryError as Error).cause).toBeUndefined();
expect(mocks.executeRequest).toHaveBeenCalledWith(
expect.objectContaining({
auth: expect.objectContaining({
type: "apiKeyQuery",
headerName: "access_token",
secrets: [{ kind: "apiKey", value: apiKey }],
}),
}),
expect.any(Object),
);
expect(JSON.stringify(loadResult)).not.toContain(apiKey);
expect(JSON.stringify(loadResult)).not.toContain("access_token");
expect(String(queryError)).not.toContain(apiKey);
expect(String(queryError)).not.toContain("access_token");
});
test("requires authentication before invalidating board-authorized query caches", async () => {
const { db, itemId } = await setup();
const viewerId = createId();
await db.insert(users).values({ id: viewerId });
const anonymous = customApiRouter.createCaller({
db,
deviceType: undefined,
session: null,
clientAddress: "198.51.100.10",
});
await expect(anonymous.refreshQueries({ itemId, all: true })).rejects.toMatchObject({ code: "UNAUTHORIZED" });
expect(mocks.invalidateCache).not.toHaveBeenCalled();
const authenticated = customApiRouter.createCaller({
db,
deviceType: undefined,
session: createSession(viewerId),
clientAddress: "198.51.100.10",
});
await expect(authenticated.refreshQueries({ itemId, all: true })).resolves.toEqual({
requestIds: ["load-status", "status"],
});
expect(mocks.invalidateCache).toHaveBeenCalledOnce();
expect(mocks.invalidateCache).toHaveBeenCalledWith([
expect.stringMatching(new RegExp(`^custom-jsx:${itemId}:.+:load-status:$`, "u")),
expect.stringMatching(new RegExp(`^custom-jsx:${itemId}:.+:status:$`, "u")),
]);
expect(mocks.acquireRequestLimit).toHaveBeenCalledWith(
expect.objectContaining({
category: "query",
userId: viewerId,
itemId,
}),
);
expect(mocks.executeRequest).not.toHaveBeenCalled();
});
test("queues valid load requests within the per-viewer concurrency limit", async () => {
const requests = Object.fromEntries(
Array.from({ length: 6 }, (_, index) => [
`load-${index}`,
{
source: "default",
kind: "query" as const,
method: "GET" as const,
path: `/status/${index}`,
auth: "inherit" as const,
permission: "view" as const,
trigger: "load" as const,
},
]),
);
const { db, itemId } = await setup(true, { ...definition, requests });
let active = 0;
let maximumActive = 0;
mocks.executeRequest.mockImplementation(async (_input, options) => {
const release = await options?.acquireRequestLimit?.();
active += 1;
maximumActive = Math.max(maximumActive, active);
try {
await new Promise((resolve) => setTimeout(resolve, 5));
return { ok: true, status: 200, statusText: "OK", data: { value: active } };
} finally {
active -= 1;
await release?.();
}
});
const caller = customApiRouter.createCaller({
db,
deviceType: undefined,
session: null,
clientAddress: "198.51.100.10",
});
const result = await caller.getData({ itemId });
expect(Object.keys(result.data)).toHaveLength(6);
expect(mocks.executeRequest).toHaveBeenCalledTimes(6);
expect(maximumActive).toBe(4);
});
test("hides private boards and disabled definitions before executing a request", async () => {
@@ -357,25 +154,6 @@ describe("Custom JSX v2 board router", () => {
expect(mocks.executeRequest).not.toHaveBeenCalled();
});
test("surfaces a real preserved v1 placement as migration-required", async () => {
const { db, itemId, definitionId, ownerId } = await setup();
await db.delete(customWidgetDefinitions).where(eq(customWidgetDefinitions.id, definitionId));
await db.insert(legacyCustomWidgetDefinitions).values({
id: definitionId,
name: "Legacy weather",
url: "https://example.com/weather",
displayConfig: stringifySuperJson({ type: "singleValue", jsonPath: "$.temperature" }),
creatorId: ownerId,
});
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
await expect(caller.getData({ itemId })).rejects.toMatchObject({
code: "PRECONDITION_FAILED",
message: "LEGACY_CUSTOM_WIDGET_MIGRATION_REQUIRED",
});
expect(mocks.executeRequest).not.toHaveBeenCalled();
});
test("rejects request-kind and parameter mismatches", async () => {
const { db, itemId, ownerId } = await setup();
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(ownerId) });
@@ -402,7 +180,6 @@ describe("Custom JSX v2 board router", () => {
);
expect(mocks.executeRequest).toHaveBeenCalledWith(
expect.objectContaining({ method: "POST", body: '{"enabled":true}' }),
expect.objectContaining({ acquireRequestLimit: expect.any(Function) }),
);
});
+60 -118
View File
@@ -12,7 +12,6 @@ import {
validateCustomWidgetOptions,
} from "@homarr/custom-widgets/core";
import type { CustomJsxRequest, CustomWidgetSource } from "@homarr/custom-widgets/core";
import { CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT } from "@homarr/custom-widgets/server";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
import { throwIfActionForbiddenAsync } from "../board/board-access";
@@ -33,10 +32,6 @@ const namedRequestInputSchema = itemInputSchema.extend({
requestId: z.string().min(1).max(64),
params: runtimeParamsSchema.default({}),
});
const refreshQueriesInputSchema = itemInputSchema.extend({
requestIds: z.array(z.string().min(1).max(64)).max(64).default([]),
all: z.boolean().default(false),
});
interface CustomWidgetItemOptions {
definitionId: string;
@@ -45,7 +40,7 @@ interface CustomWidgetItemOptions {
refreshInterval?: number;
}
type RouterContext = Parameters<typeof throwIfActionForbiddenAsync>[0] & { clientAddress?: string };
type RouterContext = Parameters<typeof throwIfActionForbiddenAsync>[0];
type ResolvedDefinition = Awaited<ReturnType<typeof resolvePlacedDefinitionAsync>>;
const parseItemOptions = (raw: string): CustomWidgetItemOptions => {
@@ -147,35 +142,28 @@ const getAuth = (resolved: ResolvedDefinition, source: IdentifiedSource, mode: "
};
};
const acquireRequestLimit = (ctx: RouterContext, resolved: ResolvedDefinition, request: IdentifiedRequest) =>
acquireCustomWidgetRequestLimit({
const withRequestLimit = async <T>(
ctx: RouterContext,
resolved: ResolvedDefinition,
request: IdentifiedRequest,
callback: () => Promise<T>,
) => {
const release = await acquireCustomWidgetRequestLimit({
category: request.kind === "query" ? "query" : request.method === "DELETE" ? "delete" : "action",
userId: ctx.session?.user.id,
anonymousId: ctx.clientAddress,
itemId: resolved.item.id,
definitionId: resolved.stored.id,
});
try {
return await callback();
} finally {
await release();
}
};
const getCacheKey = (resolved: ResolvedDefinition, request: IdentifiedRequest, params: Record<string, unknown>) =>
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${request.id}:${hashRuntimeParams(params)}`;
async function mapLoadRequests<T, TResult>(
requests: readonly T[],
execute: (request: T) => Promise<TResult>,
): Promise<TResult[]> {
const results: TResult[] = [];
for (let index = 0; index < requests.length; index += CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT) {
results.push(
...(await Promise.all(
requests
.slice(index, index + CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT)
.map(async (request) => await execute(request)),
)),
);
}
return results;
}
const executeRequest = async (
ctx: RouterContext,
resolved: ResolvedDefinition,
@@ -186,28 +174,20 @@ const executeRequest = async (
const source = findSource(resolved, request.source);
const values = resolveCustomWidgetRequestValues(request, resolved.configuration, params);
const targetUrl = renderRequestTarget(source.baseUrl, request, values);
try {
return await executeCustomWidgetRequest(
{
baseUrl: source.baseUrl,
targetUrl,
method: request.method,
body: renderRequestBody(request, values),
staticHeaders: request.headers,
auth: getAuth(resolved, source, request.auth),
networkScope: source.networkScope,
kind: request.kind,
cacheKey: request.kind === "query" ? getCacheKey(resolved, request, values) : undefined,
cacheTtlSeconds: request.cacheSeconds,
},
{
acquireRequestLimit: () => acquireRequestLimit(ctx, resolved, request),
},
);
} catch (error) {
if (error instanceof TRPCError) throw error;
throw new TRPCError({ code: "BAD_GATEWAY", message: "External request failed" });
}
return withRequestLimit(ctx, resolved, request, () =>
executeCustomWidgetRequest({
baseUrl: source.baseUrl,
targetUrl,
method: request.method,
body: renderRequestBody(request, values),
staticHeaders: request.headers,
auth: getAuth(resolved, source, request.auth),
networkScope: source.networkScope,
kind: request.kind,
cacheKey: request.kind === "query" ? getCacheKey(resolved, request, values) : undefined,
cacheTtlSeconds: request.cacheSeconds,
}),
);
};
export const customApiRouter = createTRPCRouter({
@@ -216,37 +196,39 @@ export const customApiRouter = createTRPCRouter({
const loadRequests = Object.entries(resolved.definition.requests).filter(
([, request]) => request.kind === "query" && request.trigger === "load",
);
const entries = await mapLoadRequests(loadRequests, 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 Promise.all(
loadRequests.map(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 {
return [
requestId,
{
data: null,
status: {
loading: false,
ok: false,
status: 0,
error: "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,
@@ -282,46 +264,6 @@ export const customApiRouter = createTRPCRouter({
};
}),
refreshQueries: protectedProcedure.input(refreshQueriesInputSchema).mutation(async ({ ctx, input }) => {
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
const available = Object.entries(resolved.definition.requests).flatMap(([requestId, request]) =>
request.kind === "query" ? [{ id: requestId, ...request }] : [],
);
const requested = new Set(input.all ? available.map(({ id }) => id) : input.requestIds);
const authorized: IdentifiedRequest[] = [];
for (const request of available) {
if (!requested.has(request.id)) continue;
try {
await throwIfActionForbiddenAsync(
ctx,
eq(boards.id, resolved.item.boardId),
request.permission as BoardPermission,
);
authorized.push(request);
} catch (error) {
if (!(error instanceof TRPCError) || error.code !== "NOT_FOUND") throw error;
}
}
if (authorized.length === 0) return { requestIds: [] };
const release = await acquireCustomWidgetRequestLimit({
category: "query",
userId: ctx.session?.user.id,
anonymousId: ctx.clientAddress,
itemId: resolved.item.id,
definitionId: resolved.stored.id,
});
try {
const version = getCustomWidgetCacheVersion(resolved.stored);
await invalidateCustomWidgetResponseCache(
authorized.map((request) => `custom-jsx:${resolved.item.id}:${version}:${request.id}:`),
);
} finally {
await release();
}
return { requestIds: authorized.map(({ id }) => id) };
}),
executeAction: protectedProcedure
.input(namedRequestInputSchema.extend({ confirmed: z.boolean().optional() }))
.mutation(async ({ ctx, input }) => {
@@ -333,7 +275,7 @@ export const customApiRouter = createTRPCRouter({
}
const response = await executeRequest(ctx, resolved, request, input.params);
if (response.ok && request.invalidates?.length) {
await invalidateCustomWidgetResponseCache(
invalidateCustomWidgetResponseCache(
request.invalidates.flatMap((requestId) => [
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
`custom-widget:options:${resolved.stored.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
+1 -3
View File
@@ -14,7 +14,7 @@ import { ZodError } from "zod/v4";
import type { Session } from "@homarr/auth";
import { extractBaseUrlFromHeaders, FlattenError } from "@homarr/common";
import { rateLimitAddressFromHeaders, userAgent } from "@homarr/common/server";
import { userAgent } from "@homarr/common/server";
import type { DeviceType } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { db } from "@homarr/db";
@@ -41,7 +41,6 @@ interface ApiContext {
session: Session | null;
deviceType: DeviceType;
baseUrl?: `${string}://${string}`;
clientAddress?: string;
db: typeof db;
}
@@ -59,7 +58,6 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
session,
deviceType: userAgent(opts.headers).device.type,
baseUrl: extractBaseUrlFromHeaders(opts.headers),
clientAddress: rateLimitAddressFromHeaders(opts.headers) ?? undefined,
db,
};
};