harden v2 custom widgets and workshop

This commit is contained in:
ajnart committed 2026-07-28 14:12:14 +02:00
1 parent e8a2c87c2d
commit 723b46926a
194 files changed
+44862 -1265

No files matched your search

+44 -17
View File
@@ -1,5 +1,10 @@
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
import { customJsxAuthoringCatalog } from "./component-catalog";
import {
getCustomWidgetCredentialKeyRisk,
isHarmlessCustomWidgetCredentialSetting,
redactCustomWidgetCredentialLiterals,
} from "./definition-security";
import { customJsxExamples } from "./examples";
export const CUSTOM_WIDGET_MANTINE_VERSION = customJsxAuthoringCatalog.mantineVersion;
@@ -93,7 +98,7 @@ ${leanShape}
Sources are keyed by name and must include "default". Auth is "none", "bearer", "basic", {"type":"apiKeyHeader","name":"X-Api-Key"}, or {"type":"apiKeyQuery","name":"api_key"}. Use the stable public API URL for public services and a clear suggested URL for self-hosted services; Homarr asks the installer for their own server URL. Never put credentials in the manifest.
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. DELETE requires full permission and receives confirmation automatically. Use {option:name} or {"$option":"name"} for saved options. Use {param:name} or {"$param":"name"} only for invocation-time params supplied by SubFetch, ActionButton, or ToggleSwitch. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Paths and query values must be primitive; JSON bodies may bind structured options.
Requests are keyed by ID. Defaults are source "default", kind "query", method "GET", query trigger "load", inherited auth, and permission "view" for queries or "modify" for actions. Actions are always manual. DELETE is valid only for actions, requires full permission, and receives confirmation automatically. Use {option:name} or {"$option":"name"} for saved options. Use {param:name} or {"$param":"name"} only for invocation-time params supplied by SubFetch, ActionButton, or ToggleSwitch. Load queries cannot use params. Values and primitive types are inferred from references; do not declare parameters or option bindings. Paths and query values must be primitive; JSON bodies may bind structured options.
Options are keyed by name. Every option has label, control, and default. Controls: text, textarea, number, switch, select, multiSelect, slider, date, time, color, icon, url, duration, timeZone, json. Select choices use \`"choices": [{"label":"...","value":"..."}]\`. Dynamic choices must use \`"choicesFrom": {"request":"requestId","itemsPath":"optional.path","valuePath":"id","labelPath":"name"}\`, never an object under \`choices\`. Options are configured outside the widget and read through \`options.name\`; a bound control writes only to \`inputs.name\` and never changes an option.
@@ -165,25 +170,42 @@ export function buildCustomWidgetAiPrompt(
return `${truncatePromptText(sections.join("\n\n"), CUSTOM_WIDGET_AI_PROMPT_LIMIT - footer.length)}${footer}`;
}
const sensitiveKey =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
function redactValue(value: unknown, key = ""): unknown {
if (sensitiveKey.test(key)) return "[REDACTED]";
if (Array.isArray(value)) return value.map((entry) => redactValue(entry));
function redactValue(value: unknown, path: Array<string | number> = []): unknown {
if (Array.isArray(value)) return value.map((entry, index) => redactValue(entry, [...path, index]));
if (value !== null && typeof value === "object")
return Object.fromEntries(
Object.entries(value).map(([entryKey, entry]) => [entryKey, redactValue(entry, entryKey)]),
Object.entries(value).map(([entryKey, entry]) => {
const entryPath = [...path, entryKey];
const risk = getCustomWidgetCredentialKeyRisk(entryKey);
if (
risk === "strong" &&
!isSchemaAuthenticationControl(entryPath) &&
!isHarmlessCustomWidgetCredentialSetting(entry)
) {
return [entryKey, "[REDACTED]"];
}
if (
risk === "ambiguous" &&
typeof entry === "string" &&
redactCustomWidgetCredentialLiterals(entry) !== entry
) {
return [entryKey, "[REDACTED]"];
}
return [entryKey, redactValue(entry, entryPath)];
}),
);
if (typeof value === "string") {
const key = typeof path.at(-1) === "string" ? (path.at(-1) as string) : "";
if (["sources", "requests", "options"].includes(key)) {
try {
return redactValue(JSON.parse(value) as unknown);
return redactValue(JSON.parse(value) as unknown, path);
} catch {
/* Keep invalid editor JSON useful. */
}
}
return key === "baseUrl" || key === "iconUrl" ? redactUrl(value) : redactText(value);
return key === "baseUrl" || key === "iconUrl"
? redactCustomWidgetCredentialLiterals(redactUrl(value))
: redactText(value);
}
return value;
}
@@ -210,13 +232,18 @@ function redactUrl(value: string): string {
}
function redactText(value: string): string {
return value
.replace(/\bhttps?:\/\/[^\s"'<>]+/giu, (candidate) => redactUrl(candidate))
.replace(/\b(authorization\s*:\s*bearer)\s+[^\s,;]+/giu, "$1 [REDACTED]")
.replace(
/\b(api[ _-]?key|access[ _-]?token|refresh[ _-]?token|client[ _-]?secret|token|password|passwd|secret)["']?\s*[:=]\s*["']?[^\s,;"'}]+/giu,
"$1: [REDACTED]",
);
return redactCustomWidgetCredentialLiterals(
value.replace(/\bhttps?:\/\/[^\s"'<>]+/giu, (candidate) => redactUrl(candidate)),
);
}
function isSchemaAuthenticationControl(path: Array<string | number>): boolean {
return (
path.length === 3 &&
path[2] === "auth" &&
(path[0] === "sources" || path[0] === "requests") &&
typeof path[1] === "string"
);
}
function formatBudgetedCodeSection(label: string, content: string, budget: number): string | null {
@@ -12,6 +12,7 @@ import {
} from "./request-schema";
import type { CustomJsxRequest } from "./request-schema";
import { customWidgetSecretKinds } from "./schema-types";
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
export * from "./options-schema";
export * from "./request-schema";
@@ -67,12 +68,12 @@ export const customWidgetDefinitionSchema = z
description: z.string().max(512).optional(),
iconUrl: z
.string()
.refine(
(value) => getCustomWidgetHttpUrlIssue(value) === null,
"Widget icons must use an unambiguous HTTP or HTTPS URL without embedded credentials",
)
.url()
.refine((value) => {
if (!URL.canParse(value)) return false;
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
}, "Widget icons must use HTTP or HTTPS without embedded credentials")
.max(2048)
.optional(),
sources: customWidgetSourcesSchema,
requests: customWidgetRequestsSchema,
@@ -1,38 +1,210 @@
import type { z } from "zod/v4";
const credentialKey =
/(^|[-_])(authorization|api[-_]?keys?|passwords?|passwds?|secrets?|tokens?|access[-_]?tokens?|refresh[-_]?tokens?|client[-_]?secrets?)($|[-_])/iu;
type DefinitionPath = Array<string | number>;
const harmlessCredentialSettings = new Set([
"anonymous",
"authentication",
"basic",
"bearer",
"configured",
"default",
"disabled",
"enabled",
"example",
"false",
"inherit",
"missing",
"none",
"optional",
"placeholder",
"public",
"redacted",
"required",
"separate",
"separately",
"source",
"true",
"unset",
]);
const commonCredentialLiteralPattern =
/\b(?:sk|pk|rk)-(?:[A-Za-z0-9][A-Za-z0-9._-]{7,})\b|\b(?:sk_(?:live|test)|github_pat|glpat|gh[pousr]|hf_|xox[baprs])-?[A-Za-z0-9._-]{8,}\b|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[0-9A-Za-z_-]{20,}\b|\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/giu;
const authorizationSchemePattern = /\b(bearer|basic)([\s:_-]+)(["']?)([A-Za-z0-9._~+/%=-]{8,})/giu;
const credentialAssignmentPattern =
/\b(authorization|auth(?:entication)?(?:[ _-]?(?:tokens?|keys?|credentials?))?|credentials?|api[ _-]?keys?|passwords?|passwds?|secrets?|tokens?|access[ _-]?(?:tokens?|keys?)|refresh[ _-]?tokens?|client[ _-]?secrets?|private[ _-]?keys?|signing[ _-]?keys?)((?:["']?\s*[:=]\s*["']?))([^\s,;"'}<>]+)/giu;
export function validateCredentialFreeExport(definition: Record<string, unknown>, ctx: z.RefinementCtx) {
inspect(definition.options, ["options"], ctx);
inspect(definition.requests, ["requests"], ctx);
if (typeof definition.iconUrl === "string" && URL.canParse(definition.iconUrl)) {
const url = new URL(definition.iconUrl);
if ([...url.searchParams.keys()].some((key) => credentialKey.test(key))) {
ctx.addIssue({ code: "custom", path: ["iconUrl"], message: "Credentials must not be embedded in the icon URL" });
const { secrets: _secrets, ...exportedDefinition } = definition;
inspect(exportedDefinition, [], ctx);
inspectRequestPathQueries(definition.requests, ctx);
inspectUrlQuery(definition.iconUrl, ["iconUrl"], "Widget icon URLs", ctx);
}
function inspect(value: unknown, path: DefinitionPath, ctx: z.RefinementCtx): void {
if (Array.isArray(value)) return value.forEach((entry, index) => inspect(entry, [...path, index], ctx));
if (typeof value === "string") {
if (containsCustomWidgetCredentialLiteral(value)) {
ctx.addIssue({ code: "custom", path, message: "Credentials must use source authentication" });
}
return;
}
if (
typeof definition.template === "string" &&
/(?:authorization\s*:\s*bearer|api[-_ ]?key\s*[:=]|password\s*[:=]|secret\s*[:=]|token\s*[:=])\s*["']?[A-Za-z0-9._~+/%=-]{8,}/iu.test(
definition.template,
)
) {
ctx.addIssue({ code: "custom", path: ["template"], message: "Credentials must not be embedded in JSX" });
if (!value || typeof value !== "object") return;
for (const [key, child] of Object.entries(value)) {
const childPath = [...path, key];
const keyRisk = getCustomWidgetCredentialKeyRisk(key);
if (
keyRisk === "strong" &&
!isSchemaAuthenticationControl(childPath) &&
hasCredentialFieldValue(child) &&
!isHarmlessCustomWidgetCredentialSetting(child)
) {
ctx.addIssue({ code: "custom", path: childPath, message: "Credentials must use source authentication" });
continue;
}
if (keyRisk === "ambiguous" && typeof child === "string" && containsCustomWidgetCredentialLiteral(child)) {
ctx.addIssue({ code: "custom", path: childPath, message: "Credentials must use source authentication" });
continue;
}
inspect(child, childPath, ctx);
}
}
function inspect(value: unknown, path: Array<string | number>, ctx: z.RefinementCtx): void {
if (Array.isArray(value)) return value.forEach((entry, index) => inspect(entry, [...path, index], ctx));
if (!value || typeof value !== "object") return;
for (const [key, child] of Object.entries(value)) {
if (credentialKey.test(key) && typeof child === "string" && child.trim()) {
ctx.addIssue({ code: "custom", path: [...path, key], message: "Credentials must use source authentication" });
function inspectRequestPathQueries(value: unknown, ctx: z.RefinementCtx): void {
if (!value || typeof value !== "object" || Array.isArray(value)) return;
for (const [requestId, candidate] of Object.entries(value)) {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
const path = (candidate as Record<string, unknown>).path;
if (typeof path !== "string") continue;
const queryStart = path.indexOf("?");
if (queryStart < 0) continue;
const query = path.slice(queryStart + 1);
for (const [key, queryValue] of parseQueryEntries(query)) {
const keyRisk = getCustomWidgetCredentialKeyRisk(key);
if (
(keyRisk === "strong" && queryValue.length > 0 && !isHarmlessCustomWidgetCredentialSetting(queryValue)) ||
containsCustomWidgetCredentialLiteral(queryValue)
) {
ctx.addIssue({
code: "custom",
path: ["requests", requestId, "path"],
message: "Request query credentials must use source authentication",
});
break;
}
}
inspect(child, [...path, key], ctx);
}
}
function inspectUrlQuery(value: unknown, path: DefinitionPath, label: string, ctx: z.RefinementCtx): void {
if (typeof value !== "string" || !URL.canParse(value)) return;
const url = new URL(value);
if (
parseQueryEntries(url.search).some(
([key, queryValue]) =>
(getCustomWidgetCredentialKeyRisk(key) === "strong" && queryValue.length > 0) ||
containsCustomWidgetCredentialLiteral(queryValue),
)
) {
ctx.addIssue({ code: "custom", path, message: `${label} cannot contain credentials` });
}
}
function parseQueryEntries(search: string): Array<[string, string]> {
const query = search.startsWith("?") ? search.slice(1) : search;
if (!query) return [];
return query.split("&").map((entry) => {
const separatorIndex = entry.indexOf("=");
const key = separatorIndex < 0 ? entry : entry.slice(0, separatorIndex);
const value = separatorIndex < 0 ? "" : entry.slice(separatorIndex + 1);
return [decodeQueryPart(key), decodeQueryPart(value)];
});
}
function decodeQueryPart(value: string): string {
try {
return decodeURIComponent(value.replaceAll("+", " "));
} catch {
return value;
}
}
export function getCustomWidgetCredentialKeyRisk(key: string): "strong" | "ambiguous" | null {
const normalized = key
.replace(/([a-z0-9])([A-Z])/gu, "$1 $2")
.replace(/[^A-Za-z0-9]+/gu, " ")
.trim()
.toLowerCase();
if (!normalized) return null;
const phrases = [
"authorization",
"authentication",
"auth",
"credential",
"credentials",
"api key",
"api keys",
"password",
"passwords",
"passwd",
"passwds",
"secret",
"secrets",
"token",
"tokens",
"access token",
"access tokens",
"access key",
"access keys",
"refresh token",
"refresh tokens",
"client secret",
"client secrets",
"private key",
"private keys",
"signing key",
"signing keys",
];
if (phrases.some((phrase) => normalized === phrase || normalized.endsWith(` ${phrase}`))) return "strong";
return normalized === "key" || normalized.endsWith(" key") || normalized === "keys" || normalized.endsWith(" keys")
? "ambiguous"
: null;
}
export function isHarmlessCustomWidgetCredentialSetting(value: unknown): boolean {
if (value === null || value === undefined || value === "" || typeof value === "boolean") return true;
return typeof value === "string" && harmlessCredentialSettings.has(value.trim().toLowerCase());
}
export function containsCustomWidgetCredentialLiteral(value: string): boolean {
return redactCustomWidgetCredentialLiterals(value) !== value;
}
export function redactCustomWidgetCredentialLiterals(value: string): string {
return value
.replace(commonCredentialLiteralPattern, "[REDACTED]")
.replace(authorizationSchemePattern, (match, scheme: string, separator: string, quote: string, candidate: string) =>
isHarmlessCustomWidgetCredentialSetting(candidate) ? match : `${scheme}${separator}${quote}[REDACTED]`,
)
.replace(credentialAssignmentPattern, (match, key: string, separator: string, candidate: string) =>
isHarmlessCustomWidgetCredentialSetting(candidate) ? match : `${key}${separator}[REDACTED]`,
);
}
function isSchemaAuthenticationControl(path: DefinitionPath): boolean {
return (
path.length === 3 &&
path[2] === "auth" &&
(path[0] === "sources" || path[0] === "requests") &&
typeof path[1] === "string"
);
}
function hasCredentialFieldValue(value: unknown): boolean {
if (value === null || value === undefined || value === "") return false;
return true;
}
export function validatePrototypeKeys(value: unknown, ctx: z.RefinementCtx) {
walk(value, [], ctx);
}
@@ -1,6 +1,7 @@
import { z } from "zod/v4";
import { customWidgetMethods } from "./schema-types";
import { getCustomWidgetHttpUrlIssue } from "./url-policy";
export const customJsxNetworkScopes = ["public", "private", "loopback"] as const;
export type CustomJsxNetworkScope = (typeof customJsxNetworkScopes)[number];
@@ -26,10 +27,9 @@ const authSchema = z.union([
export type CustomWidgetSourceUrlIssue = "invalid" | "protocol" | "credentials" | "queryOrFragment";
export function getCustomWidgetSourceUrlIssue(value: string): CustomWidgetSourceUrlIssue | null {
if (!URL.canParse(value)) return "invalid";
const issue = getCustomWidgetHttpUrlIssue(value);
if (issue) return issue;
const url = new URL(value);
if (url.protocol !== "http:" && url.protocol !== "https:") return "protocol";
if (url.username || url.password) return "credentials";
if (url.search || url.hash) return "queryOrFragment";
return null;
}
@@ -45,12 +45,12 @@ export const customWidgetSourceSchema = z.strictObject({
name: z.string().trim().min(1).max(128).optional(),
baseUrl: z
.string()
.url()
.max(2048)
.superRefine((value, ctx) => {
const issue = getCustomWidgetSourceUrlIssue(value);
if (issue && issue !== "invalid") ctx.addIssue({ code: "custom", message: sourceUrlIssueMessages[issue] });
}),
if (issue) ctx.addIssue({ code: "custom", message: sourceUrlIssueMessages[issue] });
})
.url()
.max(2048),
networkScope: z.enum(customJsxNetworkScopes),
auth: authSchema.default("none"),
});
@@ -157,6 +157,15 @@ export const customJsxRequestSchema = z
confirmation: confirmationSchema.optional(),
invalidates: z.array(customWidgetIdentifierSchema).max(32).optional(),
})
.superRefine((request, context) => {
if (request.method === "DELETE" && request.kind !== "action") {
context.addIssue({
code: "custom",
path: ["kind"],
message: "DELETE requests must be manual actions",
});
}
})
.transform((request) => {
const confirmation =
request.method === "DELETE" && request.confirmation === undefined
@@ -0,0 +1,108 @@
export type CustomWidgetHttpUrlIssue = "invalid" | "protocol" | "credentials";
const forbiddenUnicodeCodePointRanges = [
[0x0000, 0x0020],
[0x007f, 0x00a0],
[0x1680, 0x1680],
[0x2000, 0x200f],
[0x2028, 0x202f],
[0x205f, 0x206f],
[0x3000, 0x3000],
[0xfeff, 0xfeff],
] as const;
/**
* Applies the conservative URL syntax shared by Homarr and the Workshop
* validator. WHATWG URL parsing intentionally accepts and normalizes several
* ambiguous spellings (for example IPv4 integers, backslashes and escaped
* hostnames). Definitions are persisted and later used for network requests,
* so authoring accepts only an unambiguous authority spelling.
*/
export function getCustomWidgetHttpUrlIssue(value: string): CustomWidgetHttpUrlIssue | null {
if (hasForbiddenUrlCharacter(value) || value.includes("\\")) return "invalid";
if (!URL.canParse(value)) return "invalid";
let url: URL;
try {
url = new URL(value);
} catch {
return "invalid";
}
if (url.protocol !== "http:" && url.protocol !== "https:") return "protocol";
const authority = getRawAuthority(value);
if (authority === null) return "invalid";
if (authority.includes("@") || url.username || url.password) return "credentials";
if (authority.includes("%") || /[。.。]/u.test(authority)) return "invalid";
const hostAndPort = splitHostAndPort(authority);
if (!hostAndPort || !hasCanonicalPort(hostAndPort.port)) return "invalid";
const rawHostname = withoutTrailingRootDot(hostAndPort.hostname);
const parsedHostname = withoutTrailingRootDot(url.hostname);
if (!rawHostname || !hasCanonicalParsedHostname(parsedHostname)) return "invalid";
if (looksNumeric(rawHostname) && !isStrictIpv4(rawHostname)) return "invalid";
if (isStrictIpv4(parsedHostname) && rawHostname !== parsedHostname) return "invalid";
return null;
}
function getRawAuthority(value: string): string | null {
const match = value.match(/^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/u);
return match?.[1] ?? null;
}
function splitHostAndPort(authority: string): { hostname: string; port: string } | null {
if (authority.startsWith("[")) {
const closingBracket = authority.indexOf("]");
if (closingBracket < 0) return null;
const hostname = authority.slice(0, closingBracket + 1);
const suffix = authority.slice(closingBracket + 1);
if (suffix && !suffix.startsWith(":")) return null;
return { hostname, port: suffix ? suffix.slice(1) : "" };
}
const firstColon = authority.indexOf(":");
if (firstColon !== authority.lastIndexOf(":")) return null;
return {
hostname: firstColon < 0 ? authority : authority.slice(0, firstColon),
port: firstColon < 0 ? "" : authority.slice(firstColon + 1),
};
}
function hasCanonicalPort(value: string): boolean {
if (!value) return true;
if (!/^(?:0|[1-9]\d{0,4})$/u.test(value)) return false;
return Number(value) <= 65_535;
}
function hasCanonicalParsedHostname(value: string): boolean {
if (value.startsWith("[") && value.endsWith("]")) return true;
if (!value || value.length > 253 || !/^[A-Za-z0-9._-]+$/u.test(value)) return false;
return value
.split(".")
.every((label) => Boolean(label) && label.length <= 63 && !label.startsWith("-") && !label.endsWith("-"));
}
function looksNumeric(value: string): boolean {
const parts = value.split(".");
return parts.every((part) => /^(?:\d+|0[xX][0-9A-Fa-f]+)$/u.test(part));
}
function isStrictIpv4(value: string): boolean {
const parts = value.split(".");
return parts.length === 4 && parts.every((part) => /^(?:0|[1-9]\d{0,2})$/u.test(part) && Number(part) <= 255);
}
function withoutTrailingRootDot(value: string): string {
return value.endsWith(".") ? value.slice(0, -1) : value;
}
function hasForbiddenUrlCharacter(value: string): boolean {
return [...value].some((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return forbiddenUnicodeCodePointRanges.some(([minimum, maximum]) => codePoint >= minimum && codePoint <= maximum);
});
}
@@ -24,6 +24,7 @@ export function RefreshButton({ label, color = "gray", variant = "subtle", size
itemId: runtime.itemId,
previewSessionId: runtime.previewSessionId,
targets: ["parent", "*"],
refresh: true,
});
} finally {
setLoading(false);
@@ -37,7 +38,7 @@ export function RefreshButton({ label, color = "gray", variant = "subtle", size
size={size as never}
onClick={() => void refresh()}
loading={loading}
disabled={(!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
disabled={(!runtime.itemId && !runtime.previewSessionId) || !runtime.canInvalidateQueries || runtime.isEditMode}
>
<IconRefresh size={16} />
</ActionIcon>
@@ -43,6 +43,7 @@ export interface RuntimeInvalidationInput {
itemId?: string;
previewSessionId?: string;
targets: readonly string[];
refresh?: boolean;
}
export interface RuntimeNotification {
@@ -82,6 +83,7 @@ export interface CustomWidgetRuntimeValue {
previewSessionId?: string;
previewLiveActions?: boolean;
queriesDisabled?: boolean;
canInvalidateQueries: boolean;
isEditMode: boolean;
requestCapabilities: readonly CustomJsxRequestCapability[];
port: CustomWidgetRuntimePort;
+4 -2
View File
@@ -10,17 +10,19 @@ export type CustomWidgetDomainErrorCode =
export class CustomWidgetDomainError extends Error {
public readonly code: CustomWidgetDomainErrorCode;
public readonly reason?: "timeout";
public readonly retryAfterMs?: number;
public constructor(input: {
code: CustomWidgetDomainErrorCode;
message: string;
cause?: unknown;
reason?: "timeout";
retryAfterMs?: number;
}) {
super(input.message, { cause: input.cause });
super(input.message);
this.name = "CustomWidgetDomainError";
this.code = input.code;
this.reason = input.reason;
this.retryAfterMs = input.retryAfterMs;
}
}
+6 -2
View File
@@ -5,7 +5,6 @@ export {
assertSafeStaticHeaders,
classifyAddress,
executeCustomWidgetRequest,
invalidateCustomWidgetResponseCache,
MAX_REQUEST_DURATION_MS,
MAX_REQUEST_BODY_BYTES,
MAX_RESPONSE_BODY_BYTES,
@@ -16,7 +15,12 @@ export {
validateCustomWidgetUrl,
} from "./request-executor";
export type { CustomWidgetAuthConfig, CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "./request-executor";
export { CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS, CustomWidgetRequestLimiter } from "./request-limits";
export {
CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT,
CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS,
CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT,
CustomWidgetRequestLimiter,
} from "./request-limits";
export type { RequestLimitInput, RequestLimiterOptions, RequestLimitStore } from "./request-limits";
export { CustomWidgetPreviewSessionService } from "./preview-sessions";
export type {
@@ -66,6 +66,11 @@ loopbackAddresses.addAddress("::1", "ipv6");
type AddressFamily = 4 | 6;
export type ResolvedAddress = { address: string; family: AddressFamily };
export type HostResolver = (hostname: string) => Promise<ResolvedAddress[]>;
export interface ResolveHostOptions {
signal?: AbortSignal;
resolver?: HostResolver;
}
type AddressClass = "public" | "private" | "loopback" | "blocked";
const normalizeHostname = (value: string) =>
value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
@@ -83,12 +88,19 @@ export function classifyAddress(address: string): AddressClass {
export async function resolveAndValidateHost(
hostname: string,
scope: CustomJsxNetworkScope,
options: ResolveHostOptions = {},
): Promise<ResolvedAddress[]> {
const normalized = normalizeHostname(hostname);
const family = isIP(normalized) as AddressFamily | 0;
throwIfAborted(options.signal);
const addresses = family
? [{ address: normalized, family }]
: ((await lookup(normalized, { all: true, verbatim: true })) as ResolvedAddress[]);
: await abortable(
options.resolver?.(normalized) ??
(lookup(normalized, { all: true, verbatim: true }) as Promise<ResolvedAddress[]>),
options.signal,
);
throwIfAborted(options.signal);
if (!addresses.length)
throw new CustomWidgetDomainError({ code: "BAD_REQUEST", message: "Target host did not resolve" });
for (const address of addresses) {
@@ -106,6 +118,39 @@ export async function resolveAndValidateHost(
return addresses;
}
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw signal.reason ?? createAbortError();
}
function abortable<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
if (!signal) return operation;
if (signal.aborted) return Promise.reject(signal.reason ?? createAbortError());
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
signal.removeEventListener("abort", onAbort);
reject(signal.reason ?? createAbortError());
};
signal.addEventListener("abort", onAbort, { once: true });
operation.then(
(value) => {
signal.removeEventListener("abort", onAbort);
resolve(value);
},
(error: unknown) => {
signal.removeEventListener("abort", onAbort);
reject(error);
},
);
});
}
function createAbortError(): Error {
const error = new Error("Operation aborted");
error.name = "AbortError";
return error;
}
export function validateCustomWidgetUrl(value: string | URL): URL {
let url: URL;
try {
@@ -30,9 +30,11 @@ export {
export const MAX_REQUEST_BODY_BYTES = 10 * 1024;
const REQUEST_TIMEOUT_MS = 10_000;
const DISPATCHER_CLOSE_GRACE_MS = 1_000;
const MAX_QUERY_REDIRECTS = 3;
const MAX_RESPONSE_CACHE_ENTRIES = 1_000;
export const MAX_REQUEST_DURATION_MS = 45_000;
const TIMEOUT_ERROR_CODES = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]);
const RESPONSE_TOO_LARGE_ERROR_CODE = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
export interface CustomWidgetAuthConfig {
type: string;
@@ -51,7 +53,7 @@ export interface CustomWidgetHttpRequest {
kind: "query" | "action";
cacheKey?: string;
cacheTtlSeconds?: number;
logError?: (event: { origin: string; method: CustomWidgetMethod; errorName: string }) => void;
logError?: (event: { origin: string; method: CustomWidgetMethod; errorName: string; reason?: "timeout" }) => void;
}
export interface CustomWidgetHttpResponse {
@@ -60,9 +62,10 @@ export interface CustomWidgetHttpResponse {
statusText: string;
data: unknown;
}
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
let cacheEpoch = 0;
type RequestHopResult =
| { kind: "response"; response: CustomWidgetHttpResponse }
| { kind: "redirect"; location: string | null; statusCode: number };
async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
const controller = new AbortController();
@@ -74,11 +77,19 @@ async function performRequest(input: CustomWidgetHttpRequest): Promise<CustomWid
throw new CustomWidgetDomainError({
code: "BAD_GATEWAY",
message: "External request exceeded the total time limit",
cause: error,
reason: "timeout",
});
}
if (error instanceof CustomWidgetDomainError) throw error;
throw error;
input.logError?.({
origin: safeOrigin(input.baseUrl),
method: input.method,
errorName: "TransportError",
});
throw new CustomWidgetDomainError({
code: "BAD_GATEWAY",
message: "External request failed",
});
} finally {
clearTimeout(timeout);
}
@@ -96,15 +107,16 @@ async function performRequestWithinDeadline(
const maxRedirects = input.kind === "query" ? MAX_QUERY_REDIRECTS : 0;
for (let redirects = 0; ; redirects += 1) {
const dispatcher = createPinnedAgent(
await resolveAndValidateHost(currentUrl.hostname, input.networkScope),
await resolveAndValidateHost(currentUrl.hostname, input.networkScope, { signal: deadlineSignal }),
REQUEST_TIMEOUT_MS,
);
const headers = buildHeaders(input, currentUrl, currentBody);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let responseData: Awaited<ReturnType<typeof dispatcher.request>>;
let result: RequestHopResult | undefined;
let lifecycleFailure: { error: unknown } | undefined;
try {
responseData = await dispatcher.request({
const responseData = await dispatcher.request({
origin: currentUrl.origin,
path: `${currentUrl.pathname}${currentUrl.search}`,
method: currentMethod,
@@ -112,54 +124,88 @@ async function performRequestWithinDeadline(
body: currentBody,
signal: AbortSignal.any([deadlineSignal, controller.signal]),
});
} catch (error) {
await dispatcher.close();
if (error instanceof CustomWidgetDomainError) throw error;
input.logError?.({
origin: currentUrl.origin,
method: currentMethod,
errorName: error instanceof Error ? error.name : "UnknownError",
});
throw new CustomWidgetDomainError({
code: "BAD_GATEWAY",
message: error instanceof Error ? error.message : "External request failed",
cause: error,
});
} finally {
clearTimeout(timeout);
}
if (![301, 302, 303, 307, 308].includes(responseData.statusCode)) {
try {
if (![301, 302, 303, 307, 308].includes(responseData.statusCode)) {
const body = await responseData.body.arrayBuffer();
const response = new Response(body.byteLength > 0 ? body : null, {
status: responseData.statusCode,
statusText: STATUS_CODES[responseData.statusCode] ?? "",
headers: normalizeResponseHeaders(responseData.headers),
});
return {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: await parseResponseBody(response),
result = {
kind: "response",
response: {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: await parseResponseBody(response),
},
};
} finally {
await dispatcher.close();
} else {
await responseData.body.dump();
result = {
kind: "redirect",
location: normalizeResponseHeaders(responseData.headers).get("location"),
statusCode: responseData.statusCode,
};
}
} catch (error) {
lifecycleFailure = { error };
} finally {
clearTimeout(timeout);
try {
const closed = await closeDispatcher(dispatcher, deadlineSignal);
if (!closed)
input.logError?.({
origin: currentUrl.origin,
method: currentMethod,
errorName: "DispatcherCloseTimeout",
});
} catch {
input.logError?.({
origin: currentUrl.origin,
method: currentMethod,
errorName: "DispatcherCloseError",
});
}
}
try {
await responseData.body.dump();
} finally {
await dispatcher.close();
if (lifecycleFailure) {
const { error } = lifecycleFailure;
if (error instanceof CustomWidgetDomainError) throw error;
if (isResponseTooLargeError(error)) {
throw new CustomWidgetDomainError({
code: "PAYLOAD_TOO_LARGE",
message: "Response exceeds the 1 MiB limit",
});
}
const timedOut = isCustomWidgetRequestTimeoutError(error, deadlineSignal, controller.signal);
input.logError?.({
origin: currentUrl.origin,
method: currentMethod,
errorName: timedOut ? "RequestTimeout" : "TransportError",
...(timedOut ? { reason: "timeout" as const } : {}),
});
throw new CustomWidgetDomainError({
code: "BAD_GATEWAY",
message: timedOut ? "External request timed out" : "External request failed",
...(timedOut ? { reason: "timeout" as const } : {}),
});
}
if (!result)
throw new CustomWidgetDomainError({
code: "INTERNAL_SERVER_ERROR",
message: "External request did not complete",
});
if (result.kind === "response") return result.response;
if (redirects >= maxRedirects)
throw new CustomWidgetDomainError({ code: "BAD_GATEWAY", message: "Upstream redirect limit exceeded" });
const location = normalizeResponseHeaders(responseData.headers).get("location");
if (!location)
if (!result.location)
throw new CustomWidgetDomainError({ code: "BAD_GATEWAY", message: "Upstream redirect is missing a location" });
const redirected = validateCustomWidgetUrl(new URL(location, currentUrl));
const redirected = validateCustomWidgetUrl(new URL(result.location, currentUrl));
if (redirected.origin !== baseUrl.origin)
throw new CustomWidgetDomainError({ code: "FORBIDDEN", message: "Cross-origin redirects are not allowed" });
if (responseData.statusCode === 303 || ([301, 302].includes(responseData.statusCode) && currentMethod === "POST")) {
if (result.statusCode === 303 || ([301, 302].includes(result.statusCode) && currentMethod === "POST")) {
currentMethod = "GET";
currentBody = undefined;
}
@@ -167,6 +213,81 @@ async function performRequestWithinDeadline(
}
}
async function closeDispatcher(
dispatcher: ReturnType<typeof createPinnedAgent>,
deadlineSignal: AbortSignal,
): Promise<boolean> {
const cleanupController = new AbortController();
const timeout = setTimeout(() => cleanupController.abort(), DISPATCHER_CLOSE_GRACE_MS);
try {
await abortable(dispatcher.close(), AbortSignal.any([deadlineSignal, cleanupController.signal]));
return true;
} catch (error) {
detachDispatcherDestroy(dispatcher);
if (cleanupController.signal.aborted && !deadlineSignal.aborted) return false;
throw error;
} finally {
clearTimeout(timeout);
}
}
function detachDispatcherDestroy(dispatcher: ReturnType<typeof createPinnedAgent>): void {
try {
void dispatcher.destroy().catch(() => undefined);
} catch {
// Cleanup is best effort after its bounded grace period.
}
}
function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
if (signal.aborted) return Promise.reject(signal.reason ?? createAbortError());
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
signal.removeEventListener("abort", onAbort);
reject(signal.reason ?? createAbortError());
};
signal.addEventListener("abort", onAbort, { once: true });
operation.then(
(value) => {
signal.removeEventListener("abort", onAbort);
resolve(value);
},
(error: unknown) => {
signal.removeEventListener("abort", onAbort);
reject(error);
},
);
});
}
function createAbortError(): Error {
const error = new Error("Operation aborted");
error.name = "AbortError";
return error;
}
export function isCustomWidgetRequestTimeoutError(error: unknown, ...signals: readonly AbortSignal[]): boolean {
if (signals.some((signal) => signal.aborted)) return true;
if (!(error instanceof Error)) return false;
if (error.name.includes("Timeout")) return true;
const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
return code !== undefined && TIMEOUT_ERROR_CODES.has(code);
}
function isResponseTooLargeError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return "code" in error && error.code === RESPONSE_TOO_LARGE_ERROR_CODE;
}
function safeOrigin(value: string): string {
try {
return new URL(value).origin;
} catch {
return "invalid";
}
}
function normalizeResponseHeaders(values: Record<string, string | string[] | undefined>) {
const headers = new Headers();
for (const [name, value] of Object.entries(values)) {
@@ -195,42 +316,5 @@ function buildHeaders(input: CustomWidgetHttpRequest, url: URL, body: string | u
}
export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
const key = input.kind === "query" ? input.cacheKey : undefined;
if (!key) return performRequest(input);
const cached = cache.get(key);
if (cached && cached.expiresAt > Date.now()) return cached.response;
if (cached) cache.delete(key);
const pending = inFlight.get(key);
if (pending) return pending;
const requestEpoch = cacheEpoch;
let request: Promise<CustomWidgetHttpResponse>;
request = performRequest(input)
.then((response) => {
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
pruneCache();
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
}
return response;
})
.finally(() => {
if (inFlight.get(key) === request) inFlight.delete(key);
});
inFlight.set(key, request);
return request;
}
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): void {
if (prefixes.length === 0) return;
cacheEpoch += 1;
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) cache.delete(key);
for (const key of inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
}
function pruneCache(): void {
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) cache.delete(key);
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES) {
const key = cache.keys().next().value as string | undefined;
if (!key) return;
cache.delete(key);
}
return performRequest(input);
}
@@ -7,12 +7,16 @@ const WINDOW_MS = 60_000;
// Keep the lease above that total and identify every acquisition so a late
// release can never remove capacity owned by a newer request.
export const CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS = 60_000;
export const CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT = 4;
export const CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT = 8;
const CATEGORY_LIMITS = { query: 60, action: 10, delete: 3 } as const;
const DEFINITION_CATEGORY_LIMITS = { query: 240, action: 40, delete: 12 } as const;
type RequestCategory = keyof typeof CATEGORY_LIMITS;
export interface RequestLimitInput {
category: RequestCategory;
userId?: string;
anonymousId?: string;
itemId: string;
definitionId: string;
}
@@ -35,33 +39,45 @@ export class CustomWidgetRequestLimiter {
public constructor(private readonly options: RequestLimiterOptions = {}) {}
public async acquire(input: RequestLimitInput): Promise<() => Promise<void>> {
const identity = input.userId ?? "anonymous";
const identity = input.userId ? `user:${input.userId}` : `anonymous:${input.anonymousId ?? "unknown"}`;
const rateKey = `custom-widget:rate:${input.category}:${hashKey(identity, input.itemId)}`;
const definitionRateKey = `custom-widget:rate:v2:definition:${input.category}:${hashKey(input.definitionId)}`;
const userKey = `custom-widget:concurrency:v2:user-item:${hashKey(identity, input.itemId)}`;
const definitionKey = `custom-widget:concurrency:v2:definition:${hashKey(input.definitionId)}`;
if (!this.options.store) return this.acquireLocal(rateKey, userKey, definitionKey, input.category);
if (!this.options.store)
return this.acquireLocal(rateKey, definitionRateKey, userKey, definitionKey, input.category);
try {
return await this.acquireStored(rateKey, userKey, definitionKey, input.category, this.options.store);
return await this.acquireStored(
rateKey,
definitionRateKey,
userKey,
definitionKey,
input.category,
this.options.store,
);
} catch (error) {
if (error instanceof CustomWidgetDomainError) throw error;
this.options.onStoreError?.(error);
throw new CustomWidgetDomainError({
code: "INTERNAL_SERVER_ERROR",
message: "Request limiter is unavailable",
cause: error,
});
}
}
private acquireLocal(rateKey: string, userKey: string, definitionKey: string, category: RequestCategory) {
private acquireLocal(
rateKey: string,
definitionRateKey: string,
userKey: string,
definitionKey: string,
category: RequestCategory,
) {
const now = Date.now();
const recent = (this.rateBuckets.get(rateKey) ?? []).filter((timestamp) => now - timestamp < WINDOW_MS);
if (recent.length >= CATEGORY_LIMITS[category]) throwLimit(WINDOW_MS - (now - (recent[0] ?? now)));
recent.push(now);
this.rateBuckets.set(rateKey, recent);
this.acquireLocalConcurrency(userKey, 4);
this.acquireLocalRate(rateKey, CATEGORY_LIMITS[category], now);
this.acquireLocalRate(definitionRateKey, DEFINITION_CATEGORY_LIMITS[category], now);
this.acquireLocalConcurrency(userKey, CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT);
try {
this.acquireLocalConcurrency(definitionKey, 8);
this.acquireLocalConcurrency(definitionKey, CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT);
} catch (error) {
this.releaseLocalConcurrency(userKey);
throw error;
@@ -74,6 +90,7 @@ export class CustomWidgetRequestLimiter {
private async acquireStored(
rateKey: string,
definitionRateKey: string,
userKey: string,
definitionKey: string,
category: RequestCategory,
@@ -82,11 +99,27 @@ export class CustomWidgetRequestLimiter {
const ownerId = randomUUID();
const rate = await store.incrementRate(rateKey, WINDOW_MS);
if (rate.count > CATEGORY_LIMITS[category]) throwLimit(rate.retryAfterMs);
if (!(await store.acquireConcurrency(userKey, ownerId, 4, CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS))) {
const definitionRate = await store.incrementRate(definitionRateKey, WINDOW_MS);
if (definitionRate.count > DEFINITION_CATEGORY_LIMITS[category]) throwLimit(definitionRate.retryAfterMs);
if (
!(await store.acquireConcurrency(
userKey,
ownerId,
CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT,
CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS,
))
) {
throwLimit(1_000);
}
try {
if (!(await store.acquireConcurrency(definitionKey, ownerId, 8, CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS))) {
if (
!(await store.acquireConcurrency(
definitionKey,
ownerId,
CUSTOM_WIDGET_DEFINITION_CONCURRENCY_LIMIT,
CUSTOM_WIDGET_REQUEST_CONCURRENCY_TTL_MS,
))
) {
throwLimit(1_000);
}
} catch (error) {
@@ -98,6 +131,13 @@ export class CustomWidgetRequestLimiter {
};
}
private acquireLocalRate(key: string, limit: number, now: number): void {
const recent = (this.rateBuckets.get(key) ?? []).filter((timestamp) => now - timestamp < WINDOW_MS);
if (recent.length >= limit) throwLimit(WINDOW_MS - (now - (recent[0] ?? now)));
recent.push(now);
this.rateBuckets.set(key, recent);
}
private acquireLocalConcurrency(key: string, limit: number): void {
const count = this.concurrency.get(key) ?? 0;
if (count >= limit) throwLimit(1_000);
@@ -45,4 +45,26 @@ describe("AI prompt", () => {
expect(prompt.endsWith(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBe(true);
expect(prompt.length).toBeLessThanOrEqual(12_000);
});
it("redacts embedded request credentials while retaining harmless request metadata", () => {
const prompt = buildCustomWidgetAiPrompt(undefined, null, {
requests: {
status: {
path: "/status?credential=Bearer-sk-secret-123456",
headers: {
"X-Auth": "Bearer sk-secret-123456",
"X-Service": "Basic dXNlcjpwYXNz",
"X-Feature-Key": "dashboard-layout",
},
},
},
template: "<Text>Bearer ghp_abcdefghijklmnopqrstuvwxyz123456</Text>",
});
expect(prompt).not.toContain("sk-secret-123456");
expect(prompt).not.toContain("dXNlcjpwYXNz");
expect(prompt).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz123456");
expect(prompt).toContain('"X-Auth": "[REDACTED]"');
expect(prompt).toContain('"X-Feature-Key": "dashboard-layout"');
});
});
@@ -0,0 +1,186 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type * as NetworkPolicy from "../server/network-policy";
import type { CustomWidgetHttpRequest } from "../server/request-executor";
const mocks = vi.hoisted(() => ({
lookup: vi.fn(),
createPinnedAgent: vi.fn(),
}));
vi.mock("node:dns/promises", () => ({ lookup: mocks.lookup }));
vi.mock("../server/network-policy", async (importOriginal) => {
const actual = await importOriginal<typeof NetworkPolicy>();
return { ...actual, createPinnedAgent: mocks.createPinnedAgent };
});
import { executeCustomWidgetRequest, MAX_REQUEST_DURATION_MS } from "../server/request-executor";
import { resolveAndValidateHost } from "../server/network-policy";
const query = {
baseUrl: "https://example.com",
method: "GET",
networkScope: "public",
kind: "query",
} satisfies CustomWidgetHttpRequest;
describe("custom widget request deadline", () => {
beforeEach(() => {
vi.useFakeTimers();
mocks.lookup.mockReset();
mocks.createPinnedAgent.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("returns at the total deadline when DNS resolution stalls", async () => {
mocks.lookup.mockReturnValue(new Promise(() => undefined));
const assertion = expect(executeCustomWidgetRequest(query)).rejects.toMatchObject({
code: "BAD_GATEWAY",
reason: "timeout",
});
await vi.advanceTimersByTimeAsync(MAX_REQUEST_DURATION_MS);
await assertion;
expect(mocks.createPinnedAgent).not.toHaveBeenCalled();
});
it("cancels an injected stalled resolver when its deadline aborts", async () => {
const controller = new AbortController();
const resolver = vi.fn(() => new Promise<never>(() => undefined));
const assertion = expect(
resolveAndValidateHost("example.com", "public", { signal: controller.signal, resolver }),
).rejects.toMatchObject({ name: "AbortError" });
controller.abort();
await assertion;
expect(resolver).toHaveBeenCalledWith("example.com");
});
it("detaches stalled dispatcher cleanup after a bounded grace period", async () => {
const close = vi.fn(() => new Promise<void>(() => undefined));
const destroy = vi.fn(async () => undefined);
mocks.createPinnedAgent.mockReturnValue({
request: vi.fn(async () => ({
statusCode: 200,
headers: { "content-type": "application/json" },
body: {
arrayBuffer: vi.fn(async () => new TextEncoder().encode("{}").buffer),
},
})),
close,
destroy,
});
const logError = vi.fn();
const request = executeCustomWidgetRequest({
...query,
baseUrl: "http://127.0.0.1",
networkScope: "loopback",
logError,
});
await vi.advanceTimersByTimeAsync(1_000);
await expect(request).resolves.toMatchObject({ ok: true, status: 200, data: {} });
expect(close).toHaveBeenCalledOnce();
expect(destroy).toHaveBeenCalledOnce();
expect(logError).toHaveBeenCalledWith(
expect.objectContaining({
errorName: "DispatcherCloseTimeout",
}),
);
});
it("does not turn a completed action into a failure when dispatcher cleanup rejects", async () => {
const closeFailure = Object.assign(new Error("cleanup failed"), { name: "DispatcherCloseError" });
const close = vi.fn(async () => {
throw closeFailure;
});
const destroy = vi.fn(async () => undefined);
mocks.createPinnedAgent.mockReturnValue({
request: vi.fn(async () => ({
statusCode: 200,
headers: { "content-type": "application/json" },
body: {
arrayBuffer: vi.fn(async () => new TextEncoder().encode('{"updated":true}').buffer),
},
})),
close,
destroy,
});
const logError = vi.fn();
await expect(
executeCustomWidgetRequest({
...query,
baseUrl: "http://127.0.0.1",
method: "POST",
networkScope: "loopback",
kind: "action",
logError,
}),
).resolves.toMatchObject({ ok: true, status: 200, data: { updated: true } });
expect(close).toHaveBeenCalledOnce();
expect(destroy).toHaveBeenCalledOnce();
expect(logError).toHaveBeenCalledWith(
expect.objectContaining({
errorName: "DispatcherCloseError",
}),
);
});
it("redacts apiKeyQuery credentials from transport errors and structured log events", async () => {
const apiKey = "api-key-query-secret";
const request = vi.fn(async ({ path }: { path: string }) => {
const failure = new Error(`Transport failed for https://example.com${path}`);
failure.name = `SocketError:${path}`;
throw failure;
});
mocks.createPinnedAgent.mockReturnValue({
request,
close: vi.fn(async () => undefined),
destroy: vi.fn(async () => undefined),
});
const logError = vi.fn();
const error = await executeCustomWidgetRequest({
...query,
baseUrl: "http://127.0.0.1",
targetUrl: "http://127.0.0.1/status?view=summary",
networkScope: "loopback",
auth: {
type: "apiKeyQuery",
headerName: "access_token",
secrets: [{ kind: "apiKey", value: apiKey }],
},
logError,
}).then(
() => undefined,
(cause: unknown) => cause,
);
expect(request).toHaveBeenCalledWith(
expect.objectContaining({
path: expect.stringContaining(`access_token=${apiKey}`),
}),
);
expect(error).toMatchObject({
code: "BAD_GATEWAY",
message: "External request failed",
});
expect((error as Error).cause).toBeUndefined();
expect(String(error)).not.toContain(apiKey);
expect(String(error)).not.toContain("access_token");
expect(logError).toHaveBeenCalledWith({
origin: "http://127.0.0.1",
method: "GET",
errorName: "TransportError",
});
expect(JSON.stringify({ error, logCalls: logError.mock.calls })).not.toContain(apiKey);
expect(JSON.stringify({ error, logCalls: logError.mock.calls })).not.toContain("access_token");
});
});
@@ -23,6 +23,51 @@ describe("custom widget request limits", () => {
await Promise.all(releases.slice(1).map((release) => release()));
});
it("keeps anonymous client concurrency buckets independent", async () => {
const limiter = new CustomWidgetRequestLimiter();
const firstClient = { ...input, userId: undefined, anonymousId: "198.51.100.10" };
const secondClient = { ...input, userId: undefined, anonymousId: "198.51.100.11" };
const firstClientReleases = await Promise.all(Array.from({ length: 4 }, () => limiter.acquire(firstClient)));
await expect(limiter.acquire(firstClient)).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
const releaseSecondClient = await limiter.acquire(secondClient);
await releaseSecondClient();
await Promise.all(firstClientReleases.map((release) => release()));
});
it("enforces an identity-independent per-definition rate bucket", async () => {
const anonymousQuery = { ...input, category: "query" as const, userId: undefined };
let increment = 0;
const store: RequestLimitStore = {
incrementRate: vi.fn(async () => {
increment += 1;
return {
// Each acquisition increments its identity bucket first and its
// definition bucket second. Simulate a fresh forged identity while
// the shared definition bucket is already exhausted.
count: increment === 4 ? 241 : 1,
retryAfterMs: 456,
};
}),
acquireConcurrency: vi.fn(async () => true),
releaseConcurrency: vi.fn(async () => undefined),
};
const limiter = new CustomWidgetRequestLimiter({ store });
const release = await limiter.acquire({ ...anonymousQuery, anonymousId: "198.51.100.10" });
await release();
await expect(limiter.acquire({ ...anonymousQuery, anonymousId: "203.0.113.20" })).rejects.toMatchObject({
code: "TOO_MANY_REQUESTS",
retryAfterMs: 456,
});
const incrementRate = vi.mocked(store.incrementRate);
expect(incrementRate.mock.calls[0]?.[0]).not.toBe(incrementRate.mock.calls[2]?.[0]);
expect(incrementRate.mock.calls[1]?.[0]).toBe(incrementRate.mock.calls[3]?.[0]);
expect(store.acquireConcurrency).toHaveBeenCalledTimes(2);
});
it("enforces category limits and exposes retry metadata", async () => {
const store: RequestLimitStore = {
incrementRate: vi.fn(async () => ({ count: 11, retryAfterMs: 321 })),
@@ -8,7 +8,14 @@ import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ActionButton, CustomJsxRenderer, CustomWidgetRuntimeProvider, SubFetch, ToggleSwitch } from "../runtime";
import {
ActionButton,
CustomJsxRenderer,
CustomWidgetRuntimeProvider,
RefreshButton,
SubFetch,
ToggleSwitch,
} from "../runtime";
import { createCustomJsxComponents } from "../jsx";
import { MAX_REFRESH_INTERVAL_MS, MAX_REFRESH_INTERVAL_SECONDS, normalizeRefreshInterval } from "../runtime/sub-fetch";
import type {
@@ -78,6 +85,7 @@ async function render(
port: CustomWidgetRuntimePort,
capabilities: readonly CustomJsxRequestCapability[] = [],
setQueryState?: (requestId: string, value: CustomWidgetPublishedQueryState | null) => void,
canInvalidateQueries = true,
) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
@@ -86,6 +94,7 @@ async function render(
<QueryClientProvider client={queryClient}>
<CustomWidgetRuntimeProvider
itemId="item-1"
canInvalidateQueries={canInvalidateQueries}
isEditMode={false}
requestCapabilities={capabilities}
port={port}
@@ -107,6 +116,16 @@ async function settle() {
}
describe("Custom Widget runtime ports", () => {
it("disables shared-cache refresh for anonymous public-board viewers", async () => {
const port = createPort();
await render(<RefreshButton />, port, [], undefined, false);
const button = host.querySelector<HTMLButtonElement>('button[aria-label="Refresh"]');
expect(button?.disabled).toBe(true);
button?.click();
expect(port.invalidate).not.toHaveBeenCalled();
});
it("clamps refresh intervals below the browser timer overflow boundary", () => {
expect(normalizeRefreshInterval(MAX_REFRESH_INTERVAL_SECONDS)).toBe(MAX_REFRESH_INTERVAL_MS);
expect(normalizeRefreshInterval(MAX_REFRESH_INTERVAL_SECONDS + 1)).toBe(MAX_REFRESH_INTERVAL_MS);
+148 -1
View File
@@ -25,12 +25,20 @@ describe("lean Custom Widget schema", () => {
trigger: "manual",
permission: "modify",
});
expect(customJsxRequestSchema.parse({ method: "DELETE", path: "/item" })).toMatchObject({
expect(customJsxRequestSchema.parse({ kind: "action", method: "DELETE", path: "/item" })).toMatchObject({
trigger: "manual",
permission: "full",
confirmation: { destructive: true },
});
});
it("rejects DELETE requests that could execute as automatic queries", () => {
expect(customJsxRequestSchema.safeParse({ method: "DELETE", path: "/item" }).success).toBe(false);
expect(
customJsxRequestSchema.safeParse({ kind: "query", trigger: "manual", method: "DELETE", path: "/item" }).success,
).toBe(false);
});
it("validates keyed sources, requests and options", () => {
const result = customWidgetDefinitionSchema.parse({
...CUSTOM_WIDGET_STARTER,
@@ -93,6 +101,80 @@ describe("lean Custom Widget schema", () => {
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, stateSchema: {} }).success).toBe(false);
});
it.each([
"http://127.1",
"http://2130706433",
"http://0x7f000001",
"http://0177.0.0.1",
"http://1.2.3",
"http://%31%32%37.0.0.1",
"https://%65xample.com",
"https://example%2ecom",
"https://example.com\\@attacker.invalid",
"https:\\\\example.com\\api",
" https://example.com",
"https://exa\tmple.com",
"https://example.com\n",
"https://example.com\u00a0",
"https://@example.com",
"https://:@example.com",
"https://example。com",
"https://127.0.0.1",
"https://-example.com",
"https://example-.com",
"https://example..com",
"https://example.com:00080",
"https://example.com:0000000065535",
"https://example.com:65536",
"https://[fe80::1%25eth0]",
"https://[::ffff:192.168.001.001]",
])("rejects ambiguous persisted URL spelling %s for sources and icons", (url) => {
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
sources: {
default: { ...CUSTOM_WIDGET_STARTER.sources.default, baseUrl: url },
},
}).success,
).toBe(false);
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: url }).success).toBe(false);
});
it.each([
"https://example.com",
"https://example.com.",
"https://münich.example",
"https://xn--mnich-kva.example",
"http://192.168.1.1:0",
"https://[2001:db8::1]:65535",
"https://[::ffff:192.168.1.1]",
])("accepts unambiguous HTTP URLs %s for sources and icons", (url) => {
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
sources: {
default: { ...CUSTOM_WIDGET_STARTER.sources.default, baseUrl: url },
},
}).success,
).toBe(true);
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: url }).success).toBe(true);
});
it("allows ordinary encoded icon paths and query values while rejecting oversized URLs", () => {
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
iconUrl: "https://example.com/icons/custom%20widget.svg?theme=dark#preview",
}).success,
).toBe(true);
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
iconUrl: `https://example.com/${"a".repeat(2048)}`,
}).success,
).toBe(false);
});
it("keeps auth secrets outside the document", () => {
const definition = customWidgetDefinitionSchema.parse({
...CUSTOM_WIDGET_STARTER,
@@ -106,6 +188,71 @@ describe("lean Custom Widget schema", () => {
).toEqual(["default:apiKey", "admin:username", "admin:password"]);
});
it("rejects credentials embedded in request paths, headers, and JSX", () => {
const requests = [
{
status: {
path: "/api/status?credential=Bearer-sk-secret-123456",
},
},
{
status: {
path: "/api/status",
headers: { "X-Auth": "Bearer sk-secret-123456" },
},
},
{
status: {
path: "/api/status",
headers: { "X-Service": "Basic dXNlcjpwYXNz" },
},
},
{
status: {
path: "/api/status",
headers: { "X-Service": "ghp_abcdefghijklmnopqrstuvwxyz123456" },
},
},
];
for (const candidate of requests) {
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: candidate }).success).toBe(
false,
);
}
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
template: "<Text>Bearer sk-secret-123456</Text>",
}).success,
).toBe(false);
});
it("allows harmless key fields, auth modes, headers, and authentication guidance", () => {
expect(
customWidgetDefinitionSchema.safeParse({
...CUSTOM_WIDGET_STARTER,
sources: {
default: {
...CUSTOM_WIDGET_STARTER.sources.default,
auth: { type: "apiKeyHeader", name: "X-Api-Key" },
},
},
requests: {
status: {
path: "/api/status?key=status&auth=none",
headers: {
Accept: "application/json",
"X-Api-Version": "2026-07",
"X-Feature-Key": "dashboard-layout",
},
body: { authenticationMode: "none", key: "status", tokenCount: 3 },
},
},
template: "<Stack><Text>Bearer authentication uses source credentials</Text></Stack>",
}).success,
).toBe(true);
});
it("requires installation confirmation for private and placeholder source URLs", () => {
const sources = {
default: { baseUrl: "https://pokeapi.co/api/v2", networkScope: "public" as const, auth: "none" as const },
@@ -1,4 +1,5 @@
import { createServer } from "node:http";
import { errors } from "undici";
import { describe, expect, test } from "vitest";
import {
@@ -6,11 +7,11 @@ import {
assertSafeStaticHeaders,
classifyAddress,
executeCustomWidgetRequest,
invalidateCustomWidgetResponseCache,
resolveAndValidateHost,
resolveSameOriginTarget,
validateCustomWidgetUrl,
} from "../server";
import { isCustomWidgetRequestTimeoutError } from "../server/request-executor";
describe("custom widget network policy", () => {
test.each([
@@ -53,6 +54,121 @@ describe("custom widget network policy", () => {
}
});
test.each([
["connect", new errors.ConnectTimeoutError()],
["headers", new errors.HeadersTimeoutError()],
["body", new errors.BodyTimeoutError()],
["generic timeout name", Object.assign(new Error("timed out"), { name: "ProxyTimeoutError" })],
])("recognizes %s timeout errors from the complete request lifecycle", (_label, error) => {
expect(isCustomWidgetRequestTimeoutError(error)).toBe(true);
});
test("recognizes an aborted request deadline as a timeout", () => {
const controller = new AbortController();
controller.abort();
expect(isCustomWidgetRequestTimeoutError(new errors.RequestAbortedError(), controller.signal)).toBe(true);
expect(isCustomWidgetRequestTimeoutError(new Error("socket failed"))).toBe(false);
});
test("normalizes response-body failures after headers arrive", async () => {
const events: Array<{ errorName: string; reason?: "timeout" }> = [];
const server = createServer((_request, response) => {
response.writeHead(200, { "content-type": "application/json" });
response.flushHeaders();
response.write('{"status":');
setImmediate(() => response.destroy());
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
try {
await expect(
executeCustomWidgetRequest({
baseUrl: `http://127.0.0.1:${address.port}`,
method: "GET",
networkScope: "loopback",
kind: "query",
logError: (event) => events.push(event),
}),
).rejects.toMatchObject({ code: "BAD_GATEWAY" });
expect(events).toHaveLength(1);
expect(events[0]?.errorName).toBe("TransportError");
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}
});
test("normalizes failures while draining a redirect body", async () => {
const server = createServer((_request, response) => {
response.writeHead(302, { location: "/target" });
response.flushHeaders();
response.write("partial redirect body");
setImmediate(() => response.destroy());
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
try {
await expect(
executeCustomWidgetRequest({
baseUrl: `http://127.0.0.1:${address.port}`,
method: "GET",
networkScope: "loopback",
kind: "query",
}),
).rejects.toMatchObject({ code: "BAD_GATEWAY" });
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}
});
test("maps Undici's response-size failure to the domain size limit", async () => {
const server = createServer((_request, response) => {
response.writeHead(200, { "content-type": "application/json" });
response.end(`"${"x".repeat(1024 * 1024)}"`);
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
try {
await expect(
executeCustomWidgetRequest({
baseUrl: `http://127.0.0.1:${address.port}`,
method: "GET",
networkScope: "loopback",
kind: "query",
}),
).rejects.toMatchObject({ code: "PAYLOAD_TOO_LARGE" });
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}
});
test("preserves domain errors raised while parsing the response body", async () => {
const server = createServer((_request, response) => {
response.writeHead(200, { "content-type": "application/json" });
response.end("{invalid");
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
try {
await expect(
executeCustomWidgetRequest({
baseUrl: `http://127.0.0.1:${address.port}`,
method: "GET",
networkScope: "loopback",
kind: "query",
}),
).rejects.toMatchObject({
code: "BAD_REQUEST",
message: "Upstream returned invalid JSON",
});
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}
});
test("preserves structured bodies for GET queries", async () => {
const server = createServer((request, response) => {
let body = "";
@@ -164,36 +280,6 @@ describe("custom widget network policy", () => {
}
});
test("evicts declared response-cache prefixes after an action", async () => {
let calls = 0;
const server = createServer((_request, response) => {
calls += 1;
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ calls }));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
const cacheKey = "custom-jsx:item:status:params";
const input = {
baseUrl: `http://127.0.0.1:${address.port}`,
method: "GET" as const,
networkScope: "loopback" as const,
kind: "query" as const,
cacheKey,
cacheTtlSeconds: 60,
};
try {
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 2 } });
} finally {
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}
});
test("allows only credential-free HTTP(S) URLs without fragments", () => {
expect(validateCustomWidgetUrl("https://example.com/api").href).toBe("https://example.com/api");
expect(() => validateCustomWidgetUrl("file:///etc/passwd")).toThrow("HTTP and HTTPS");