diff --git a/apps/web/package.json b/apps/web/package.json index f396bff7a5..1daed6e1fd 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -23,6 +23,7 @@ "@formkit/auto-animate": "^0.9.0", "@legendapp/list": "3.3.3", "@lexical/react": "^0.41.0", + "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.4", "@t3tools/client-runtime": "workspace:*", @@ -33,6 +34,8 @@ "class-variance-authority": "^0.7.1", "effect": "catalog:", "jose": "catalog:", + "jsonc-parser": "3.3.1", + "jszip": "3.10.1", "lexical": "^0.41.0", "lucide-react": "^0.564.0", "react": "19.2.6", diff --git a/apps/web/src/components/settings/ThemeSearchDialog.tsx b/apps/web/src/components/settings/ThemeSearchDialog.tsx new file mode 100644 index 0000000000..e26039b366 --- /dev/null +++ b/apps/web/src/components/settings/ThemeSearchDialog.tsx @@ -0,0 +1,277 @@ +import { CheckCircle2Icon, PlusIcon, SearchIcon, ShieldCheckIcon } from "lucide-react"; +import type { FormEvent } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { + importOpenVsxThemeExtension, + searchOpenVsxThemes, + type OpenVsxThemeExtension, +} from "../../openVsxThemes"; +import { + getCustomThemes, + installCustomTheme, + removeCustomTheme, + type ThemeDefinition, +} from "../../themePalette"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Spinner } from "../ui/spinner"; + +const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, { + notation: "compact", + maximumFractionDigits: 1, +}); +const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"]; + +export function ThemeSearchDialog({ + open, + onOpenChange, + onInstalled, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + onInstalled: (themes: ReadonlyArray) => void; +}) { + const [query, setQuery] = useState(""); + const [results, setResults] = useState | null>(null); + const [error, setError] = useState(null); + const [isSearching, setIsSearching] = useState(false); + const [installingId, setInstallingId] = useState(null); + const requestRef = useRef(null); + + useEffect(() => { + requestRef.current?.abort(); + requestRef.current = null; + if (!open) return; + setQuery(""); + setResults(null); + setError(null); + setIsSearching(false); + setInstallingId(null); + }, [open]); + + const runSearch = useCallback(async (searchText: string) => { + const trimmed = searchText.trim(); + if (!trimmed) return; + requestRef.current?.abort(); + const controller = new AbortController(); + requestRef.current = controller; + setQuery(trimmed); + setIsSearching(true); + setError(null); + setResults(null); + try { + const nextResults = await searchOpenVsxThemes(trimmed, controller.signal); + if (!controller.signal.aborted) setResults(nextResults); + } catch (cause) { + if (!controller.signal.aborted) { + setError(cause instanceof Error ? cause.message : "Open VSX search failed."); + } + } finally { + if (requestRef.current === controller) { + requestRef.current = null; + setIsSearching(false); + } + } + }, []); + + const handleSearch = useCallback( + (event: FormEvent) => { + event.preventDefault(); + void runSearch(query); + }, + [query, runSearch], + ); + + const handleInstall = useCallback( + async (extension: OpenVsxThemeExtension) => { + requestRef.current?.abort(); + const controller = new AbortController(); + requestRef.current = controller; + setInstallingId(extension.id); + setError(null); + try { + const themes = await importOpenVsxThemeExtension(extension, controller.signal); + if (controller.signal.aborted) return; + const existingIds = new Set(getCustomThemes().map((theme) => theme.id)); + const duplicates = themes.filter((theme) => existingIds.has(theme.id)); + if (duplicates.length > 0) { + throw new Error(`${duplicates.map((theme) => theme.label).join(", ")} is already added.`); + } + + const installed: ThemeDefinition[] = []; + try { + for (const theme of themes) installed.push(installCustomTheme(theme)); + } catch (cause) { + for (const theme of installed) { + try { + removeCustomTheme(theme.id); + } catch { + // Best effort rollback. The original storage failure is clearer. + } + } + throw cause; + } + onInstalled(installed); + onOpenChange(false); + } catch (cause) { + if (!controller.signal.aborted) { + setError(cause instanceof Error ? cause.message : "That theme could not be added."); + } + } finally { + if (requestRef.current === controller) { + requestRef.current = null; + setInstallingId(null); + } + } + }, + [onInstalled, onOpenChange], + ); + + return ( + { + if (!nextOpen) requestRef.current?.abort(); + onOpenChange(nextOpen); + }} + > + + + Search themes + + Find community themes from Open VSX and add them in one click. + + + +
+ + setQuery(event.currentTarget.value)} + placeholder="try dracula, nord, catppuccin..." + size="lg" + type="search" + value={query} + /> + + + + {error ? ( +
+ {error} +
+ ) : null} + + {results === null && !isSearching ? ( +
+
+

What theme are you looking for?

+

+ Only themes with a supported open-source license are shown. +

+
+
+ {SUGGESTED_SEARCHES.map((suggestion) => ( + + ))} +
+
+ ) : null} + + {isSearching ? ( +
+ Finding themes... +
+ ) : null} + + {results ? ( + results.length === 0 ? ( +
+

No supported open-source themes found

+

Try a broader search.

+
+ ) : ( +
+ {results.map((extension) => { + const isInstalling = installingId === extension.id; + return ( +
+
+ {extension.iconUrl ? ( + + ) : ( +
+ +
+ )} +
+

{extension.name}

+

+ {extension.publisher} ยท{" "} + {DOWNLOAD_FORMAT.format(extension.downloadCount)} downloads +

+
+
+

+ {extension.description || "A community color theme for your editor."} +

+
+ + {extension.license} + + +
+
+ ); + })} +
+ ) + ) : null} + +
+ Sourced from Open VSX, with license and package + integrity checks +
+
+
+
+ ); +} diff --git a/apps/web/src/components/settings/ThemeSettings.tsx b/apps/web/src/components/settings/ThemeSettings.tsx index 4eb7904508..b8cfee9eda 100644 --- a/apps/web/src/components/settings/ThemeSettings.tsx +++ b/apps/web/src/components/settings/ThemeSettings.tsx @@ -3,6 +3,7 @@ import { DownloadIcon, PenLineIcon, PlusIcon, + SearchIcon, Trash2Icon, UploadIcon, } from "lucide-react"; @@ -35,6 +36,7 @@ import { Button } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; import { ThemeImportDialog } from "./ThemeImportDialog"; +import { ThemeSearchDialog } from "./ThemeSearchDialog"; import { useThemeEditorStore } from "./themeEditorStore"; import { STANDARD_THEME_CARDS, @@ -250,6 +252,7 @@ export function ThemeLibrary({ setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean; }) { const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor); + const [isSearchOpen, setIsSearchOpen] = useState(false); const [themeToRemove, setThemeToRemove] = useState(null); // Keep the last removal target so the dialog title stays populated while the // close animation plays after confirming. @@ -553,9 +556,12 @@ export function ThemeLibrary({ {renderModeTiles()}

Themes

-
+
+
{renderPairGrid()} + { + toastManager.add( + stackedThreadToast({ + type: "success", + title: + installedThemes.length === 1 + ? `${installedThemes[0]!.label} added` + : `${installedThemes.length} themes added`, + description: installedThemes.map((installed) => installed.label).join(", "), + }), + ); + }} + onOpenChange={setIsSearchOpen} + open={isSearchOpen} + /> { // An updated theme that is showing (as the base or either half) diff --git a/apps/web/src/openVsxThemes.test.ts b/apps/web/src/openVsxThemes.test.ts new file mode 100644 index 0000000000..5265ad34ae --- /dev/null +++ b/apps/web/src/openVsxThemes.test.ts @@ -0,0 +1,203 @@ +import { sha256 } from "@noble/hashes/sha2"; +import JSZip from "jszip"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + importOpenVsxThemeExtension, + searchOpenVsxThemes, + type OpenVsxThemeExtension, +} from "./openVsxThemes"; +import { getThemeColorsForMode } from "./themePalette"; + +const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file"; + +function extensionDetail(overrides: Record = {}) { + return { + namespace: "demo", + name: "theme", + displayName: "Demo Theme", + description: "A nice theme", + version: "1.0.0", + downloadCount: 123456, + license: "MIT", + files: { + icon: `${ASSET_ROOT}/icon.png`, + manifest: `${ASSET_ROOT}/package.json`, + sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`, + download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`, + }, + ...overrides, + }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("Open VSX themes", () => { + it("searches theme extensions and keeps only supported open-source licenses", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/-/search?")) { + return new Response( + JSON.stringify({ + extensions: [ + { namespace: "demo", name: "theme" }, + { namespace: "closed", name: "theme" }, + ], + }), + { status: 200 }, + ); + } + if (url.endsWith("/closed/theme")) { + return new Response( + JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })), + { status: 200 }, + ); + } + return new Response(JSON.stringify(extensionDetail()), { status: 200 }); + }); + vi.stubGlobal("fetch", fetchMock); + + const results = await searchOpenVsxThemes(" dracula "); + + expect(results).toEqual([ + expect.objectContaining({ + id: "demo.theme", + name: "Demo Theme", + publisher: "demo", + downloadCount: 123456, + license: "MIT", + }), + ]); + const searchUrl = new URL(String(fetchMock.mock.calls[0]![0])); + expect(searchUrl.searchParams.get("query")).toBe("dracula"); + expect(searchUrl.searchParams.get("category")).toBe("Themes"); + expect(searchUrl.searchParams.get("size")).toBe("16"); + }); + + it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => { + const zip = new JSZip(); + zip.file( + "extension/themes/base.jsonc", + `{ + // inherited workbench colors + "colors": { + "editor.foreground": "#eeeeee", + "focusBorder": "#8b5cf6", + }, + }`, + ); + zip.file( + "extension/themes/demo-dark.json", + `{ + "include": "./base.jsonc", + "colors": { "editor.background": "#111111" } + }`, + ); + zip.file( + "extension/themes/demo-light.json", + `{ + "colors": { + "editor.background": "#fafafa", + "editor.foreground": "#222222", + "focusBorder": "#8b5cf6" + } + }`, + ); + zip.file( + "extension/themes/demo.json", + `{ + "colors": { + "editor.background": "#181818", + "editor.foreground": "#eeeeee" + } + }`, + ); + const packageBytes = await zip.generateAsync({ type: "arraybuffer" }); + const checksum = [...sha256(new Uint8Array(packageBytes))] + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); + const manifest = { + contributes: { + themes: [ + { label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" }, + { label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" }, + { label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" }, + ], + }, + }; + const extension: OpenVsxThemeExtension = { + id: "demo.theme", + name: "Demo Theme", + publisher: "demo", + description: "", + downloadCount: 1, + iconUrl: null, + license: "MIT", + manifestUrl: `${ASSET_ROOT}/package.json`, + sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`, + version: "1.0.0", + vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`, + }; + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request) => { + const url = String(input); + if (url === extension.manifestUrl) { + return new Response(JSON.stringify(manifest), { status: 200 }); + } + if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`); + return new Response(packageBytes, { + status: 200, + headers: { "Content-Length": String(packageBytes.byteLength) }, + }); + }), + ); + + const themes = await importOpenVsxThemeExtension(extension); + + expect(themes).toHaveLength(2); + expect(new Set(themes.map((theme) => theme.id)).size).toBe(2); + const paired = themes.find( + (theme) => + getThemeColorsForMode(theme, "light") !== null && + getThemeColorsForMode(theme, "dark") !== null, + )!; + expect(paired.label).toBe("Demo"); + expect(paired.colors.canvas).toBe("#fafafa"); + expect(getThemeColorsForMode(paired, "dark")!.canvas).toBe("#111111"); + expect(getThemeColorsForMode(paired, "dark")!.text).toBe("#eeeeee"); + }); + + it("rejects a package whose Open VSX checksum does not match", async () => { + const extension: OpenVsxThemeExtension = { + id: "demo.theme", + name: "Demo Theme", + publisher: "demo", + description: "", + downloadCount: 1, + iconUrl: null, + license: "MIT", + manifestUrl: `${ASSET_ROOT}/package.json`, + sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`, + version: "1.0.0", + vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`, + }; + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request) => { + const url = String(input); + if (url === extension.manifestUrl) { + return new Response( + JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }), + ); + } + if (url === extension.sha256Url) return new Response("0".repeat(64)); + return new Response(new Uint8Array([1, 2, 3])); + }), + ); + + await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check"); + }); +}); diff --git a/apps/web/src/openVsxThemes.ts b/apps/web/src/openVsxThemes.ts new file mode 100644 index 0000000000..de3bbe08bf --- /dev/null +++ b/apps/web/src/openVsxThemes.ts @@ -0,0 +1,462 @@ +import { sha256 } from "@noble/hashes/sha2"; +import JSZip from "jszip"; +import { parse, type ParseError } from "jsonc-parser"; + +import type { ThemeDefinition } from "./themePalette"; +import { + isVsCodeThemeFile, + pairVsCodeThemes, + parseVsCodeThemeFile, + resolveThemeLabelCollisions, +} from "./vscodeThemeImport"; + +const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search"; +const MAX_VSIX_BYTES = 20 * 1024 * 1024; +const MAX_SEARCH_BYTES = 512 * 1024; +const MAX_MANIFEST_BYTES = 256 * 1024; +const MAX_THEME_BYTES = 256 * 1024; +const MAX_ZIP_ENTRIES = 2_000; +const MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024; +const MAX_COMPRESSION_RATIO = 200; +const MAX_THEMES_PER_EXTENSION = 40; +const MAX_INCLUDE_DEPTH = 8; +const SUPPORTED_LICENSES = new Set([ + "0BSD", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "CC0-1.0", + "ISC", + "MIT", + "MPL-2.0", + "Unlicense", +]); + +export type OpenVsxThemeExtension = { + id: string; + name: string; + publisher: string; + description: string; + downloadCount: number; + iconUrl: string | null; + manifestUrl: string; + sha256Url: string; + vsixUrl: string; + version: string; + license: string; +}; + +type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown }; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function trustedOpenVsxUrl(value: unknown): string | null { + if (typeof value !== "string") return null; + try { + const url = new URL(value); + return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org" + ? url.toString() + : null; + } catch { + return null; + } +} + +function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null { + if (!isRecord(value) || !isRecord(value.files)) return null; + const namespace = typeof value.namespace === "string" ? value.namespace.trim() : ""; + const extensionName = typeof value.name === "string" ? value.name.trim() : ""; + const displayName = typeof value.displayName === "string" ? value.displayName.trim() : ""; + const version = typeof value.version === "string" ? value.version.trim() : ""; + const license = typeof value.license === "string" ? value.license.trim() : ""; + const manifestUrl = trustedOpenVsxUrl(value.files.manifest); + const sha256Url = trustedOpenVsxUrl(value.files.sha256); + const vsixUrl = trustedOpenVsxUrl(value.files.download); + if ( + !namespace || + !extensionName || + !displayName || + !version || + !SUPPORTED_LICENSES.has(license) || + !manifestUrl || + !sha256Url || + !vsixUrl + ) { + return null; + } + return { + id: `${namespace}.${extensionName}`, + name: displayName, + publisher: namespace, + description: typeof value.description === "string" ? value.description : "", + downloadCount: + typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount) + ? value.downloadCount + : 0, + iconUrl: trustedOpenVsxUrl(value.files.icon), + manifestUrl, + sha256Url, + vsixUrl, + version, + license, + }; +} + +export async function searchOpenVsxThemes( + query: string, + signal?: AbortSignal, +): Promise { + const searchText = query.trim(); + if (!searchText) return []; + const url = new URL(OPEN_VSX_SEARCH_URL); + url.searchParams.set("query", searchText); + url.searchParams.set("category", "Themes"); + // Ask for a few extras because results without a supported SPDX license + // are intentionally omitted. + url.searchParams.set("size", "16"); + const response = await fetch(url, signal ? { signal } : {}); + if (!response.ok) throw new Error("Open VSX search is unavailable right now."); + const searchBytes = await readCappedResponse( + response, + MAX_SEARCH_BYTES, + "Open VSX returned an unexpectedly large response.", + ); + let value: unknown; + try { + value = JSON.parse(new TextDecoder().decode(searchBytes)); + } catch { + throw new Error("Open VSX returned an unreadable response."); + } + const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : []; + const identities = candidates.flatMap((candidate): Array<[string, string]> => { + if (!isRecord(candidate)) return []; + const namespace = typeof candidate.namespace === "string" ? candidate.namespace : ""; + const name = typeof candidate.name === "string" ? candidate.name : ""; + return namespace && name ? [[namespace, name]] : []; + }); + const details = await Promise.allSettled( + identities.slice(0, 16).map(async ([namespace, name]) => { + const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`; + const detailResponse = await fetch(detailUrl, signal ? { signal } : {}); + if (!detailResponse.ok) return null; + return extensionFromDetail(await detailResponse.json()); + }), + ); + if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError"); + return details + .flatMap((result) => (result.status === "fulfilled" && result.value ? [result.value] : [])) + .slice(0, 8); +} + +function parseJsoncObject(source: string, description: string): Record { + const errors: ParseError[] = []; + const value: unknown = parse(source, errors, { allowTrailingComma: true }); + if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`); + return value; +} + +function normalizePackagePath(path: string, relativeTo = "extension/"): string { + if (path.includes("\0") || path.startsWith("/") || /^[a-zA-Z]:/.test(path)) { + throw new Error("Theme path is not a safe relative package path."); + } + const normalizedInput = path.replaceAll("\\", "/"); + const baseSegments = relativeTo.split("/").slice(0, -1); + const segments = baseSegments; + for (const segment of normalizedInput.split("/")) { + if (!segment || segment === ".") continue; + if (segment === "..") { + if (segments.length <= 1) throw new Error("Theme path escapes the extension package."); + segments.pop(); + continue; + } + segments.push(segment); + } + if (segments[0] !== "extension") segments.unshift("extension"); + return segments.join("/"); +} + +function contributionType(uiTheme: unknown): string | null { + if (uiTheme === "vs") return "light"; + if (uiTheme === "vs-dark") return "dark"; + if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme; + return null; +} + +type ZipEntrySizes = { + compressedSize?: unknown; + uncompressedSize?: unknown; +}; + +type InspectableZipObject = JSZip.JSZipObject & { + _data?: ZipEntrySizes; + unsafeOriginalName?: string; + internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper; +}; + +function inspectZipDirectory(bytes: Uint8Array): void { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const minimumOffset = Math.max(0, bytes.byteLength - 65_557); + let endOffset = bytes.byteLength - 22; + while (endOffset >= minimumOffset && view.getUint32(endOffset, true) !== 0x06054b50) { + endOffset -= 1; + } + if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory."); + + const directorySize = view.getUint32(endOffset + 12, true); + const directoryOffset = view.getUint32(endOffset + 16, true); + const directoryEnd = directoryOffset + directorySize; + if (directoryEnd > endOffset || directoryEnd > bytes.byteLength) { + throw new Error("That extension package has an invalid ZIP directory."); + } + + let entryCount = 0; + let offset = directoryOffset; + while (offset < directoryEnd) { + if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) { + throw new Error("That extension package has an invalid ZIP directory."); + } + entryCount += 1; + if (entryCount > MAX_ZIP_ENTRIES) { + throw new Error("That extension package has too many files."); + } + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentLength = view.getUint16(offset + 32, true); + offset += 46 + nameLength + extraLength + commentLength; + } + if (offset !== directoryEnd) + throw new Error("That extension package has an invalid ZIP directory."); +} + +function inspectZip(zip: JSZip): void { + const entries = Object.values(zip.files) as InspectableZipObject[]; + if (entries.length > MAX_ZIP_ENTRIES) + throw new Error("That extension package has too many files."); + + let totalUncompressed = 0; + for (const entry of entries) { + if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName); + if (entry.dir) continue; + const compressed = entry._data?.compressedSize; + const uncompressed = entry._data?.uncompressedSize; + if (typeof compressed !== "number" || typeof uncompressed !== "number") { + throw new Error("That extension package has unreadable file metadata."); + } + totalUncompressed += uncompressed; + if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) { + throw new Error("That extension package expands beyond the safe import limit."); + } + if ( + uncompressed > 0 && + (compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO) + ) { + throw new Error("That extension package has an unsafe compression ratio."); + } + } +} + +async function readZipText(zip: JSZip, path: string, description: string): Promise { + const file = zip.file(path) as InspectableZipObject | null; + if (!file) throw new Error(`${description} is missing from the extension package.`); + if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) { + throw new Error(`${description} has unreadable size metadata.`); + } + if (file._data.uncompressedSize > MAX_THEME_BYTES) { + throw new Error(`${description} is too large.`); + } + + return new Promise((resolve, reject) => { + const chunks: Uint8Array[] = []; + let byteLength = 0; + let settled = false; + const stream = file.internalStream!("uint8array"); + stream + .on("data", (chunk) => { + if (settled) return; + byteLength += chunk.byteLength; + if (byteLength > MAX_THEME_BYTES) { + settled = true; + stream.pause(); + reject(new Error(`${description} is too large.`)); + return; + } + chunks.push(chunk); + }) + .on("error", (cause) => { + if (settled) return; + settled = true; + reject(cause); + }) + .on("end", () => { + if (settled) return; + settled = true; + const bytes = new Uint8Array(byteLength); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + resolve(new TextDecoder().decode(bytes)); + }) + .resume(); + }); +} + +async function loadThemeObject( + zip: JSZip, + path: string, + ancestors: ReadonlySet = new Set(), +): Promise> { + if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply."); + if (ancestors.has(path)) throw new Error("Theme includes contain a cycle."); + const value = parseJsoncObject(await readZipText(zip, path, path), path); + if (typeof value.include !== "string") return value; + + const includePath = normalizePackagePath(value.include, path); + const nextAncestors = new Set(ancestors); + nextAncestors.add(path); + const base = await loadThemeObject(zip, includePath, nextAncestors); + return { + ...base, + ...value, + colors: { + ...(isRecord(base.colors) ? base.colors : {}), + ...(isRecord(value.colors) ? value.colors : {}), + }, + }; +} + +async function readCappedResponse( + response: Response, + limit: number, + tooLargeMessage: string, +): Promise { + const contentLength = response.headers.get("content-length"); + if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage); + if (!response.body) { + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength > limit) throw new Error(tooLargeMessage); + return bytes; + } + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let byteLength = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + byteLength += value.byteLength; + if (byteLength > limit) { + await reader.cancel(); + throw new Error(tooLargeMessage); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + + const result = new Uint8Array(byteLength); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.byteLength; + } + return result; +} + +async function fetchPackage(url: string, signal?: AbortSignal): Promise { + const response = await fetch(url, signal ? { signal } : {}); + if (!response.ok) throw new Error("That Open VSX theme could not be downloaded."); + return readCappedResponse( + response, + MAX_VSIX_BYTES, + "That theme extension is too large to import safely.", + ); +} + +export async function importOpenVsxThemeExtension( + extension: OpenVsxThemeExtension, + signal?: AbortSignal, +): Promise> { + const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {}); + if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest."); + const manifestBytes = await readCappedResponse( + manifestResponse, + MAX_MANIFEST_BYTES, + "That Open VSX extension manifest is too large.", + ); + const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest"); + const contributes = isRecord(manifest.contributes) ? manifest.contributes : null; + const contributions = Array.isArray(contributes?.themes) + ? contributes.themes.filter(isRecord) + : []; + if (contributions.length === 0) throw new Error("That extension does not contain color themes."); + if (contributions.length > MAX_THEMES_PER_EXTENSION) { + throw new Error("That extension contains too many color themes to import safely."); + } + + const packageBytes = await fetchPackage(extension.vsixUrl, signal); + const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {}); + if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum."); + const expectedChecksum = new TextDecoder() + .decode( + await readCappedResponse( + checksumResponse, + 256, + "That Open VSX checksum response is invalid.", + ), + ) + .trim() + .split(/\s+/)[0]; + if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) { + throw new Error("That Open VSX theme has an invalid checksum."); + } + const actualChecksum = [...sha256(packageBytes)] + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); + if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) { + throw new Error("That Open VSX theme failed its integrity check."); + } + let zip: JSZip; + try { + inspectZipDirectory(packageBytes); + zip = await JSZip.loadAsync(packageBytes); + inspectZip(zip); + } catch (cause) { + if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause; + throw new Error("That Open VSX extension package could not be opened.", { cause }); + } + + const parsed: Array<{ theme: ThemeDefinition; sourceName: string }> = []; + const failures: string[] = []; + for (const contribution of contributions as ThemeContribution[]) { + if (typeof contribution.path !== "string") continue; + try { + const path = normalizePackagePath(contribution.path); + const themeValue = await loadThemeObject(zip, path); + const type = contributionType(contribution.uiTheme); + const label = + typeof contribution.label === "string" && contribution.label.trim() + ? contribution.label.trim() + : extension.name; + const decorated = { + ...themeValue, + displayName: label, + ...(type ? { type } : {}), + }; + if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme"); + parsed.push({ theme: parseVsCodeThemeFile(decorated), sourceName: path.split("/").at(-1)! }); + } catch (cause) { + failures.push(cause instanceof Error ? cause.message : "theme could not be read"); + } + } + if (parsed.length === 0) { + throw new Error(failures[0] ?? "That extension has no compatible color themes."); + } + const paired = pairVsCodeThemes(resolveThemeLabelCollisions(parsed)); + return resolveThemeLabelCollisions(paired.map((theme) => ({ theme }))); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9b99999318..6012b42ddc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -542,6 +542,9 @@ importers: '@lexical/react': specifier: ^0.41.0 version: 0.41.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6)(yjs@13.6.31) + '@noble/hashes': + specifier: 'catalog:' + version: 1.8.0 '@pierre/diffs': specifier: 'catalog:' version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/themes@4.3.0)(react-dom@19.2.6(react@19.2.6))(react@19.2.6) @@ -572,6 +575,12 @@ importers: jose: specifier: 'catalog:' version: 6.2.2 + jsonc-parser: + specifier: 3.3.1 + version: 3.3.1 + jszip: + specifier: 3.10.1 + version: 3.10.1 lexical: specifier: ^0.41.0 version: 0.41.0