fix: harden v2 custom widgets and Workshop (#6480)

This commit is contained in:
Thomas authored and GitHub committed 2026-07-31 13:28:53 +02:00
1 parent e8a2c87c2d
commit 557ebe0a2f
138 files changed
+5151 -1976

No files matched your search

@@ -18,7 +18,9 @@ describe("AI prompt", () => {
expect(prompt).toContain("Example — Service dashboard");
expect(prompt).toContain("Example — Search and action");
expect(prompt).toContain("visual hierarchy");
expect(prompt).toContain('template set exactly to "__HOMARR_TEMPLATE__"');
expect(prompt).toContain("Put the complete JSX directly in its template string");
expect(prompt).toContain("copy one code block and paste it into Homarr once");
expect(prompt).not.toContain("fenced block followed by");
expect(prompt).toContain('trigger="manual"');
expect(prompt).toContain("never write `=> {` anywhere");
expect(prompt).toContain('"choicesFrom"');
@@ -45,4 +47,40 @@ 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"');
});
it("redacts credentials embedded directly in the free-form request", () => {
const prompt = buildCustomWidgetAiPrompt(
undefined,
null,
null,
"Use Authorization: Bearer sk-secret-123456 and token=ghp_abcdefghijklmnopqrstuvwxyz123456",
);
expect(prompt).not.toContain("sk-secret-123456");
expect(prompt).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz123456");
expect(prompt).toContain("Authorization: Bearer [REDACTED]");
expect(prompt).toContain("token=[REDACTED]");
});
});
@@ -7,12 +7,11 @@ import {
parseCustomWidgetClipboardDetailed,
} from "../core";
const response = (manifest: unknown, jsx = "<Text>Ready</Text>") =>
`\`\`\`json\n${JSON.stringify(manifest, null, 2)}\n\`\`\`\n\`\`\`jsx\n${jsx}\n\`\`\``;
const response = (manifest: unknown) => `\`\`\`json\n${JSON.stringify(manifest, null, 2)}\n\`\`\``;
describe("Custom Widget imports", () => {
it("accepts exactly one lean manifest and JSX block", () => {
const result = parseCustomWidgetAiResponse(response({ ...CUSTOM_WIDGET_STARTER, template: "__HOMARR_TEMPLATE__" }));
it("accepts one complete JSON block and loads its template", () => {
const result = parseCustomWidgetAiResponse(response({ ...CUSTOM_WIDGET_STARTER, template: "<Text>Ready</Text>" }));
expect(result.success).toBe(true);
if (result.success) expect(result.widget.template).toBe("<Text>Ready</Text>");
});
@@ -25,7 +24,7 @@ describe("Custom Widget imports", () => {
requests: [],
optionsSchema: {},
defaultOptions: {},
template: "__HOMARR_TEMPLATE__",
template: "<Text>Ready</Text>",
}),
);
expect(result.success).toBe(false);
@@ -34,12 +33,20 @@ describe("Custom Widget imports", () => {
it("reports missing fences and removed local state", () => {
expect(parseCustomWidgetAiResponse(JSON.stringify(CUSTOM_WIDGET_STARTER)).success).toBe(false);
const result = parseCustomWidgetAiResponse(
response({ ...CUSTOM_WIDGET_STARTER, stateSchema: {}, template: "__HOMARR_TEMPLATE__" }),
response({ ...CUSTOM_WIDGET_STARTER, stateSchema: {}, template: "<Text>Ready</Text>" }),
);
expect(result.success).toBe(false);
if (!result.success) expect(result.issues.some(({ code }) => code === "REMOVED_LOCAL_STATE")).toBe(true);
});
it("rejects additional code blocks", () => {
const result = parseCustomWidgetAiResponse(
`${response({ ...CUSTOM_WIDGET_STARTER, template: "<Text>Ready</Text>" })}\n\`\`\`jsx\n<Text>Old format</Text>\n\`\`\``,
);
expect(result.success).toBe(false);
if (!result.success) expect(result.issues.some(({ code }) => code === "AI_SINGLE_JSON_BLOCK_REQUIRED")).toBe(true);
});
it("returns a capability review from keyed records", () => {
const review = getImportReview(CUSTOM_WIDGET_STARTER);
expect(review).toMatchObject({ origins: ["https://example.com"], authTypes: ["none"], hasActions: false });
@@ -13,15 +13,12 @@ describe("reference widget capabilities", () => {
expect(parsed.requests.detail?.trigger).toBe("manual");
});
it("round-trips the full Pokédex through the exact two-block AI paste format", () => {
it("round-trips the full Pokédex through the single-block AI paste format", () => {
const pokedex = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-pokedex")?.widget;
if (!pokedex) throw new Error("Pokédex seed was not found");
const { template, ...manifest } = pokedex;
const parsed = parseCustomWidgetAiResponse(
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
);
const parsed = parseCustomWidgetAiResponse(`\`\`\`json\n${JSON.stringify(pokedex, null, 2)}\n\`\`\``);
expect(parsed.success).toBe(true);
if (parsed.success) expect(parsed.widget.template).toBe(template);
if (parsed.success) expect(parsed.widget.template).toBe(pokedex.template);
});
it("validates a polished Portainer dashboard with start, stop, and restart actions", () => {
@@ -38,10 +35,10 @@ describe("reference widget capabilities", () => {
});
it("round-trips the Portainer dashboard through AI paste", () => {
const { template, ...manifest } = PORTAINER_REFERENCE_WIDGET;
const parsed = parseCustomWidgetAiResponse(
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
`\`\`\`json\n${JSON.stringify(PORTAINER_REFERENCE_WIDGET, null, 2)}\n\`\`\``,
);
expect(parsed.success).toBe(true);
if (parsed.success) expect(parsed.widget.template).toBe(PORTAINER_REFERENCE_WIDGET.template);
});
});
@@ -0,0 +1,209 @@
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 { closeDispatcher, DISPATCHER_CLOSE_GRACE_MS } from "../server/request-dispatcher-lifecycle";
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(DISPATCHER_CLOSE_GRACE_MS);
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("consumes a late close rejection when cleanup starts after the deadline", async () => {
const abortReason = new Error("request deadline elapsed");
const closeFailure = new Error("late close failure");
const controller = new AbortController();
controller.abort(abortReason);
let rejectClose: ((reason: Error) => void) | undefined;
const close = vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
rejectClose = reject;
}),
);
const destroy = vi.fn(async () => undefined);
await expect(closeDispatcher({ close, destroy } as never, controller.signal)).rejects.toBe(abortReason);
rejectClose?.(closeFailure);
await Promise.resolve();
expect(close).toHaveBeenCalledOnce();
expect(destroy).toHaveBeenCalledOnce();
});
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 })),
+150 -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,82 @@ 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]",
"https://[0:0:0:0:0:0:0:1]",
"https://[2001:0db8::1]",
])("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 +190,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");