harden v2 custom widgets and workshop
This commit is contained in:
1 parent
e8a2c87c2d
commit
723b46926a
194 files changed
+44862
-1265
No files matched your search
@@ -156,24 +156,6 @@ const requestSignal = (signal?: AbortSignal) =>
|
||||
: [AbortSignal.timeout(WORKSHOP_REQUEST_TIMEOUT_MS)],
|
||||
);
|
||||
|
||||
function oauthText(...values: unknown[]) {
|
||||
return values.find((value): value is string => typeof value === "string" && value.trim().length > 0)?.trim();
|
||||
}
|
||||
|
||||
function githubProfile(meta: Record<string, unknown> | undefined, record: { id: string }) {
|
||||
const rawUser =
|
||||
meta?.rawUser && typeof meta.rawUser === "object" ? (meta.rawUser as Record<string, unknown>) : undefined;
|
||||
const displayName = oauthText(meta?.name, meta?.username, rawUser?.name, rawUser?.login);
|
||||
const avatarUrl = oauthText(meta?.avatarUrl, meta?.avatarURL, rawUser?.avatar_url);
|
||||
const githubUsername = oauthText(meta?.username, rawUser?.login);
|
||||
return {
|
||||
displayName: (displayName ?? `GitHub user ${String(record.id ?? "").slice(0, 8)}`).slice(0, 100),
|
||||
avatarUrl: avatarUrl?.startsWith("https://") ? avatarUrl : undefined,
|
||||
githubUsername,
|
||||
githubProfileUrl: githubUsername ? `https://github.com/${encodeURIComponent(githubUsername)}` : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const timestamp = (value: string) => (Number.isNaN(Date.parse(value)) ? 0 : Date.parse(value));
|
||||
|
||||
function sortListings(items: WorkshopSubmissionSummary[], sort: WorkshopListOptions["sort"]) {
|
||||
@@ -349,9 +331,7 @@ export class WorkshopBackend {
|
||||
provider: "github",
|
||||
createData: { displayName: "GitHub user" },
|
||||
});
|
||||
const profile = githubProfile(auth.meta, auth.record);
|
||||
const updated = await this.pocketBase.collection("users").update(auth.record.id, profile);
|
||||
this.pocketBase.authStore.save(auth.token, updated);
|
||||
this.pocketBase.authStore.save(auth.token, auth.record);
|
||||
return this.currentUser;
|
||||
} catch (error) {
|
||||
throw workshopError(error, "GitHub sign-in failed");
|
||||
@@ -578,7 +558,8 @@ export class WorkshopBackend {
|
||||
|
||||
public async toggleOutdated(id: string, outdated: boolean) {
|
||||
try {
|
||||
await this.pocketBase.collection("submissions").update(id, { outdated });
|
||||
const current = await this.get(id);
|
||||
await this.pocketBase.collection("submissions").update(id, { outdated, expectedRevision: current.revision });
|
||||
return this.get(id);
|
||||
} catch (error) {
|
||||
throw workshopError(error, "Failed to update submission status");
|
||||
|
||||
@@ -68,13 +68,17 @@ describe("WorkshopBackend", () => {
|
||||
test("lets PocketBase own the complete GitHub popup flow", async () => {
|
||||
mocks.authWithOAuth2.mockResolvedValue({
|
||||
token: "token",
|
||||
record: { id: "user-id" },
|
||||
record: {
|
||||
id: "user-id",
|
||||
displayName: "octocat",
|
||||
githubUsername: "octocat",
|
||||
githubProfileUrl: "https://github.com/octocat",
|
||||
},
|
||||
meta: { username: "octocat" },
|
||||
});
|
||||
mocks.update.mockResolvedValue({ id: "user-id", displayName: "octocat" });
|
||||
|
||||
const client = new WorkshopBackend("https://workshop.example.com");
|
||||
await client.signInWithGitHub();
|
||||
const user = await client.signInWithGitHub();
|
||||
|
||||
expect(mocks.authWithOAuth2).toHaveBeenCalledWith({
|
||||
provider: "github",
|
||||
@@ -82,6 +86,8 @@ describe("WorkshopBackend", () => {
|
||||
});
|
||||
expect(mocks.authWithOAuth2.mock.calls[0]?.[0]).not.toHaveProperty("requestKey");
|
||||
expect(mocks.authWithOAuth2.mock.calls[0]?.[0]).not.toHaveProperty("urlCallback");
|
||||
expect(mocks.update).not.toHaveBeenCalled();
|
||||
expect(user).toMatchObject({ displayName: "octocat", githubUsername: "octocat" });
|
||||
});
|
||||
|
||||
test("exposes the typed submission collection service", () => {
|
||||
@@ -150,6 +156,31 @@ describe("WorkshopBackend", () => {
|
||||
expect(payload).not.toHaveProperty("widgetSchema");
|
||||
});
|
||||
|
||||
test("uses the current revision when toggling submission status", async () => {
|
||||
const client = new WorkshopBackend("https://workshop.example.com");
|
||||
const current = {
|
||||
...listingRecord(),
|
||||
type: "customCss" as const,
|
||||
content: ".dashboard { color: red; }",
|
||||
revision: 4,
|
||||
outdated: false,
|
||||
};
|
||||
const updated = { ...current, revision: 5, outdated: true };
|
||||
vi.spyOn(client, "get")
|
||||
.mockResolvedValueOnce(current as never)
|
||||
.mockResolvedValueOnce(updated as never);
|
||||
mocks.update.mockResolvedValue(updated);
|
||||
|
||||
await expect(client.toggleOutdated(current.id, true)).resolves.toMatchObject({
|
||||
revision: 5,
|
||||
outdated: true,
|
||||
});
|
||||
expect(mocks.update).toHaveBeenCalledWith(current.id, {
|
||||
outdated: true,
|
||||
expectedRevision: 4,
|
||||
});
|
||||
});
|
||||
|
||||
test("uses PocketBase filtering and pagination when the listing view is current", async () => {
|
||||
mocks.getList.mockResolvedValue({
|
||||
page: 1,
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { CUSTOM_WIDGET_STARTER, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { PocketBaseUrl } from "./pocketbase-url";
|
||||
|
||||
describe("PocketBase URL compatibility", () => {
|
||||
test.each([
|
||||
"https://example.com",
|
||||
"https://example.com.",
|
||||
"https://münich.example",
|
||||
"https://xn--mnich-kva.example",
|
||||
"http://example.com:0",
|
||||
"http://example.com:",
|
||||
"http://example.com:80",
|
||||
"http://[::1]:8090",
|
||||
"http://[::ffff:192.168.1.1]",
|
||||
])("accepts canonical URL %s", (value) => {
|
||||
expect(URL.canParse(value)).toBe(true);
|
||||
expect(PocketBaseUrl.canParse(value)).toBe(true);
|
||||
});
|
||||
|
||||
test.each([
|
||||
"http://",
|
||||
"https://:",
|
||||
"http://1.2.3.4.5",
|
||||
"http://09.0.0.1",
|
||||
"http://099.0.0.1",
|
||||
"http://[:::1]",
|
||||
"http://[::ffff:192.168.001.001]",
|
||||
"http://[::ffff:192.168.1.01]",
|
||||
"http://[fe80::1%25eth0]",
|
||||
"http://example.com:65536",
|
||||
"https://xn--a.example",
|
||||
"https://xn--0.example",
|
||||
"https://xn--abc.example",
|
||||
])("rejects canonical invalid URL %s", (value) => {
|
||||
expect(URL.canParse(value)).toBe(false);
|
||||
expect(PocketBaseUrl.canParse(value)).toBe(false);
|
||||
});
|
||||
|
||||
test.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://example-.com",
|
||||
"https://example..com",
|
||||
"https://example.com:00080",
|
||||
"https://example.com:0000000065535",
|
||||
"https://example。com",
|
||||
"https://127.0.0.1",
|
||||
" https://example.com",
|
||||
"https://exa\tmple.com",
|
||||
"https://example.com/path\u00a0",
|
||||
])("conservatively rejects WHATWG-normalized URL %s", (value) => {
|
||||
expect(URL.canParse(value)).toBe(true);
|
||||
expect(PocketBaseUrl.canParse(value)).toBe(false);
|
||||
});
|
||||
|
||||
test("normalizes international hostnames like the native parser", () => {
|
||||
expect(new PocketBaseUrl("https://münich.example").hostname).toBe("xn--mnich-kva.example");
|
||||
expect(new PocketBaseUrl("https://例え.テスト.").hostname).toBe("xn--r8jz45g.xn--zckzah.");
|
||||
});
|
||||
|
||||
test.each([
|
||||
"https://example.com",
|
||||
"https://example.com.",
|
||||
"https://münich.example",
|
||||
"https://例え.テスト",
|
||||
"https://xn--r8jz45g.xn--zckzah",
|
||||
"http://192.168.1.1:0",
|
||||
"https://[2001:db8::1]:65535",
|
||||
"https://[::ffff:192.168.1.1]",
|
||||
"http://0.0.0.0",
|
||||
"http://255.255.255.255",
|
||||
"https://example.com:",
|
||||
"https://example.com:0",
|
||||
"https://example.com:65535",
|
||||
"http://[::]",
|
||||
"http://[::1]",
|
||||
"http://[1:2:3:4:5:6:7:8]",
|
||||
"http://[1:2:3:4:5:6:7::]",
|
||||
"https://faß.de",
|
||||
"https://xn--fa-hia.de",
|
||||
"https://مثال.إختبار",
|
||||
"https://a_b.example",
|
||||
"https://example.com/%5c@evil",
|
||||
"https://example.com/%2f%2fevil",
|
||||
"https://example.com/icon.svg?next=https%3A%2F%2Fevil#preview",
|
||||
"http://127.1",
|
||||
"http://2130706433",
|
||||
"http://0x7f000001",
|
||||
"http://0xffffffff",
|
||||
"http://0x100000000",
|
||||
"http://0177.0.0.1",
|
||||
"http://0377.0377.0377.0377",
|
||||
"http://1.2.3",
|
||||
"http://1.",
|
||||
"http://1..2",
|
||||
"http://256.0.0.1",
|
||||
"http://00.0.0.0",
|
||||
"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:01",
|
||||
"https://example.com:00080",
|
||||
"https://example.com:0000000065535",
|
||||
"https://example.com:65536",
|
||||
"https://example.com:655350",
|
||||
"https://[fe80::1%25eth0]",
|
||||
"https://[::ffff:192.168.001.001]",
|
||||
"https://[1:2:3:4:5:6:7:8:9]",
|
||||
"https://\u200d.example",
|
||||
"http:example.com",
|
||||
"https:/example.com",
|
||||
"https:///example.com",
|
||||
"ftp://example.com",
|
||||
"file:///tmp/icon.svg",
|
||||
"https://user:password@example.com",
|
||||
])("keeps canonical source and icon validation in parity for %s", (value) => {
|
||||
const validate = (UrlImplementation: typeof URL, field: "source" | "icon") => {
|
||||
const runtime = globalThis as unknown as { URL: typeof URL };
|
||||
const originalUrl = runtime.URL;
|
||||
runtime.URL = UrlImplementation;
|
||||
try {
|
||||
const definition =
|
||||
field === "source"
|
||||
? {
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: {
|
||||
default: { ...CUSTOM_WIDGET_STARTER.sources.default, baseUrl: value },
|
||||
},
|
||||
}
|
||||
: { ...CUSTOM_WIDGET_STARTER, iconUrl: value };
|
||||
return customWidgetDefinitionSchema.safeParse(definition).success;
|
||||
} finally {
|
||||
runtime.URL = originalUrl;
|
||||
}
|
||||
};
|
||||
|
||||
const nativeUrl = URL;
|
||||
expect(validate(PocketBaseUrl as unknown as typeof URL, "source")).toBe(validate(nativeUrl, "source"));
|
||||
expect(validate(PocketBaseUrl as unknown as typeof URL, "icon")).toBe(validate(nativeUrl, "icon"));
|
||||
});
|
||||
|
||||
test("exposes the URL fields used by the canonical schema", () => {
|
||||
const url = new PocketBaseUrl("https://user:password@example.com:8443/icon.svg?token=secret&mode=dark#icon");
|
||||
expect(url).toMatchObject({
|
||||
protocol: "https:",
|
||||
username: "user",
|
||||
password: "password",
|
||||
hostname: "example.com",
|
||||
port: "8443",
|
||||
search: "?token=secret&mode=dark",
|
||||
hash: "#icon",
|
||||
});
|
||||
expect(url.searchParams.keys()).toEqual(["token", "mode"]);
|
||||
});
|
||||
|
||||
test("validates credential queries without iterable URLSearchParams", () => {
|
||||
const runtime = globalThis as unknown as { URL: typeof URL };
|
||||
const originalUrl = runtime.URL;
|
||||
runtime.URL = PocketBaseUrl as unknown as typeof URL;
|
||||
try {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://example.com/icon.svg?clientSecret=must-never-be-published",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
requests: {
|
||||
default: {
|
||||
...CUSTOM_WIDGET_STARTER.requests.default,
|
||||
path: "/api/status?key=status&auth=none",
|
||||
},
|
||||
},
|
||||
}).success,
|
||||
).toBe(true);
|
||||
} finally {
|
||||
runtime.URL = originalUrl;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
import { toASCII } from "tr46";
|
||||
|
||||
interface PortableSearchParams {
|
||||
keys(): string[];
|
||||
}
|
||||
|
||||
interface ParsedAuthority {
|
||||
username: string;
|
||||
password: string;
|
||||
hostname: string;
|
||||
port: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* PocketBase's Goja runtime intentionally has no browser URL global. The
|
||||
* canonical Custom Widget schema uses the small subset implemented here.
|
||||
*/
|
||||
export class PocketBaseUrl {
|
||||
public readonly protocol: string;
|
||||
public readonly username: string;
|
||||
public readonly password: string;
|
||||
public readonly hostname: string;
|
||||
public readonly port: string;
|
||||
public readonly search: string;
|
||||
public readonly hash: string;
|
||||
public readonly origin: string;
|
||||
public readonly searchParams: PortableSearchParams;
|
||||
|
||||
public static canParse(value: unknown): boolean {
|
||||
try {
|
||||
const parsed = new PocketBaseUrl(value);
|
||||
void parsed;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public constructor(value: unknown) {
|
||||
if (typeof value !== "string" || hasForbiddenUrlCharacter(value) || value.includes("\\")) {
|
||||
throw new TypeError("Invalid URL");
|
||||
}
|
||||
|
||||
const scheme = value.match(/^([A-Za-z][A-Za-z0-9+.-]*):/u);
|
||||
if (!scheme?.[1]) throw new TypeError("Invalid URL");
|
||||
this.protocol = `${scheme[1].toLowerCase()}:`;
|
||||
|
||||
const afterScheme = value.slice(scheme[0].length);
|
||||
const hashIndex = afterScheme.indexOf("#");
|
||||
const withoutHash = hashIndex < 0 ? afterScheme : afterScheme.slice(0, hashIndex);
|
||||
this.hash = hashIndex < 0 ? "" : afterScheme.slice(hashIndex);
|
||||
const searchIndex = withoutHash.indexOf("?");
|
||||
const withoutSearch = searchIndex < 0 ? withoutHash : withoutHash.slice(0, searchIndex);
|
||||
this.search = searchIndex < 0 ? "" : withoutHash.slice(searchIndex);
|
||||
this.searchParams = createSearchParams(this.search);
|
||||
|
||||
const requiresAuthority = this.protocol === "http:" || this.protocol === "https:" || this.protocol === "ftp:";
|
||||
if (!withoutSearch.startsWith("//")) {
|
||||
if (requiresAuthority) throw new TypeError("Invalid URL");
|
||||
this.username = "";
|
||||
this.password = "";
|
||||
this.hostname = "";
|
||||
this.port = "";
|
||||
this.origin = "null";
|
||||
return;
|
||||
}
|
||||
|
||||
const authorityAndPath = withoutSearch.slice(2);
|
||||
const slashIndex = authorityAndPath.indexOf("/");
|
||||
const authority = slashIndex < 0 ? authorityAndPath : authorityAndPath.slice(0, slashIndex);
|
||||
const parsed = parseAuthority(authority);
|
||||
this.username = parsed.username;
|
||||
this.password = parsed.password;
|
||||
this.hostname = parsed.hostname;
|
||||
this.port = parsed.port;
|
||||
this.origin = `${this.protocol}//${this.hostname}${this.port ? `:${this.port}` : ""}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function installPocketBaseUrlPolyfill(): void {
|
||||
const runtime = globalThis as unknown as Record<string, unknown>;
|
||||
if (typeof runtime.URL === "undefined") runtime.URL = PocketBaseUrl;
|
||||
}
|
||||
|
||||
function parseAuthority(authority: string): ParsedAuthority {
|
||||
if (!authority || /[。.。]/u.test(authority)) throw new TypeError("Invalid URL");
|
||||
const atIndex = authority.lastIndexOf("@");
|
||||
const credentials = atIndex < 0 ? "" : authority.slice(0, atIndex);
|
||||
const hostAndPort = atIndex < 0 ? authority : authority.slice(atIndex + 1);
|
||||
if (!hostAndPort) throw new TypeError("Invalid URL");
|
||||
|
||||
const credentialSeparator = credentials.indexOf(":");
|
||||
const username = credentialSeparator < 0 ? credentials : credentials.slice(0, credentialSeparator);
|
||||
const password = credentialSeparator < 0 ? "" : credentials.slice(credentialSeparator + 1);
|
||||
|
||||
let hostname: string;
|
||||
let port = "";
|
||||
if (hostAndPort.startsWith("[")) {
|
||||
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 suffix = hostAndPort.slice(closeIndex + 1);
|
||||
if (suffix) {
|
||||
if (!suffix.startsWith(":")) throw new TypeError("Invalid URL");
|
||||
port = suffix.length === 1 ? "" : validatePort(suffix.slice(1));
|
||||
}
|
||||
} else {
|
||||
const firstColon = hostAndPort.indexOf(":");
|
||||
const lastColon = hostAndPort.lastIndexOf(":");
|
||||
if (firstColon !== lastColon) throw new TypeError("Invalid URL");
|
||||
hostname = firstColon < 0 ? hostAndPort : hostAndPort.slice(0, firstColon);
|
||||
const portValue = firstColon < 0 ? "" : hostAndPort.slice(firstColon + 1);
|
||||
port = portValue ? validatePort(portValue) : "";
|
||||
const normalizedHostname = normalizeHostname(hostname);
|
||||
if (!normalizedHostname) throw new TypeError("Invalid URL");
|
||||
hostname = normalizedHostname;
|
||||
}
|
||||
|
||||
return { username, password, hostname: hostname.toLowerCase(), port };
|
||||
}
|
||||
|
||||
function validatePort(value: string): string {
|
||||
if (!/^(?:0|[1-9]\d{0,4})$/u.test(value)) throw new TypeError("Invalid URL");
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port > 65_535) throw new TypeError("Invalid URL");
|
||||
return String(port);
|
||||
}
|
||||
|
||||
function normalizeHostname(value: string): string | null {
|
||||
const ascii = toASCII(value, {
|
||||
checkHyphens: false,
|
||||
checkBidi: true,
|
||||
checkJoiners: true,
|
||||
useSTD3ASCIIRules: false,
|
||||
transitionalProcessing: false,
|
||||
verifyDNSLength: false,
|
||||
ignoreInvalidPunycode: false,
|
||||
});
|
||||
if (!ascii || hasForbiddenUrlCharacter(ascii) || /[#%/:<>?@[\\\]^|]/u.test(ascii)) return null;
|
||||
const candidate = ascii.endsWith(".") ? ascii.slice(0, -1) : ascii;
|
||||
if (!candidate || candidate.length > 253 || !/^[A-Za-z0-9._-]+$/u.test(candidate)) return null;
|
||||
if (looksNumeric(candidate)) {
|
||||
const rawCandidate = value.endsWith(".") ? value.slice(0, -1) : value;
|
||||
return isStrictIpv4(candidate) && rawCandidate === candidate ? ascii.toLowerCase() : null;
|
||||
}
|
||||
const isValid = candidate
|
||||
.split(".")
|
||||
.every((part) => Boolean(part) && part.length <= 63 && !part.startsWith("-") && !part.endsWith("-"));
|
||||
return isValid ? ascii.toLowerCase() : null;
|
||||
}
|
||||
|
||||
function hasForbiddenUrlCharacter(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return (
|
||||
code <= 0x20 ||
|
||||
(code >= 0x7f && code <= 0xa0) ||
|
||||
code === 0x1680 ||
|
||||
(code >= 0x2000 && code <= 0x200f) ||
|
||||
(code >= 0x2028 && code <= 0x202f) ||
|
||||
(code >= 0x205f && code <= 0x206f) ||
|
||||
code === 0x3000 ||
|
||||
code === 0xfeff
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function isValidIpv6(value: string): boolean {
|
||||
if (value.includes("%")) return false;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return address.includes("::") ? groupCount < 8 : groupCount === 8;
|
||||
}
|
||||
|
||||
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 looksNumeric(value: string): boolean {
|
||||
return value.split(".").every((part) => /^(?:\d+|0[xX][0-9A-Fa-f]+)$/u.test(part));
|
||||
}
|
||||
|
||||
function createSearchParams(search: string): PortableSearchParams {
|
||||
const keys = search
|
||||
? search
|
||||
.slice(1)
|
||||
.split("&")
|
||||
.map((entry) => entry.split("=", 1)[0] ?? "")
|
||||
.map(decodeQueryPart)
|
||||
: [];
|
||||
return { keys: () => [...keys] };
|
||||
}
|
||||
|
||||
function decodeQueryPart(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value.replaceAll("+", " "));
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { installPocketBaseUrlPolyfill } from "./pocketbase-url";
|
||||
|
||||
installPocketBaseUrlPolyfill();
|
||||
|
||||
export type PocketBaseWidgetValidationResult = { success: true; content: string } | { success: false; error: string };
|
||||
|
||||
/**
|
||||
* PocketBase loads the generated CommonJS bundle of this module in its
|
||||
* embedded JSVM. Keeping the canonical schema here prevents direct Workshop
|
||||
* writes from accepting definitions that Homarr would reject at install time.
|
||||
*/
|
||||
export function validatePocketBaseWidget(content: string): PocketBaseWidgetValidationResult {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(content) as unknown;
|
||||
} catch {
|
||||
return { success: false, error: "Widget content must be valid JSON" };
|
||||
}
|
||||
|
||||
const result = customWidgetDefinitionSchema.safeParse(parsed);
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
result.error.issues
|
||||
.slice(0, 5)
|
||||
.map((issue) => `${issue.path.join(".") || "widget"}: ${issue.message}`)
|
||||
.join("\n") || "Invalid widget",
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, content: JSON.stringify(result.data) };
|
||||
}
|
||||
@@ -2,7 +2,52 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import { CUSTOM_WIDGET_STARTER } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { validateWorkshopWidget, workshopSubmissionInputSchema, workshopSubmissionSummarySchema } from "./schema";
|
||||
import {
|
||||
normalizeDocsBaseUrl,
|
||||
normalizeHttpUrl,
|
||||
resolveHomarrUrlConfig,
|
||||
validateWorkshopWidget,
|
||||
workshopSubmissionInputSchema,
|
||||
workshopSubmissionSummarySchema,
|
||||
} from "./schema";
|
||||
|
||||
describe("Workshop URL configuration", () => {
|
||||
test("normalizes the URL contract and derives Workshop defaults", () => {
|
||||
expect(
|
||||
resolveHomarrUrlConfig({
|
||||
homarrWebsiteUrl: "https://docs.example.com/",
|
||||
workshopApiUrl: "https://api.example.com///",
|
||||
}),
|
||||
).toEqual({
|
||||
homarrWebsiteUrl: "https://docs.example.com",
|
||||
workshopApiUrl: "https://api.example.com",
|
||||
workshopWebUrl: "https://docs.example.com/workshop",
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects unsafe or ambiguous public URLs", () => {
|
||||
expect(() => normalizeHttpUrl("file:///tmp/workshop", "WORKSHOP_API_URL")).toThrow("HTTP or HTTPS");
|
||||
expect(() => normalizeHttpUrl("https://user:secret@example.com", "WORKSHOP_API_URL")).toThrow("credentials");
|
||||
expect(() => normalizeHttpUrl("https://example.com/?token=secret", "WORKSHOP_API_URL")).toThrow("query string");
|
||||
expect(() => normalizeHttpUrl("\nhttps://example.com", "WORKSHOP_API_URL")).toThrow("control characters");
|
||||
});
|
||||
|
||||
test.each([
|
||||
[undefined, "/"],
|
||||
["/", "/"],
|
||||
["/docs", "/docs/"],
|
||||
["/docs/", "/docs/"],
|
||||
])("normalizes DOCS_BASE_URL %s", (input, expected) => {
|
||||
expect(normalizeDocsBaseUrl(input)).toBe(expected);
|
||||
});
|
||||
|
||||
test.each(["docs", "/docs?preview=1", "/../docs", "/%2e%2e/private", "/docs path", String.raw`/docs\private`])(
|
||||
"rejects invalid DOCS_BASE_URL %s",
|
||||
(input) => {
|
||||
expect(() => normalizeDocsBaseUrl(input)).toThrow("DOCS_BASE_URL");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Workshop widget validation", () => {
|
||||
test("accepts a canonical credential-free widget", () => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { customWidgetImportSchema } from "@homarr/custom-widgets/core";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
export const WORKSHOP_API_URL = "https://homarr.dev";
|
||||
export const WORKSHOP_WEB_URL = "https://homarr.dev/workshop";
|
||||
export const HOMARR_WEBSITE_URL = "https://homarr.dev";
|
||||
export const WORKSHOP_API_URL = HOMARR_WEBSITE_URL;
|
||||
export const WORKSHOP_WEB_URL = `${HOMARR_WEBSITE_URL}/workshop`;
|
||||
export const WORKSHOP_CSS_SCHEMA = "homarr-custom-css-v1";
|
||||
export const MAX_WORKSHOP_CSS_LENGTH = 16_384;
|
||||
export const MAX_WORKSHOP_CONTENT_LENGTH = 1_000_000;
|
||||
@@ -11,6 +12,71 @@ export const MAX_WORKSHOP_SCREENSHOT_BYTES = 5 * 1024 * 1024;
|
||||
export const WORKSHOP_REQUEST_TIMEOUT_MS = 8_000;
|
||||
export const WORKSHOP_SCREENSHOT_MIME_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
|
||||
|
||||
export interface HomarrUrlConfig {
|
||||
homarrWebsiteUrl: string;
|
||||
workshopApiUrl: string;
|
||||
workshopWebUrl: string;
|
||||
}
|
||||
|
||||
export interface HomarrUrlConfigInput {
|
||||
homarrWebsiteUrl?: string;
|
||||
workshopApiUrl?: string;
|
||||
workshopWebUrl?: string;
|
||||
}
|
||||
|
||||
export function normalizeHttpUrl(value: string, variableName: string): string {
|
||||
if (value !== value.trim() || hasAsciiControl(value)) {
|
||||
throw new Error(`${variableName} must not include surrounding whitespace or control characters`);
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new Error(`${variableName} must be a valid absolute HTTP(S) URL`);
|
||||
}
|
||||
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new Error(`${variableName} must use HTTP or HTTPS`);
|
||||
}
|
||||
if (url.username || url.password) {
|
||||
throw new Error(`${variableName} must not include credentials`);
|
||||
}
|
||||
if (url.search || url.hash) {
|
||||
throw new Error(`${variableName} must not include a query string or fragment`);
|
||||
}
|
||||
|
||||
return url.toString().replace(/\/+$/u, "");
|
||||
}
|
||||
|
||||
function hasAsciiControl(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return code <= 31 || code === 127;
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveHomarrUrlConfig(input: HomarrUrlConfigInput = {}): HomarrUrlConfig {
|
||||
const homarrWebsiteUrl = normalizeHttpUrl(input.homarrWebsiteUrl ?? HOMARR_WEBSITE_URL, "HOMARR_WEBSITE_URL");
|
||||
const workshopApiUrl = normalizeHttpUrl(input.workshopApiUrl ?? homarrWebsiteUrl, "WORKSHOP_API_URL");
|
||||
const workshopWebUrl = normalizeHttpUrl(input.workshopWebUrl ?? `${homarrWebsiteUrl}/workshop`, "WORKSHOP_WEB_URL");
|
||||
|
||||
return { homarrWebsiteUrl, workshopApiUrl, workshopWebUrl };
|
||||
}
|
||||
|
||||
export function normalizeDocsBaseUrl(value = "/"): string {
|
||||
if (
|
||||
!value.startsWith("/") ||
|
||||
/[^A-Za-z0-9._~/-]/u.test(value) ||
|
||||
value.split("/").some((segment) => segment === "." || segment === "..")
|
||||
) {
|
||||
throw new Error("DOCS_BASE_URL must be a safe path that starts with '/'");
|
||||
}
|
||||
|
||||
const path = value.replace(/^\/+|\/+$/gu, "");
|
||||
return path ? `/${path}/` : "/";
|
||||
}
|
||||
|
||||
export const workshopReportCategorySchema = z.enum(["malicious", "spam", "copyright", "inappropriate", "other"]);
|
||||
export const workshopSubmissionTypeSchema = z.enum(["customWidget", "customCss"]);
|
||||
export type WorkshopSubmissionType = z.infer<typeof workshopSubmissionTypeSchema>;
|
||||
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
declare module "tr46" {
|
||||
interface ToAsciiOptions {
|
||||
checkHyphens?: boolean;
|
||||
checkBidi?: boolean;
|
||||
checkJoiners?: boolean;
|
||||
useSTD3ASCIIRules?: boolean;
|
||||
transitionalProcessing?: boolean;
|
||||
verifyDNSLength?: boolean;
|
||||
ignoreInvalidPunycode?: boolean;
|
||||
}
|
||||
|
||||
export function toASCII(value: string, options?: ToAsciiOptions): string | null;
|
||||
}
|
||||
Reference in new issue
Block a user