fix v2 hardening review findings

This commit is contained in:
ajnart committed 2026-07-28 15:28:58 +02:00
1 parent b82a6a7abc
commit a7eae3ff81
35 files changed
+1147 -277

No files matched your search

@@ -5,3 +5,4 @@ export {
parseStoredCustomWidgetDefinition,
serializeCustomWidgetDefinition,
} from "./router/custom-widget/stored-definition";
export { configureCustomWidgetSourceFromRequest } from "./router/custom-widget/secret-persistence";
@@ -1,19 +1,35 @@
import { TRPCError } from "@trpc/server";
import { encryptSecret } from "@homarr/common/server";
import type { Database } from "@homarr/db";
import { and, eq, handleTransactionsAsync } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
import type {
CustomWidgetCreateInput,
CustomWidgetSecretKind,
CustomWidgetSource,
HomarrCustomWidgetV2,
} from "@homarr/custom-widgets/core";
import type { CustomWidgetCreateInput, CustomWidgetSecretKind, CustomWidgetSource } from "@homarr/custom-widgets/core";
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
import { hasSameSecretBinding } from "./secret-policy";
import { serializeCustomWidgetDefinition } from "./stored-definition";
import { assertSecretSources, hasSameSecretBinding } from "./secret-policy";
import { parseStoredCustomWidgetDefinition, serializeCustomWidgetDefinition } from "./stored-definition";
type CustomWidgetSecretInput = CustomWidgetCreateInput["secrets"][number];
type ConfigureCustomWidgetSourceInput = {
definitionId: string;
sourceId: string;
baseUrl: string;
networkScope?: CustomWidgetSource["networkScope"];
secrets: CustomWidgetCreateInput["secrets"];
expectedSource?: CustomWidgetSource;
};
type SourceConfigurationIssue = "definition-not-found" | "source-not-found" | "binding-changed";
class SourceConfigurationError extends Error {
constructor(readonly issue: SourceConfigurationIssue) {
super(`Custom widget source configuration failed: ${issue}`);
this.name = "SourceConfigurationError";
}
}
export async function setCustomWidgetSecret(db: Database, definitionId: string, secret: CustomWidgetSecretInput) {
const updatedAt = new Date();
const secretRow = {
@@ -65,22 +81,39 @@ export async function setCustomWidgetSecret(db: Database, definitionId: string,
});
}
export async function configureCustomWidgetSource(
export async function configureCustomWidgetSource(db: Database, input: ConfigureCustomWidgetSourceInput) {
try {
return await persistCustomWidgetSourceConfiguration(db, input);
} catch (error) {
if (!(error instanceof SourceConfigurationError)) throw error;
if (error.issue === "definition-not-found") throw new TRPCError({ code: "NOT_FOUND" });
if (error.issue === "source-not-found") {
throw new TRPCError({ code: "NOT_FOUND", message: "Widget source not found" });
}
throw new TRPCError({
code: "CONFLICT",
message: "Widget source authentication changed while it was being configured",
});
}
}
export async function configureCustomWidgetSourceFromRequest(
db: Database,
input: {
definitionId: string;
sourceId: string;
definition: HomarrCustomWidgetV2;
previousSource: CustomWidgetSource;
source: CustomWidgetSource;
secrets: CustomWidgetCreateInput["secrets"];
},
input: ConfigureCustomWidgetSourceInput & { expectedSource: CustomWidgetSource },
) {
const definitionChanges = {
...serializeCustomWidgetDefinition(input.definition),
updatedAt: new Date(),
};
const bindingChanged = !hasSameSecretBinding(input.previousSource, input.source);
try {
return {
status: "configured" as const,
source: await persistCustomWidgetSourceConfiguration(db, input),
};
} catch (error) {
if (!(error instanceof SourceConfigurationError)) throw error;
return { status: error.issue } as const;
}
}
async function persistCustomWidgetSourceConfiguration(db: Database, input: ConfigureCustomWidgetSourceInput) {
let configuredSource: CustomWidgetSource | undefined;
const secretRows = input.secrets.map((secret) => ({
definitionId: input.definitionId,
sourceId: input.sourceId,
@@ -91,11 +124,19 @@ export async function configureCustomWidgetSource(
await handleTransactionsAsync(db, {
async handleAsync(database, schema) {
await database.transaction(async (transaction) => {
const [stored] = await transaction
.select()
.from(schema.customWidgetDefinitions)
.where(eq(schema.customWidgetDefinitions.id, input.definitionId))
.limit(1)
.for("update");
const sourceUpdate = prepareSourceUpdate(stored, input);
configuredSource = sourceUpdate.source;
await transaction
.update(schema.customWidgetDefinitions)
.set(definitionChanges)
.set(sourceUpdate.definitionChanges)
.where(eq(schema.customWidgetDefinitions.id, input.definitionId));
if (bindingChanged) {
if (sourceUpdate.bindingChanged) {
await transaction
.delete(schema.customWidgetSecrets)
.where(
@@ -120,39 +161,82 @@ export async function configureCustomWidgetSource(
});
},
handleSync(database) {
database.transaction((transaction) => {
transaction
.update(customWidgetDefinitions)
.set(definitionChanges)
.where(eq(customWidgetDefinitions.id, input.definitionId))
.run();
if (bindingChanged) {
database.transaction(
(transaction) => {
const stored = transaction
.select()
.from(customWidgetDefinitions)
.where(eq(customWidgetDefinitions.id, input.definitionId))
.limit(1)
.get();
const sourceUpdate = prepareSourceUpdate(stored, input);
configuredSource = sourceUpdate.source;
transaction
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, input.definitionId),
eq(customWidgetSecrets.sourceId, input.sourceId),
),
)
.update(customWidgetDefinitions)
.set(sourceUpdate.definitionChanges)
.where(eq(customWidgetDefinitions.id, input.definitionId))
.run();
}
for (const secret of secretRows) {
transaction
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, input.definitionId),
eq(customWidgetSecrets.sourceId, input.sourceId),
eq(customWidgetSecrets.kind, secret.kind),
),
)
.run();
transaction.insert(customWidgetSecrets).values(secret).run();
}
});
if (sourceUpdate.bindingChanged) {
transaction
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, input.definitionId),
eq(customWidgetSecrets.sourceId, input.sourceId),
),
)
.run();
}
for (const secret of secretRows) {
transaction
.delete(customWidgetSecrets)
.where(
and(
eq(customWidgetSecrets.definitionId, input.definitionId),
eq(customWidgetSecrets.sourceId, input.sourceId),
eq(customWidgetSecrets.kind, secret.kind),
),
)
.run();
transaction.insert(customWidgetSecrets).values(secret).run();
}
},
{ behavior: "immediate" },
);
},
});
if (!configuredSource) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
return configuredSource;
}
function prepareSourceUpdate(
stored: Parameters<typeof parseStoredCustomWidgetDefinition>[0] | undefined,
input: ConfigureCustomWidgetSourceInput,
) {
if (!stored) throw new SourceConfigurationError("definition-not-found");
const definition = parseStoredCustomWidgetDefinition(stored);
const previousSource = definition.sources[input.sourceId];
if (!previousSource) throw new SourceConfigurationError("source-not-found");
if (input.expectedSource && !hasSameCustomWidgetSourceAuthentication(previousSource, input.expectedSource)) {
throw new SourceConfigurationError("binding-changed");
}
const source = customWidgetSourceSchema.parse({
...previousSource,
baseUrl: input.baseUrl,
networkScope: input.networkScope ?? previousSource.networkScope,
});
assertSecretSources({ [input.sourceId]: source }, input.secrets);
return {
source,
bindingChanged: !hasSameSecretBinding(previousSource, source),
definitionChanges: {
...serializeCustomWidgetDefinition({
...definition,
sources: { ...definition.sources, [input.sourceId]: source },
}),
updatedAt: new Date(),
},
};
}
export async function clearCustomWidgetSecret(
@@ -80,20 +80,18 @@ export const secretProcedures = {
networkScope: input.networkScope ?? current.networkScope,
});
assertSecretSources({ [input.sourceId]: source }, input.secrets);
const updated = { ...definition, sources: { ...definition.sources, [input.sourceId]: source } };
await configureCustomWidgetSource(ctx.db, {
const configuredSource = await configureCustomWidgetSource(ctx.db, {
definitionId: input.definitionId,
sourceId: input.sourceId,
definition: updated,
previousSource: current,
source,
baseUrl: source.baseUrl,
networkScope: input.networkScope,
secrets: input.secrets,
});
return {
definitionId: input.definitionId,
sourceId: input.sourceId,
baseUrl: source.baseUrl,
networkScope: source.networkScope,
baseUrl: configuredSource.baseUrl,
networkScope: configuredSource.networkScope,
configuredSecrets: input.secrets.map(({ kind }) => kind),
};
}),
@@ -14,6 +14,7 @@ import { describe, expect, test } from "vitest";
import { customWidgetRouter } from "../../custom-widget/custom-widget-router";
import { getCustomWidgetConfigurationRequestForUser } from "../../custom-widget/configuration-requests";
import { configureCustomWidgetSourceFromRequest } from "../../custom-widget/secret-persistence";
import { serializeCustomWidgetDefinition } from "../../custom-widget/stored-definition";
const userId = createId();
@@ -399,6 +400,103 @@ describe("custom widget definition persistence", () => {
).toHaveLength(0);
});
test("uses the persisted source binding from inside the configuration transaction", async () => {
const db = await prepareDatabase();
const created = await createCaller(db).create({ ...jellyfin, secrets: [secret] });
const definition = customWidgetDefinitionSchema.parse(jellyfin);
const defaultSource = definition.sources.default;
if (!defaultSource) throw new Error("Jellyfin default source is missing");
await db
.update(customWidgetDefinitions)
.set(
serializeCustomWidgetDefinition({
...definition,
name: "Concurrent definition edit",
sources: {
...definition.sources,
default: { ...defaultSource, baseUrl: "https://changed.example/api" },
},
}),
)
.where(eq(customWidgetDefinitions.id, created.id));
await expect(
configureCustomWidgetSourceFromRequest(db, {
definitionId: created.id,
sourceId: "default",
baseUrl: defaultSource.baseUrl,
networkScope: defaultSource.networkScope,
secrets: [],
expectedSource: defaultSource,
}),
).resolves.toMatchObject({
status: "configured",
source: { baseUrl: defaultSource.baseUrl },
});
expect(await createCaller(db).get({ id: created.id })).toMatchObject({
name: "Concurrent definition edit",
sources: { default: { baseUrl: defaultSource.baseUrl } },
});
expect(
await db.query.customWidgetSecrets.findMany({
where: eq(customWidgetSecrets.definitionId, created.id),
}),
).toHaveLength(0);
});
test("rejects stale setup-link credentials after a concurrent authentication binding change", async () => {
const db = await prepareDatabase();
const created = await createCaller(db).create({ ...jellyfin, secrets: [] });
const definition = customWidgetDefinitionSchema.parse(jellyfin);
const expectedSource = definition.sources.default;
if (!expectedSource || typeof expectedSource.auth === "string") {
throw new Error("Jellyfin default source must use header authentication");
}
await db
.update(customWidgetDefinitions)
.set(
serializeCustomWidgetDefinition({
...definition,
name: "Concurrent definition edit",
sources: {
...definition.sources,
default: {
...expectedSource,
auth: { ...expectedSource.auth, name: "X-Replaced-Credential" },
},
},
}),
)
.where(eq(customWidgetDefinitions.id, created.id));
await expect(
configureCustomWidgetSourceFromRequest(db, {
definitionId: created.id,
sourceId: "default",
baseUrl: "https://configured.example/api",
networkScope: "public",
secrets: [secret],
expectedSource,
}),
).resolves.toEqual({ status: "binding-changed" });
expect(await createCaller(db).get({ id: created.id })).toMatchObject({
name: "Concurrent definition edit",
sources: {
default: {
baseUrl: expectedSource.baseUrl,
auth: { name: "X-Replaced-Credential" },
},
},
});
expect(
await db.query.customWidgetSecrets.findMany({
where: eq(customWidgetSecrets.definitionId, created.id),
}),
).toHaveLength(0);
});
test("clears persisted credentials when a general definition update changes its binding", async () => {
const db = await prepareDatabase();
const caller = createCaller(db);
@@ -42,6 +42,14 @@ export function getCustomWidgetHttpUrlIssue(value: string): CustomWidgetHttpUrlI
const rawHostname = withoutTrailingRootDot(hostAndPort.hostname);
const parsedHostname = withoutTrailingRootDot(url.hostname);
if (!rawHostname || !hasCanonicalParsedHostname(parsedHostname)) return "invalid";
if (
rawHostname.startsWith("[") &&
parsedHostname.startsWith("[") &&
!rawHostname.includes(".") &&
rawHostname.toLowerCase() !== parsedHostname
) {
return "invalid";
}
if (looksNumeric(rawHostname) && !isStrictIpv4(rawHostname)) return "invalid";
if (isStrictIpv4(parsedHostname) && rawHostname !== parsedHostname) return "invalid";
@@ -1,6 +1,6 @@
import type { createPinnedAgent } from "./network-policy";
const DISPATCHER_CLOSE_GRACE_MS = 1_000;
export const DISPATCHER_CLOSE_GRACE_MS = 1_000;
type CustomWidgetDispatcher = ReturnType<typeof createPinnedAgent>;
@@ -31,7 +31,10 @@ function detachDispatcherDestroy(dispatcher: CustomWidgetDispatcher): void {
}
function abortable<T>(operation: Promise<T>, signal: AbortSignal): Promise<T> {
if (signal.aborted) return Promise.reject(signal.reason ?? createAbortError());
if (signal.aborted) {
void operation.catch(() => undefined);
return Promise.reject(signal.reason ?? createAbortError());
}
return new Promise<T>((resolve, reject) => {
const onAbort = () => {
@@ -15,6 +15,7 @@ vi.mock("../server/network-policy", async (importOriginal) => {
});
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 = {
@@ -83,7 +84,7 @@ describe("custom widget request deadline", () => {
logError,
});
await vi.advanceTimersByTimeAsync(1_000);
await vi.advanceTimersByTimeAsync(DISPATCHER_CLOSE_GRACE_MS);
await expect(request).resolves.toMatchObject({ ok: true, status: 200, data: {} });
expect(close).toHaveBeenCalledOnce();
@@ -133,6 +134,28 @@ describe("custom widget request deadline", () => {
);
});
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 }) => {
@@ -128,6 +128,8 @@ describe("lean Custom Widget schema", () => {
"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({
+7 -3
View File
@@ -36,9 +36,13 @@ describe("createDocumentationLink parameter validation", () => {
meta.content = "https://docs.example.com/base/";
document.head.append(meta);
expect(createDocumentationLink("/docs/getting-started")).toBe("https://docs.example.com/base/docs/getting-started");
meta.remove();
try {
expect(createDocumentationLink("/docs/getting-started")).toBe(
"https://docs.example.com/base/docs/getting-started",
);
} finally {
meta.remove();
}
});
test("should work with only path parameter", () => {
@@ -0,0 +1,139 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import type { Root } from "react-dom/client";
import type * as MantineCoreExports from "@mantine/core";
import type * as TablerIconsExports from "@tabler/icons-react";
import CustomJsxDisplay from "./custom-jsx-display";
vi.mock("@homarr/api/client", () => ({
clientApi: {
useUtils: () => ({
widget: {
customApi: {
getData: {
invalidate: vi.fn(),
},
},
},
}),
},
fetchApi: {
customWidget: {
previewAction: { mutate: vi.fn() },
previewQuery: { query: vi.fn() },
previewRefresh: { mutate: vi.fn() },
},
widget: {
customApi: {
executeAction: { mutate: vi.fn() },
queryRequest: { query: vi.fn() },
refreshQueries: { mutate: vi.fn() },
},
},
},
}));
vi.mock("@homarr/modals", () => ({
useConfirmModal: () => ({ openConfirmModal: vi.fn() }),
}));
vi.mock("@homarr/notifications", () => ({
showErrorNotification: vi.fn(),
showSuccessNotification: vi.fn(),
}));
vi.mock("@homarr/translation/client", () => ({
useScopedI18n: () => (key: string) => (key === "refresh" ? "Refresh" : key),
}));
vi.mock("@tanstack/react-query", () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
vi.mock("@mantine/core", async (importOriginal) => {
const original = await importOriginal<typeof MantineCoreExports>();
const renderElement = createElement;
const MockContainer = ({ children }: { children?: ReactNode }) => renderElement("div", null, children);
const ActionIcon = ({
children,
loading: _loading,
color: _color,
variant: _variant,
size: _size,
...props
}: ComponentPropsWithoutRef<"button"> & {
children?: ReactNode;
loading?: boolean;
color?: string;
variant?: string;
size?: string;
}) => renderElement("button", props, children);
return {
...original,
ActionIcon,
Alert: MockContainer,
Box: MockContainer,
Stack: MockContainer,
Text: MockContainer,
};
});
vi.mock("@tabler/icons-react", async (importOriginal) => {
const original = await importOriginal<typeof TablerIconsExports>();
return {
...original,
IconRefresh: () => createElement("span", { "aria-hidden": true }),
};
});
describe("CustomJsxDisplay preview refresh", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { value: true, writable: true });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
});
const renderPreview = async (canInvalidateQueries?: boolean) => {
await act(async () => {
root.render(
<CustomJsxDisplay
data={{
template: '<RefreshButton label="Refresh" />',
data: {},
previewSessionId: "preview-session",
...(canInvalidateQueries === undefined ? {} : { canInvalidateQueries }),
}}
/>,
);
});
return container.querySelector<HTMLButtonElement>('button[aria-label="Refresh"]');
};
it("enables refresh when a preview session omits the invalidation capability", async () => {
const button = await renderPreview();
expect(button).not.toBeNull();
expect(button?.disabled).toBe(false);
});
it("honors an explicitly disabled invalidation capability", async () => {
const button = await renderPreview(false);
expect(button).not.toBeNull();
expect(button?.disabled).toBe(true);
});
});
@@ -69,7 +69,7 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
previewSessionId={previewSessionId}
previewLiveActions={data.previewLiveActions === true}
queriesDisabled={data.queriesDisabled === true}
canInvalidateQueries={data.canInvalidateQueries === true}
canInvalidateQueries={typeof data.canInvalidateQueries === "boolean" ? data.canInvalidateQueries : undefined}
isEditMode={data.isEditMode === true}
requestCapabilities={capabilities}
setQueryState={publishQueryState}
@@ -27,6 +27,9 @@ describe("PocketBase URL compatibility", () => {
"http://09.0.0.1",
"http://099.0.0.1",
"http://[:::1]",
"http://[:1:2:3:4:5:6:7:8]",
"http://[1:2:3:4:5:6:7:8:]",
"http://[192.168.1.1::]",
"http://[::ffff:192.168.001.001]",
"http://[::ffff:192.168.1.01]",
"http://[fe80::1%25eth0]",
@@ -70,6 +73,11 @@ describe("PocketBase URL compatibility", () => {
expect(new PocketBaseUrl("https://例え.テスト.").hostname).toBe("xn--r8jz45g.xn--zckzah.");
});
test("normalizes IPv6 hostnames like the native parser", () => {
expect(new PocketBaseUrl("http://[1:2:3:4:5:6:7::]").hostname).toBe("[1:2:3:4:5:6:7:0]");
expect(new PocketBaseUrl("http://[::ffff:192.168.1.1]").hostname).toBe("[::ffff:c0a8:101]");
});
test.each([
"https://example.com",
"https://example.com.",
+60 -17
View File
@@ -99,8 +99,9 @@ function parseAuthority(authority: string): ParsedAuthority {
const closeIndex = hostAndPort.indexOf("]");
if (closeIndex < 0) throw new TypeError("Invalid URL");
const address = hostAndPort.slice(1, closeIndex);
if (!isValidIpv6(address)) throw new TypeError("Invalid URL");
hostname = `[${address.toLowerCase()}]`;
const normalizedAddress = normalizeIpv6(address);
if (normalizedAddress === null) throw new TypeError("Invalid URL");
hostname = `[${normalizedAddress}]`;
const suffix = hostAndPort.slice(closeIndex + 1);
if (suffix) {
if (!suffix.startsWith(":")) throw new TypeError("Invalid URL");
@@ -167,24 +168,66 @@ function hasForbiddenUrlCharacter(value: string): boolean {
});
}
function isValidIpv6(value: string): boolean {
if (value.includes("%")) return false;
function normalizeIpv6(value: string): string | null {
if (value.includes("%")) return null;
const address = value;
if (!address.includes(":") || address.includes(":::") || /[^0-9A-Fa-f:.]/u.test(address)) return false;
if (address.indexOf("::") !== address.lastIndexOf("::")) return false;
const groups = address.split(":").filter(Boolean);
let groupCount = groups.length;
for (const [index, group] of groups.entries()) {
if (group.includes(".")) {
if (index !== groups.length - 1 || !isStrictIpv4(group)) return false;
groupCount += 1;
} else if (!/^[0-9A-Fa-f]{1,4}$/u.test(group)) {
return false;
}
if (!address.includes(":") || address.includes(":::") || /[^0-9A-Fa-f:.]/u.test(address)) return null;
if (address.indexOf("::") !== address.lastIndexOf("::")) return null;
if ((address.startsWith(":") && !address.startsWith("::")) || (address.endsWith(":") && !address.endsWith("::"))) {
return null;
}
return address.includes("::") ? groupCount < 8 : groupCount === 8;
const hasCompression = address.includes("::");
const [left = "", right = ""] = hasCompression ? address.split("::") : [address, ""];
if (hasCompression && left.includes(".")) return null;
const leftGroups = parseIpv6Groups(left);
const rightGroups = parseIpv6Groups(right);
if (leftGroups === null || rightGroups === null) return null;
const explicitGroupCount = leftGroups.length + rightGroups.length;
if ((!hasCompression && explicitGroupCount !== 8) || (hasCompression && explicitGroupCount >= 8)) return null;
const groups = hasCompression
? [...leftGroups, ...Array.from({ length: 8 - explicitGroupCount }, () => 0), ...rightGroups]
: leftGroups;
let bestStart = -1;
let bestLength = 1;
for (let index = 0; index < groups.length;) {
if (groups[index] !== 0) {
index += 1;
continue;
}
let end = index + 1;
while (end < groups.length && groups[end] === 0) end += 1;
if (end - index > bestLength) {
bestStart = index;
bestLength = end - index;
}
index = end;
}
const hexadecimalGroups = groups.map((group) => group.toString(16));
if (bestStart < 0) return hexadecimalGroups.join(":");
const before = hexadecimalGroups.slice(0, bestStart).join(":");
const after = hexadecimalGroups.slice(bestStart + bestLength).join(":");
return `${before}::${after}`;
}
function parseIpv6Groups(value: string): number[] | null {
if (!value) return [];
const groups = value.split(":");
const parsed: number[] = [];
for (const [index, group] of groups.entries()) {
if (group.includes(".")) {
if (index !== groups.length - 1 || !isStrictIpv4(group)) return null;
const parts = group.split(".").map(Number);
parsed.push(((parts[0] ?? 0) << 8) | (parts[1] ?? 0), ((parts[2] ?? 0) << 8) | (parts[3] ?? 0));
} else {
if (!/^[0-9A-Fa-f]{1,4}$/u.test(group)) return null;
parsed.push(Number.parseInt(group, 16));
}
}
return parsed;
}
function isStrictIpv4(value: string): boolean {
+1
View File
@@ -37,6 +37,7 @@ describe("Workshop URL configuration", () => {
["/", "/"],
["/docs", "/docs/"],
["/docs/", "/docs/"],
["/docs..preview", "/docs..preview/"],
])("normalizes DOCS_BASE_URL %s", (input, expected) => {
expect(normalizeDocsBaseUrl(input)).toBe(expected);
});