Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(licenses): surface JPDFium native component licenses in third-party notices (#8477)

brios16e9733f5934
diff --git a/.gitignore b/.gitignore
index d584b11df4..89576e8595 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,6 +46,7 @@ exampleYmlFiles/stirling/
/testing/compose/multinode/.active-topology
/testing/compose/multinode/regression-report/
/.test-state/
+/.test-state-*.exit
SwaggerDoc.json
# Runtime storage for uploaded files and user data (not Java source code)
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/UIDataController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/UIDataController.java
index b6cef0b2d6..ca02c080f1 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/UIDataController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/UIDataController.java
@@ -23,6 +23,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.Dependency;
import stirling.software.SPDF.model.SignatureFile;
import stirling.software.SPDF.service.SharedSignatureService;
+import stirling.software.SPDF.util.NativeLicenseLoader;
import stirling.software.common.annotations.api.UiDataApi;
import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.common.configuration.RuntimePathConfig;
@@ -31,6 +32,7 @@ import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import tools.jackson.core.JacksonException;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
@@ -91,17 +93,36 @@ public class UIDataController {
@Operation(summary = "Get third-party licenses data")
public ResponseEntity<LicensesData> getLicensesData() {
LicensesData data = new LicensesData();
- Resource resource = new ClassPathResource("static/3rdPartyLicenses.json");
-
- try (InputStream is = resource.getInputStream()) {
- Map<String, List<Dependency>> licenseData =
- objectMapper.readValue(
- is, new TypeReference<Map<String, List<Dependency>>>() {});
- data.setDependencies(licenseData.get("dependencies"));
- } catch (IOException e) {
+ List<Dependency> combined = new ArrayList<>();
+ try {
+ Resource resource = new ClassPathResource("static/3rdPartyLicenses.json");
+ try (InputStream is = resource.getInputStream()) {
+ Map<String, List<Dependency>> licenseData =
+ objectMapper.readValue(
+ is, new TypeReference<Map<String, List<Dependency>>>() {});
+ // A report containing JSON null parses without error but yields no map.
+ if (licenseData != null) {
+ List<Dependency> dependencies = licenseData.get("dependencies");
+ if (dependencies != null) {
+ combined.addAll(dependencies);
+ }
+ }
+ }
+ } catch (IOException | JacksonException e) {
+ // Jackson 3 reports malformed JSON with an unchecked JacksonException,
+ // which must not suppress the native notices loaded below.
log.error("Failed to load licenses data", e);
- data.setDependencies(Collections.emptyList());
}
+ try {
+ // Resource discovery follows the thread context loader, which hosted
+ // runtimes and tests both control.
+ combined.addAll(
+ NativeLicenseLoader.loadNativeLicenses(
+ Thread.currentThread().getContextClassLoader()));
+ } catch (RuntimeException e) {
+ log.warn("Unable to load JPDFium native licenses", e);
+ }
+ data.setDependencies(combined);
return ResponseEntity.ok(data);
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/Dependency.java b/app/core/src/main/java/stirling/software/SPDF/model/Dependency.java
index 008a6f5295..2eb6f680eb 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/Dependency.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/Dependency.java
@@ -9,4 +9,5 @@ public class Dependency {
private String moduleVersion;
private String moduleLicense;
private String moduleLicenseUrl;
+ private String moduleLicenseText;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/util/NativeLicenseLoader.java b/app/core/src/main/java/stirling/software/SPDF/util/NativeLicenseLoader.java
new file mode 100644
index 0000000000..adca33736d
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/util/NativeLicenseLoader.java
@@ -0,0 +1,241 @@
+package stirling.software.SPDF.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.SPDF.model.Dependency;
+
+/**
+ * Reads third-party license notices bundled inside dependency jars. JPDFium ships its native
+ * attribution as {@code licenses/NOTICE.txt} plus one full-text file per component inside every
+ * natives jar, so discovery runs off the runtime classpath: whatever natives jars are present
+ * (per-platform selects, future vips jars) contribute their notices with no code change.
+ *
+ * <p>License lines may wrap onto following lines and may name no sibling file at all (multi-license
+ * stacks reference several texts inline); both still produce a notice, the latter without full
+ * text. Deduplication only collapses records that say the same thing: anything that actually
+ * differs (component, license, or text) is preserved, never discarded.
+ */
+@Slf4j
+public final class NativeLicenseLoader {
+
+ public static final String NOTICE_RESOURCE = "licenses/NOTICE.txt";
+
+ private static final Pattern SECTION_HEADER = Pattern.compile("^\\d+\\.\\s+(.+?)\\s*$");
+ private static final Pattern LICENSE_LEAD = Pattern.compile("^-\\s*License:\\s*(.*)$");
+ private static final Pattern COPYRIGHT_LEAD = Pattern.compile("^-\\s*Copyright\\s+(.*)$");
+ private static final Pattern SEE_FILE = Pattern.compile("\\(see\\s+(\\S+?)\\)");
+ private static final Pattern FULL_TEXT_FILE = Pattern.compile("\\(full text in\\s+(\\S+?)\\)");
+
+ private NativeLicenseLoader() {}
+
+ public static List<Dependency> loadNativeLicenses(ClassLoader classLoader) {
+ List<Dependency> merged = new ArrayList<>();
+ Enumeration<URL> notices;
+ try {
+ notices = classLoader.getResources(NOTICE_RESOURCE);
+ } catch (IOException e) {
+ log.warn("Unable to enumerate native license notices", e);
+ return List.of();
+ }
+ while (notices.hasMoreElements()) {
+ URL noticeUrl = notices.nextElement();
+ try {
+ for (Dependency dependency : parseNotice(noticeUrl)) {
+ mergeNotice(merged, dependency);
+ }
+ } catch (Exception e) {
+ log.warn("Skipping unreadable native license notice {}", noticeUrl, e);
+ }
+ }
+ return merged;
+ }
+
+ private static void mergeNotice(List<Dependency> merged, Dependency incoming) {
+ for (int i = 0; i < merged.size(); i++) {
+ Dependency current = merged.get(i);
+ if (!sameNameAndLicense(current, incoming)) {
+ continue;
+ }
+ if (Objects.equals(current.getModuleLicenseText(), incoming.getModuleLicenseText())) {
+ return;
+ }
+ if (current.getModuleLicenseText() == null && incoming.getModuleLicenseText() != null) {
+ merged.set(i, incoming);
+ return;
+ }
+ if (incoming.getModuleLicenseText() == null) {
+ return;
+ }
+ }
+ merged.add(incoming);
+ }
+
+ private static boolean sameNameAndLicense(Dependency left, Dependency right) {
+ return Objects.equals(left.getModuleName(), right.getModuleName())
+ && Objects.equals(left.getModuleLicense(), right.getModuleLicense());
+ }
+
+ private static List<Dependency> parseNotice(URL noticeUrl) throws IOException {
+ List<String> lines;
+ try (InputStream in = noticeUrl.openStream()) {
+ lines = new String(in.readAllBytes(), StandardCharsets.UTF_8).lines().toList();
+ }
+ List<Dependency> dependencies = new ArrayList<>();
+ String name = null;
+ StringBuilder copyright = new StringBuilder();
+ StringBuilder licenseValue = null;
+ boolean inCopyright = false;
+ boolean inTitle = false;
+ for (String raw : lines) {
+ Matcher header = SECTION_HEADER.matcher(raw);
+ if (header.matches()) {
+ flushSection(dependencies, noticeUrl, name, copyright, licenseValue);
+ name = header.group(1).trim();
+ copyright.setLength(0);
+ licenseValue = null;
+ inCopyright = false;
+ inTitle = true;
+ continue;
+ }
+ if (name == null) {
+ continue;
+ }
+ String trimmed = raw.trim();
+ if (trimmed.isEmpty()) {
+ flushSection(dependencies, noticeUrl, name, copyright, licenseValue);
+ name = null;
+ copyright.setLength(0);
+ licenseValue = null;
+ inCopyright = false;
+ inTitle = false;
+ continue;
+ }
+ if (inTitle && !trimmed.startsWith("-")) {
+ // A section title may wrap onto the lines below it; everything up
+ // to the first metadata bullet still names the component.
+ name = name + " " + trimmed;
+ continue;
+ }
+ if (trimmed.startsWith("-")) {
+ inCopyright = false;
+ inTitle = false;
+ Matcher copyrightLead = COPYRIGHT_LEAD.matcher(trimmed);
+ Matcher licenseLead = LICENSE_LEAD.matcher(trimmed);
+ if (copyrightLead.matches()) {
+ if (!copyright.isEmpty()) {
+ copyright.append(' ');
+ }
+ copyright.append(copyrightLead.group(1).trim());
+ inCopyright = true;
+ } else if (licenseLead.matches()) {
+ licenseValue = new StringBuilder(licenseLead.group(1).trim());
+ }
+ continue;
+ }
+ if (licenseValue != null) {
+ licenseValue.append(' ').append(trimmed);
+ } else if (inCopyright) {
+ copyright.append(' ').append(trimmed);
+ }
+ }
+ flushSection(dependencies, noticeUrl, name, copyright, licenseValue);
+ return dependencies;
+ }
+
+ private static void flushSection(
+ List<Dependency> dependencies,
+ URL noticeUrl,
+ String name,
+ StringBuilder copyright,
+ StringBuilder licenseValue) {
+ if (name == null || licenseValue == null) {
+ return;
+ }
+ String value = licenseValue.toString().trim();
+ if (value.isEmpty()) {
+ return;
+ }
+ List<String> licenseFiles = referencedFiles(value);
+ Dependency dependency = new Dependency();
+ dependency.setModuleName(name);
+ dependency.setModuleLicense(stripFileReferences(value));
+ if (!licenseFiles.isEmpty()) {
+ List<String> texts = new ArrayList<>();
+ for (String file : licenseFiles) {
+ String text = readSiblingText(noticeUrl, file);
+ if (text == null) {
+ continue;
+ }
+ // Every referenced file keeps a heading so a multi-text notice
+ // still shows which text came from where.
+ texts.add(licenseFiles.size() > 1 ? "--- " + file + " ---\n" + text : text);
+ }
+ if (!texts.isEmpty()) {
+ String copyrightText = copyright.toString().trim();
+ String combined = String.join("\n\n", texts);
+ // A missing sibling is already reported by readSiblingText; leaving the text
+ // unset keeps the UI from presenting copyright alone as the license.
+ dependency.setModuleLicenseText(
+ copyrightText.isEmpty()
+ ? combined
+ : "Copyright " + copyrightText + "\n\n" + combined);
+ }
+ }
+ dependencies.add(dependency);
+ }
+
+ private static List<String> referencedFiles(String licenseValue) {
+ List<String> files = new ArrayList<>();
+ Matcher see = SEE_FILE.matcher(licenseValue);
+ while (see.find()) {
+ if (!files.contains(see.group(1))) {
+ files.add(see.group(1));
+ }
+ }
+ Matcher fullText = FULL_TEXT_FILE.matcher(licenseValue);
+ while (fullText.find()) {
+ if (!files.contains(fullText.group(1))) {
+ files.add(fullText.group(1));
+ }
+ }
+ return files;
+ }
+
+ private static String stripFileReferences(String licenseValue) {
+ return FULL_TEXT_FILE
+ .matcher(SEE_FILE.matcher(licenseValue).replaceAll(""))
+ .replaceAll("")
+ .trim()
+ .replaceAll("\\s{2,}", " ");
+ }
+
+ // NOTICE files come from any jar on the classpath and the endpoint is unauthenticated,
+ // so only plain sibling filenames may be read. Anything else could escape the notice
+ // directory (../) or switch schemes entirely (file:/C:/) and leak local files.
+ private static String readSiblingText(URL noticeUrl, String licenseFile) {
+ if (!licenseFile.matches("[A-Za-z0-9._+-]+") || licenseFile.startsWith(".")) {
+ log.warn(
+ "Ignoring suspicious native license reference {} beside {}",
+ licenseFile,
+ noticeUrl);
+ return null;
+ }
+ try (InputStream in = new URL(noticeUrl, licenseFile).openStream()) {
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8).strip();
+ } catch (IOException e) {
+ log.warn("Unable to read native license text {} beside {}", licenseFile, noticeUrl, e);
+ return null;
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/UIDataControllerGapTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/UIDataControllerGapTest.java
index df934461f8..0a762ccea7 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/UIDataControllerGapTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/UIDataControllerGapTest.java
@@ -10,6 +10,8 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.net.URL;
+import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -161,6 +163,67 @@ class UIDataControllerGapTest {
// Each parsed dependency should at least carry a module name.
assertNotNull(deps.get(0).getModuleName());
}
+
+ @Test
+ @DisplayName("native notices still load when the generated report is missing")
+ void nativeNoticesSurviveMissingReport() throws Exception {
+ URL fixture = Path.of("src/test/resources", "vips-sim").toUri().toURL();
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ try (URLClassLoader isolated = new URLClassLoader(new URL[] {fixture}, null)) {
+ Thread.currentThread().setContextClassLoader(isolated);
+ try {
+ ResponseEntity<UIDataController.LicensesData> response =
+ controller(userService).getLicensesData();
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ UIDataController.LicensesData body = response.getBody();
+ assertNotNull(body);
+ // The generated JSON is invisible under the fixture loader,
+ // so only the fixture notice may come back.
+ List<Dependency> deps = body.getDependencies();
+ assertNotNull(deps);
+ assertEquals(1, deps.size());
+ assertEquals("Simulated Vips Native Codec", deps.get(0).getModuleName());
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+ }
+
+ @Test
+ @DisplayName("native notices still load when the generated report is malformed")
+ void nativeNoticesSurviveMalformedReport(@TempDir Path tempDir) throws Exception {
+ Files.createDirectories(tempDir.resolve("static"));
+ // Jackson 3 reports this with an unchecked JacksonException, not an IOException.
+ Files.writeString(tempDir.resolve("static/3rdPartyLicenses.json"), "{invalid json");
+ Path licensesDir = Files.createDirectories(tempDir.resolve("licenses"));
+ Files.writeString(
+ licensesDir.resolve("NOTICE.txt"),
+ "1. Temp Native Codec\n"
+ + " - Copyright (c) 2026 Temp\n"
+ + " - License: Temp License (see TEMP-LICENSE.txt)\n");
+ Files.writeString(licensesDir.resolve("TEMP-LICENSE.txt"), "Temp full text.");
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ try (URLClassLoader isolated =
+ new URLClassLoader(new URL[] {tempDir.toUri().toURL()}, null)) {
+ Thread.currentThread().setContextClassLoader(isolated);
+ try {
+ ResponseEntity<UIDataController.LicensesData> response =
+ controller(userService).getLicensesData();
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ UIDataController.LicensesData body = response.getBody();
+ assertNotNull(body);
+ List<Dependency> deps = body.getDependencies();
+ assertNotNull(deps);
+ assertEquals(1, deps.size());
+ assertEquals("Temp Native Codec", deps.get(0).getModuleName());
+ assertNotNull(deps.get(0).getModuleLicenseText());
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+ }
}
@Nested
diff --git a/app/core/src/test/java/stirling/software/SPDF/util/NativeLicenseLoaderTest.java b/app/core/src/test/java/stirling/software/SPDF/util/NativeLicenseLoaderTest.java
new file mode 100644
index 0000000000..324caef692
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/util/NativeLicenseLoaderTest.java
@@ -0,0 +1,321 @@
+package stirling.software.SPDF.util;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.FileOutputStream;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import stirling.software.SPDF.model.Dependency;
+
+class NativeLicenseLoaderTest {
+
+ private static URLClassLoader isolatedLoader(String... fixtureRoots) throws Exception {
+ URL[] urls = new URL[fixtureRoots.length];
+ for (int i = 0; i < fixtureRoots.length; i++) {
+ urls[i] = Path.of("src/test/resources", fixtureRoots[i]).toUri().toURL();
+ }
+ return new URLClassLoader(urls, null);
+ }
+
+ private static String notice(String name, String licenseLine) {
+ return "1. "
+ + name
+ + "\n - Copyright (c) 2024 Test Contributors.\n - License: "
+ + licenseLine
+ + "\n";
+ }
+
+ private static void writeJar(Path jar, Map<String, String> entries) throws Exception {
+ try (JarOutputStream out = new JarOutputStream(new FileOutputStream(jar.toFile()))) {
+ for (Map.Entry<String, String> entry : entries.entrySet()) {
+ out.putNextEntry(new JarEntry(entry.getKey()));
+ out.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+ }
+ }
+
+ private static List<Dependency> loadFromJars(Path... jars) throws Exception {
+ URL[] urls = new URL[jars.length];
+ for (int i = 0; i < jars.length; i++) {
+ urls[i] = jars[i].toUri().toURL();
+ }
+ try (URLClassLoader both = new URLClassLoader(urls, null)) {
+ return NativeLicenseLoader.loadNativeLicenses(both);
+ }
+ }
+
+ @Test
+ void parsesNoticeSectionsWithWrappedCopyrights() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = isolatedLoader("native-licenses")) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ Map<String, Dependency> byName =
+ dependencies.stream().collect(Collectors.toMap(Dependency::getModuleName, d -> d));
+ assertEquals(5, byName.size());
+
+ Dependency testComponent = byName.get("Test Component");
+ assertNotNull(testComponent);
+ assertEquals("BSD 3-Clause", testComponent.getModuleLicense());
+ assertNull(testComponent.getModuleVersion(), "component versions are unknown");
+ assertTrue(
+ testComponent.getModuleLicenseText().startsWith("Copyright (c) 2016"),
+ "copyright is prepended to the license text");
+ assertTrue(
+ testComponent
+ .getModuleLicenseText()
+ .contains("Redistribution and use in source and binary forms"));
+
+ Dependency wrapped = byName.get("Wrapped Copyright Library");
+ assertNotNull(wrapped);
+ assertTrue(
+ wrapped.getModuleLicenseText()
+ .contains(
+ "Copyright (c) 2015, OpenJPEG, entirely written by the OpenJPEG"
+ + " authors"),
+ "wrapped copyright continuations are joined");
+ }
+
+ @Test
+ void parsesWrappedFileReferencesAndFilelessLicenses() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = isolatedLoader("native-licenses")) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ Map<String, Dependency> byName =
+ dependencies.stream().collect(Collectors.toMap(Dependency::getModuleName, d -> d));
+
+ Dependency wrappedRef = byName.get("Wrapped File Reference Library");
+ assertNotNull(wrappedRef, "a file reference wrapped onto the next line still resolves");
+ assertEquals(
+ "GNU Lesser General Public License v2.1 or later", wrappedRef.getModuleLicense());
+ assertTrue(
+ wrappedRef.getModuleLicenseText().contains("resolved through a"),
+ "the wrapped sibling file is read");
+
+ Dependency stack = byName.get("Multi License Stack");
+ assertNotNull(stack, "a license naming no sibling file still produces a notice");
+ assertTrue(
+ stack.getModuleLicense().contains("Apache-2.0 OR MIT"),
+ "compound expressions are preserved verbatim");
+ assertNull(stack.getModuleLicenseText(), "no sibling file means no text");
+ }
+
+ @Test
+ void discoversNoticesFromAnyJarUsingTheLayout() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = isolatedLoader("vips-sim")) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ assertEquals(1, dependencies.size());
+ assertEquals("Simulated Vips Native Codec", dependencies.get(0).getModuleName());
+ assertEquals(
+ "GNU Lesser General Public License v2.1 or later",
+ dependencies.get(0).getModuleLicense());
+ assertNull(dependencies.get(0).getModuleVersion());
+ assertTrue(
+ dependencies
+ .get(0)
+ .getModuleLicenseText()
+ .contains("Simulated vips native codec license text"));
+ }
+
+ @Test
+ void identicalNoticesInTwoJarsCollapseToOneEntry(@TempDir Path tempDir) throws Exception {
+ Map<String, String> jarContent =
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Dup Codec", "MIT License (see DUP-MIT.txt)"),
+ "licenses/DUP-MIT.txt",
+ "Duplicate codec license text.");
+ Path first = tempDir.resolve("first.jar");
+ Path second = tempDir.resolve("second.jar");
+ writeJar(first, jarContent);
+ writeJar(second, jarContent);
+
+ List<Dependency> dependencies = loadFromJars(first, second);
+
+ assertEquals(1, dependencies.size());
+ assertEquals("Dup Codec", dependencies.get(0).getModuleName());
+ assertTrue(
+ dependencies.get(0).getModuleLicenseText().contains("Duplicate codec"),
+ "sibling text resolves through jar URLs");
+ }
+
+ @Test
+ void sameComponentWithDifferentLicensesIsPreserved(@TempDir Path tempDir) throws Exception {
+ Path first = tempDir.resolve("first.jar");
+ Path second = tempDir.resolve("second.jar");
+ writeJar(
+ first,
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Shared Codec", "MIT License (see SHARED-MIT.txt)"),
+ "licenses/SHARED-MIT.txt",
+ "MIT text."));
+ writeJar(
+ second,
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Shared Codec", "Apache License 2.0 (see SHARED-APACHE.txt)"),
+ "licenses/SHARED-APACHE.txt",
+ "Apache text."));
+
+ List<Dependency> dependencies = loadFromJars(first, second);
+
+ assertEquals(2, dependencies.size());
+ }
+
+ @Test
+ void validTextSurvivesWhenTheFirstJarLacksIt(@TempDir Path tempDir) throws Exception {
+ Path first = tempDir.resolve("first.jar");
+ Path second = tempDir.resolve("second.jar");
+ writeJar(
+ first,
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Partial Codec", "BSD 3-Clause (see PARTIAL-BSD.txt)")));
+ writeJar(
+ second,
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Partial Codec", "BSD 3-Clause (see PARTIAL-BSD.txt)"),
+ "licenses/PARTIAL-BSD.txt",
+ "Partial codec license text."));
+
+ List<Dependency> dependencies = loadFromJars(first, second);
+
+ assertEquals(1, dependencies.size());
+ assertTrue(
+ dependencies.get(0).getModuleLicenseText().contains("Partial codec"),
+ "the complete record wins over the textless one");
+ }
+
+ @Test
+ void jarWithoutNoticeDoesNotBreakOtherJars(@TempDir Path tempDir) throws Exception {
+ Path first = tempDir.resolve("first.jar");
+ Path second = tempDir.resolve("second.jar");
+ writeJar(first, Map.of("licenses/UNRELATED.txt", "no notice here"));
+ writeJar(
+ second,
+ Map.of(
+ "licenses/NOTICE.txt",
+ notice("Lone Codec", "MIT License (see LONE-MIT.txt)"),
+ "licenses/LONE-MIT.txt",
+ "Lone codec license text."));
+
+ List<Dependency> dependencies = loadFromJars(first, second);
+
+ assertEquals(1, dependencies.size());
+ assertEquals("Lone Codec", dependencies.get(0).getModuleName());
+ }
+
+ @Test
+ void parsesWrappedTitlesAndMultiFileNotices() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = isolatedLoader("notice-edge")) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ Map<String, Dependency> byName =
+ dependencies.stream().collect(Collectors.toMap(Dependency::getModuleName, d -> d));
+ assertEquals(2, byName.size());
+
+ Dependency magick = byName.get("ImageMagick / MagickCore");
+ assertNotNull(magick, "a title wrapped onto the next line is joined");
+ assertEquals("ImageMagick License", magick.getModuleLicense());
+ assertTrue(magick.getModuleLicenseText().contains("ImageMagick license text."));
+
+ Dependency dual = byName.get("Dual Text Codec");
+ assertNotNull(dual);
+ String text = dual.getModuleLicenseText();
+ assertNotNull(text);
+ assertTrue(text.contains("--- DUAL-BSD.txt ---"), "each file keeps a heading");
+ assertTrue(text.contains("Dual BSD text."));
+ assertTrue(text.contains("--- DUAL-PATENT.txt ---"));
+ assertTrue(text.contains("Dual patent text."));
+ assertEquals("BSD 3-Clause plus patent grant", dual.getModuleLicense());
+ }
+
+ @Test
+ void noNoticeOnTheClasspathReturnsEmptyList() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = new URLClassLoader(new URL[0], null)) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ assertTrue(dependencies.isEmpty());
+ }
+
+ @Test
+ void malformedNoticeReturnsEmptyList() throws Exception {
+ List<Dependency> dependencies;
+ try (URLClassLoader loader = isolatedLoader("malformed")) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ assertTrue(dependencies.isEmpty());
+ }
+
+ @Test
+ void hostileFileReferencesAreNeverRead(@TempDir Path tempDir) throws Exception {
+ Path licensesDir = Files.createDirectories(tempDir.resolve("licenses"));
+ Files.writeString(
+ licensesDir.resolve("NOTICE.txt"),
+ "1. Crafty Codec\n"
+ + " - Copyright (c) 2024 Someone\n"
+ + " - License: BSD 3-Clause (see ../evil.txt)\n"
+ + "2. Craftier Codec\n"
+ + " - Copyright (c) 2024 Someone Else\n"
+ + " - License: MIT License (see file:/etc/passwd)\n");
+ Files.writeString(tempDir.resolve("evil.txt"), "you should never read this");
+ List<Dependency> dependencies;
+ try (URLClassLoader loader =
+ new URLClassLoader(new URL[] {tempDir.toUri().toURL()}, null)) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ assertEquals(2, dependencies.size());
+ for (Dependency dependency : dependencies) {
+ assertNull(
+ dependency.getModuleLicenseText(),
+ "traversal and scheme references must not be resolved");
+ }
+ }
+
+ @Test
+ void missingSiblingLicenseTextLeavesTextUnset(@TempDir Path tempDir) throws Exception {
+ Path licensesDir = Files.createDirectories(tempDir.resolve("licenses"));
+ Files.writeString(
+ licensesDir.resolve("NOTICE.txt"),
+ "1. Component Without Text\n"
+ + " - Copyright (c) 2024 Someone\n"
+ + " - License: BSD 3-Clause (see MISSING-FILE.txt)\n");
+ List<Dependency> dependencies;
+ try (URLClassLoader loader =
+ new URLClassLoader(new URL[] {tempDir.toUri().toURL()}, null)) {
+ dependencies = NativeLicenseLoader.loadNativeLicenses(loader);
+ }
+
+ assertEquals(1, dependencies.size());
+ assertNull(
+ dependencies.get(0).getModuleLicenseText(),
+ "copyright alone must not stand in for the license text");
+ }
+}
diff --git a/app/core/src/test/resources/malformed/licenses/NOTICE.txt b/app/core/src/test/resources/malformed/licenses/NOTICE.txt
new file mode 100644
index 0000000000..226e0d98b5
--- /dev/null
+++ b/app/core/src/test/resources/malformed/licenses/NOTICE.txt
@@ -0,0 +1 @@
+This file is not a license notice, just malformed content for parser tests.
diff --git a/app/core/src/test/resources/native-licenses/licenses/NOTICE.txt b/app/core/src/test/resources/native-licenses/licenses/NOTICE.txt
new file mode 100644
index 0000000000..ab7c4d05f5
--- /dev/null
+++ b/app/core/src/test/resources/native-licenses/licenses/NOTICE.txt
@@ -0,0 +1,22 @@
+1. Test Component
+ - Copyright (c) 2016, Test Component Contributors. All rights reserved.
+ - License: BSD 3-Clause (see TEST-COMPONENT-BSD-3.txt)
+
+2. Wrapped Copyright Library
+ - Copyright (c) 2015, OpenJPEG, entirely written by
+ the OpenJPEG authors under a permissive license.
+ - License: BSD 2-Clause (see WRAPPED-BSD-2.txt)
+
+3. Vips Style Image Library
+ - Copyright (c) 2010, Vips Style Contributors.
+ - License: GNU Lesser General Public License v2.1 or later (see VIPS-STYLE-LGPL-2.1.txt)
+
+4. Wrapped File Reference Library
+ - Copyright (c) 2020, Wrapped Ref Contributors.
+ - License: GNU Lesser General Public License v2.1 or later
+ (see WRAPPED-REF-LGPL-2.1.txt)
+
+5. Multi License Stack
+ - Copyright (c) 2021, Stack Contributors.
+ - License: Apache-2.0 OR MIT (stack crates),
+ BSD-3-Clause (tiny parts). Texts live beside the notice.
diff --git a/app/core/src/test/resources/native-licenses/licenses/TEST-COMPONENT-BSD-3.txt b/app/core/src/test/resources/native-licenses/licenses/TEST-COMPONENT-BSD-3.txt
new file mode 100644
index 0000000000..9113fc1d4f
--- /dev/null
+++ b/app/core/src/test/resources/native-licenses/licenses/TEST-COMPONENT-BSD-3.txt
@@ -0,0 +1,4 @@
+BSD 3-Clause fixture license text for Test Component.
+
+Redistribution and use in source and binary forms are permitted
+provided that the above copyright notice is retained.
diff --git a/app/core/src/test/resources/native-licenses/licenses/VIPS-STYLE-LGPL-2.1.txt b/app/core/src/test/resources/native-licenses/licenses/VIPS-STYLE-LGPL-2.1.txt
new file mode 100644
index 0000000000..6bf85c9fe3
--- /dev/null
+++ b/app/core/src/test/resources/native-licenses/licenses/VIPS-STYLE-LGPL-2.1.txt
@@ -0,0 +1 @@
+LGPL 2.1 fixture license text for Vips Style Image Library.
diff --git a/app/core/src/test/resources/native-licenses/licenses/WRAPPED-BSD-2.txt b/app/core/src/test/resources/native-licenses/licenses/WRAPPED-BSD-2.txt
new file mode 100644
index 0000000000..34453a8ec4
--- /dev/null
+++ b/app/core/src/test/resources/native-licenses/licenses/WRAPPED-BSD-2.txt
@@ -0,0 +1 @@
+BSD 2-Clause fixture license text for Wrapped Copyright Library.
diff --git a/app/core/src/test/resources/native-licenses/licenses/WRAPPED-REF-LGPL-2.1.txt b/app/core/src/test/resources/native-licenses/licenses/WRAPPED-REF-LGPL-2.1.txt
new file mode 100644
index 0000000000..0ad5d6ac86
--- /dev/null
+++ b/app/core/src/test/resources/native-licenses/licenses/WRAPPED-REF-LGPL-2.1.txt
@@ -0,0 +1,2 @@
+Wrapped file reference library license text, resolved through a
+file reference wrapped onto the next notice line.
diff --git a/app/core/src/test/resources/notice-edge/licenses/DUAL-BSD.txt b/app/core/src/test/resources/notice-edge/licenses/DUAL-BSD.txt
new file mode 100644
index 0000000000..9107b3f5fb
--- /dev/null
+++ b/app/core/src/test/resources/notice-edge/licenses/DUAL-BSD.txt
@@ -0,0 +1 @@
+Dual BSD text.
diff --git a/app/core/src/test/resources/notice-edge/licenses/DUAL-PATENT.txt b/app/core/src/test/resources/notice-edge/licenses/DUAL-PATENT.txt
new file mode 100644
index 0000000000..1640fd61b2
--- /dev/null
+++ b/app/core/src/test/resources/notice-edge/licenses/DUAL-PATENT.txt
@@ -0,0 +1 @@
+Dual patent text.
diff --git a/app/core/src/test/resources/notice-edge/licenses/IMAGEMAGICK-LICENSE.txt b/app/core/src/test/resources/notice-edge/licenses/IMAGEMAGICK-LICENSE.txt
new file mode 100644
index 0000000000..7ee2407753
--- /dev/null
+++ b/app/core/src/test/resources/notice-edge/licenses/IMAGEMAGICK-LICENSE.txt
@@ -0,0 +1 @@
+ImageMagick license text.
diff --git a/app/core/src/test/resources/notice-edge/licenses/NOTICE.txt b/app/core/src/test/resources/notice-edge/licenses/NOTICE.txt
new file mode 100644
index 0000000000..d680169548
--- /dev/null
+++ b/app/core/src/test/resources/notice-edge/licenses/NOTICE.txt
@@ -0,0 +1,8 @@
+1. ImageMagick /
+ MagickCore
+ - Copyright (c) 1999 ImageMagick Studio LLC
+ - License: ImageMagick License (see IMAGEMAGICK-LICENSE.txt)
+
+2. Dual Text Codec
+ - Copyright (c) 2022 Dual Contributors
+ - License: BSD 3-Clause (see DUAL-BSD.txt) plus patent grant (full text in DUAL-PATENT.txt)
diff --git a/app/core/src/test/resources/vips-sim/licenses/NOTICE.txt b/app/core/src/test/resources/vips-sim/licenses/NOTICE.txt
new file mode 100644
index 0000000000..536ff6a0c9
--- /dev/null
+++ b/app/core/src/test/resources/vips-sim/licenses/NOTICE.txt
@@ -0,0 +1,3 @@
+1. Simulated Vips Native Codec
+ - Copyright (c) 2024, Simulated Vips Contributors.
+ - License: GNU Lesser General Public License v2.1 or later (see SIM-VIPS-LGPL-2.1.txt)
diff --git a/app/core/src/test/resources/vips-sim/licenses/SIM-VIPS-LGPL-2.1.txt b/app/core/src/test/resources/vips-sim/licenses/SIM-VIPS-LGPL-2.1.txt
new file mode 100644
index 0000000000..70e745c41a
--- /dev/null
+++ b/app/core/src/test/resources/vips-sim/licenses/SIM-VIPS-LGPL-2.1.txt
@@ -0,0 +1 @@
+Simulated vips native codec license text.
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index e6d7885739..537d9f5c8e 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -12367,15 +12367,24 @@ title = "Legal Documents"
backendDescription = "Licenses for backend dependencies bundled with this server."
backendLabel = "Backend Licenses"
backendTitle = "Backend 3rd Party Licenses"
+clearSearch = "Clear search"
empty = "No dependencies found."
frontendDescription = "Licenses for frontend dependencies bundled into the release build."
frontendLabel = "Frontend Licenses"
frontendTitle = "Frontend 3rd Party Licenses"
license = "License"
+licenseAbout = "About"
+licenseAboutCompound = "About {{short}}"
+licenseAboutTitle = "About {{short}}"
listDescription = "The list is shown directly in the UI from the release bundle or backend endpoint."
listTitle = "Bundled dependencies"
loadError = "Failed to load third-party licenses"
module = "Module"
+noMatch = "No matching dependencies."
+searchPlaceholder = "Search dependencies"
+showingCount = "{{count}} dependencies"
+showingCount_one = "{{count}} dependency"
+showingCount_other = "{{count}} dependencies"
version = "Version"
[settings.licensingAnalytics]
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.test.tsx b/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.test.tsx
new file mode 100644
index 0000000000..cfa851e6b4
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.test.tsx
@@ -0,0 +1,138 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { FrontendThirdPartyLicensesSection } from "@editor/components/shared/config/configSections/ThirdPartyLicensesSection";
+import {
+ dedupeDependencies,
+ resolveLicenseDisplay,
+} from "@editor/components/shared/config/configSections/licenseDisplay";
+import frontendLicenses from "../../../../../../assets/3rdPartyLicenses.json"; // oxlint-disable-line no-restricted-imports -- row expectations must follow the generated asset
+
+const expectedRows = dedupeDependencies(
+ (frontendLicenses as { dependencies?: [] }).dependencies ?? [],
+);
+
+const viewport = vi.hoisted(() => ({ phone: false }));
+
+vi.mock("@editor/hooks/useIsMobile", () => ({
+ useIsPhone: () => viewport.phone,
+}));
+
+vi.mock("@editor/services/apiClient", () => ({
+ default: { get: vi.fn() },
+}));
+
+// jsdom reports no scroll geometry, so the real virtualizer renders nothing.
+// Returning every item keeps the layout branch under test fully mounted.
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: (options: {
+ count: number;
+ getItemKey: (i: number) => string;
+ }) => {
+ const items = Array.from({ length: options.count }, (_, index) => ({
+ index,
+ start: index,
+ end: index + 1,
+ size: 1,
+ key: options.getItemKey(index),
+ }));
+ return {
+ getVirtualItems: () => items,
+ getTotalSize: () => options.count,
+ measureElement: () => {},
+ };
+ },
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) =>
+ typeof fallback === "string" ? fallback : key,
+ }),
+}));
+
+function renderSection() {
+ return render(
+ <MantineProvider>
+ <FrontendThirdPartyLicensesSection />
+ </MantineProvider>,
+ );
+}
+
+function requireFirstRow() {
+ const row = expectedRows[0];
+ if (!row) {
+ throw new Error("3rdPartyLicenses.json has no rows");
+ }
+ return row;
+}
+
+describe("third-party licenses layout", () => {
+ it("renders the three-column table on wide viewports", () => {
+ viewport.phone = false;
+ const { container } = renderSection();
+
+ expect(screen.getByRole("table")).toBeTruthy();
+ expect(screen.getByRole("columnheader", { name: "Module" })).toBeTruthy();
+ expect(screen.getByRole("columnheader", { name: "Version" })).toBeTruthy();
+ expect(screen.getByRole("columnheader", { name: "License" })).toBeTruthy();
+ expect(
+ container.querySelectorAll("tbody tr[data-index]").length,
+ ).toBeGreaterThan(0);
+ });
+
+ it("drops the table for a card list on phones", () => {
+ viewport.phone = true;
+ const { container } = renderSection();
+
+ expect(screen.queryByRole("table")).toBeNull();
+ expect(screen.getByPlaceholderText("Search dependencies")).toBeTruthy();
+ const cards = container.querySelectorAll("div[data-index]");
+ // Expected rows follow the generated asset, so a dependency change cannot
+ // fail this test without any code change.
+ expect(cards.length).toBe(expectedRows.length);
+ // Each card carries the module, its version and the resolved license label.
+ const first = requireFirstRow();
+ expect(cards[0].textContent).toContain(first.moduleName);
+ expect(cards[0].textContent).toContain(first.moduleVersion);
+ expect(cards[0].textContent).toContain(
+ resolveLicenseDisplay(first.moduleLicense, first.moduleName).short,
+ );
+ });
+
+ it("clears the search from the field when nothing matches", () => {
+ viewport.phone = false;
+ renderSection();
+
+ const search = screen.getByPlaceholderText(
+ "Search dependencies",
+ ) as HTMLInputElement;
+ expect(screen.queryByRole("button", { name: "Clear search" })).toBeNull();
+
+ fireEvent.change(search, { target: { value: "zzz-no-such-dependency" } });
+
+ expect(screen.getByText("No matching dependencies.")).toBeTruthy();
+ const clear = screen.getByRole("button", { name: "Clear search" });
+ // The reset lives in the field, not as a button under the empty state.
+ expect(search.parentElement?.contains(clear)).toBe(true);
+
+ fireEvent.click(clear);
+
+ expect(search.value).toBe("");
+ expect(screen.queryByText("No matching dependencies.")).toBeNull();
+ });
+
+ it("widens and wraps the version column instead of clipping it", () => {
+ viewport.phone = false;
+ const { container } = renderSection();
+
+ const versionHeader = screen.getByRole("columnheader", { name: "Version" });
+ expect(versionHeader.style.width).toBe("20%");
+ const versionCell = container.querySelector(
+ "tbody tr[data-index] td:nth-child(2)",
+ );
+ expect(versionCell?.firstElementChild?.getAttribute("style")).toContain(
+ "overflow-wrap: anywhere",
+ );
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx b/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx
index a5211a1545..c31e9f86d7 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx
+++ b/frontend/src/editor/core/components/shared/config/configSections/ThirdPartyLicensesSection.tsx
@@ -1,25 +1,47 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Alert,
Anchor,
+ Box,
Group,
Loader,
+ Modal,
Paper,
+ ScrollArea,
Stack,
Table,
Text,
+ TextInput,
} from "@mantine/core";
+import { useVirtualizer } from "@tanstack/react-virtual";
import { isAxiosError } from "axios";
+import { ActionIcon } from "@editor/ui/ActionIcon";
+import { Icon } from "@editor/ui/Icon";
+import { useIsPhone } from "@editor/hooks/useIsMobile";
import apiClient from "@editor/services/apiClient";
import frontendLicenses from "../../../../../../assets/3rdPartyLicenses.json"; // oxlint-disable-line no-restricted-imports -- asset lives outside @editor alias root
+import {
+ dedupeDependencies,
+ matchesLicenseQuery,
+ resolveAboutLinks,
+ resolveLicenseDisplay,
+ resolveModuleLicenseUrl,
+ resolveModuleUrl,
+} from "@editor/components/shared/config/configSections/licenseDisplay";
+import type {
+ DependencyRow,
+ LicenseAboutLink,
+} from "@editor/components/shared/config/configSections/licenseDisplay";
-interface Dependency {
+export interface Dependency {
moduleName?: string;
moduleUrl?: string;
moduleVersion?: string;
moduleLicense?: string;
moduleLicenseUrl?: string;
+ /** Full license text the backend parsed from a bundled notice file. Present on native-component entries; generated-report entries carry moduleLicenseUrl instead. */
+ moduleLicenseText?: string;
}
interface LicensesResponse {
@@ -30,29 +52,52 @@ interface LicensesSectionBodyProps {
dependencies: Dependency[];
}
-const getModuleUrl = (dependency: Dependency) =>
- dependency.moduleUrl || dependency.moduleLicenseUrl;
-
function LicensesSectionBody({ dependencies }: LicensesSectionBodyProps) {
const { t } = useTranslation();
+ const isPhone = useIsPhone();
const sortedDependencies = useMemo(
- () =>
- [...dependencies].sort((a, b) =>
- (a.moduleName || "").localeCompare(b.moduleName || ""),
- ),
+ () => dedupeDependencies(dependencies),
[dependencies],
);
- const getDependencyKey = (dependency: Dependency) =>
- [
- dependency.moduleName ?? "module",
- dependency.moduleVersion ?? "version",
- dependency.moduleUrl ?? "url",
- ].join(":");
+ const [selected, setSelected] = useState<DependencyRow | null>(null);
+
+ const [query, setQuery] = useState("");
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const filteredDependencies = useMemo(() => {
+ const needle = query.trim().toLowerCase();
+ if (!needle) {
+ return sortedDependencies;
+ }
+ return sortedDependencies.filter((dependency) =>
+ matchesLicenseQuery(dependency, needle),
+ );
+ }, [sortedDependencies, query]);
+
+ // Native notices add dozens of rows per jar, so only mount the visible slice.
+ const virtualizer = useVirtualizer<HTMLDivElement, HTMLElement>({
+ count: filteredDependencies.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => 56,
+ overscan: 8,
+ // Ordinal row IDs stay valid however filtering reshuffles indexes.
+ getItemKey: (index) =>
+ filteredDependencies[index]?.rowId ?? `license-index-${index}`,
+ });
+ const virtualItems = virtualizer.getVirtualItems();
+ const topPad = virtualItems[0]?.start ?? 0;
+ const bottomPad =
+ virtualizer.getTotalSize() - (virtualItems.at(-1)?.end ?? 0);
+
+ const emptyLabel =
+ dependencies.length === 0
+ ? t("settings.licenses.empty", "No dependencies found.")
+ : t("settings.licenses.noMatch", "No matching dependencies.");
+ const isEmpty = filteredDependencies.length === 0;
return (
<Stack gap="lg">
- <Paper withBorder p="md" radius="md">
+ <Paper withBorder p={isPhone ? "sm" : "md"} radius="md">
<Stack gap="md">
<Group justify="space-between" align="center">
<div>
@@ -65,76 +110,457 @@ function LicensesSectionBody({ dependencies }: LicensesSectionBodyProps) {
"The list is shown directly in the UI from the release bundle or backend endpoint.",
)}
</Text>
+ <Text size="xs" c="dimmed" mt={4}>
+ {t("settings.licenses.showingCount", "{{count}} dependencies", {
+ count: filteredDependencies.length,
+ })}
+ </Text>
</div>
</Group>
+ <TextInput
+ placeholder={t(
+ "settings.licenses.searchPlaceholder",
+ "Search dependencies",
+ )}
+ aria-label={t(
+ "settings.licenses.searchPlaceholder",
+ "Search dependencies",
+ )}
+ value={query}
+ onChange={(event) => setQuery(event.currentTarget.value)}
+ rightSectionPointerEvents="all"
+ rightSection={
+ // A typo otherwise strands the user on an empty list with this
+ // field as the only way back.
+ query.trim().length > 0 ? (
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={t(
+ "settings.licenses.clearSearch",
+ "Clear search",
+ )}
+ onClick={() => setQuery("")}
+ >
+ <Icon name="x" size="1rem" />
+ </ActionIcon>
+ ) : null
+ }
+ />
- <Table
- highlightOnHover
- withRowBorders
- verticalSpacing="sm"
- horizontalSpacing="md"
+ <div
+ ref={scrollRef}
+ style={{
+ // An empty result hugs its message; a populated list keeps the
+ // fixed scroll height. A phone card is taller than a table row,
+ // so the phone list uses a viewport-relative height instead.
+ height: isEmpty ? "auto" : isPhone ? "min(560px, 62vh)" : 480,
+ overflowY: "auto",
+ overflowX: "auto",
+ }}
>
- <Table.Thead>
- <Table.Tr>
- <Table.Th>{t("settings.licenses.module", "Module")}</Table.Th>
- <Table.Th>{t("settings.licenses.version", "Version")}</Table.Th>
- <Table.Th>{t("settings.licenses.license", "License")}</Table.Th>
- </Table.Tr>
- </Table.Thead>
- <Table.Tbody>
- {sortedDependencies.length === 0 ? (
- <Table.Tr>
- <Table.Td colSpan={3}>
- <Text ta="center" c="dimmed" py="xl">
- {t("settings.licenses.empty", "No dependencies found.")}
- </Text>
- </Table.Td>
- </Table.Tr>
- ) : (
- sortedDependencies.map((dependency) => (
- <Table.Tr key={getDependencyKey(dependency)}>
- <Table.Td>
- {getModuleUrl(dependency) ? (
- <Anchor
- href={getModuleUrl(dependency)}
- target="_blank"
- rel="noopener noreferrer"
- >
- {dependency.moduleName || "-"}
- </Anchor>
- ) : (
- <Text size="sm">{dependency.moduleName || "-"}</Text>
+ {isPhone ? (
+ <div>
+ {filteredDependencies.length === 0 ? (
+ <Text ta="center" c="dimmed" py="xl">
+ {emptyLabel}
+ </Text>
+ ) : (
+ <>
+ {topPad > 0 && <div style={{ height: topPad }} />}
+ {virtualItems.map((virtualRow) => {
+ const dependency = filteredDependencies[virtualRow.index];
+ if (!dependency) {
+ return null;
+ }
+ return (
+ <PhoneLicenseRow
+ key={dependency.rowId}
+ dependency={dependency}
+ index={virtualRow.index}
+ onSelect={setSelected}
+ measureRef={virtualizer.measureElement}
+ />
+ );
+ })}
+ {bottomPad > 0 && <div style={{ height: bottomPad }} />}
+ </>
+ )}
+ </div>
+ ) : (
+ <Table
+ highlightOnHover
+ withRowBorders
+ verticalSpacing="sm"
+ horizontalSpacing="md"
+ stickyHeader
+ // Collapsed borders disable thead stickiness, so the header
+ // scrolls away; separate with zero spacing renders identically.
+ // Fixed layout pins column widths to the header cells, so
+ // filtering and virtualization cannot shift them around.
+ style={{
+ borderCollapse: "separate",
+ borderSpacing: 0,
+ tableLayout: "fixed",
+ }}
+ >
+ <Table.Thead>
+ <Table.Tr>
+ <Table.Th style={{ width: "38%" }}>
+ {t("settings.licenses.module", "Module")}
+ </Table.Th>
+ <Table.Th style={{ width: "20%" }}>
+ {t("settings.licenses.version", "Version")}
+ </Table.Th>
+ <Table.Th style={{ width: "42%" }}>
+ {t("settings.licenses.license", "License")}
+ </Table.Th>
+ </Table.Tr>
+ </Table.Thead>
+ <Table.Tbody>
+ {filteredDependencies.length === 0 ? (
+ <Table.Tr>
+ <Table.Td colSpan={3}>
+ <Text ta="center" c="dimmed" py="xl">
+ {emptyLabel}
+ </Text>
+ </Table.Td>
+ </Table.Tr>
+ ) : (
+ <>
+ {topPad > 0 && (
+ <Table.Tr key="spacer-top">
+ <Table.Td
+ colSpan={3}
+ style={{ height: topPad, padding: 0, border: 0 }}
+ />
+ </Table.Tr>
)}
- </Table.Td>
- <Table.Td>
- <Text size="sm" c="dimmed">
- {dependency.moduleVersion || "-"}
- </Text>
- </Table.Td>
- <Table.Td>
- {dependency.moduleLicenseUrl ? (
- <Anchor
- href={dependency.moduleLicenseUrl}
- target="_blank"
- rel="noopener noreferrer"
- >
- {dependency.moduleLicense || "-"}
- </Anchor>
- ) : (
- <Text size="sm">{dependency.moduleLicense || "-"}</Text>
+ {virtualItems.map((virtualRow) => {
+ const dependency =
+ filteredDependencies[virtualRow.index];
+ if (!dependency) {
+ return null;
+ }
+ return (
+ <VirtualLicenseRow
+ key={dependency.rowId}
+ dependency={dependency}
+ index={virtualRow.index}
+ onSelect={setSelected}
+ measureRef={virtualizer.measureElement}
+ />
+ );
+ })}
+ {bottomPad > 0 && (
+ <Table.Tr key="spacer-bottom">
+ <Table.Td
+ colSpan={3}
+ style={{ height: bottomPad, padding: 0, border: 0 }}
+ />
+ </Table.Tr>
)}
- </Table.Td>
- </Table.Tr>
- ))
- )}
- </Table.Tbody>
- </Table>
+ </>
+ )}
+ </Table.Tbody>
+ </Table>
+ )}
+ </div>
+ <LicenseModal
+ dependency={selected}
+ onClose={() => setSelected(null)}
+ />
</Stack>
</Paper>
</Stack>
);
}
+const SPDX_LICENSE_PAGE = "https://spdx.org/licenses";
+
+function AboutLink({
+ spdxId,
+ short,
+ text,
+}: {
+ spdxId: string;
+ short: string;
+ text?: string;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Anchor
+ href={`${SPDX_LICENSE_PAGE}/${spdxId}.html`}
+ target="_blank"
+ rel="noopener noreferrer"
+ size="xs"
+ c="dimmed"
+ title={t("settings.licenses.licenseAboutTitle", "About {{short}}", {
+ short,
+ })}
+ >
+ {text ?? t("settings.licenses.licenseAbout", "About")}
+ </Anchor>
+ );
+}
+
+// A dual-licensed row keeps its full label and gets one explainer link per
+// known part, so neither alternative hides behind the other.
+function AboutLinks({ links }: { links: LicenseAboutLink[] }) {
+ const { t } = useTranslation();
+ if (links.length === 0) {
+ return null;
+ }
+ if (links.length === 1) {
+ return <AboutLink spdxId={links[0].spdxId} short={links[0].short} />;
+ }
+ return (
+ <>
+ {links.map((link, index) => (
+ <span key={link.spdxId}>
+ {index > 0 ? (
+ <Text size="xs" c="dimmed" span>
+ {" - "}
+ </Text>
+ ) : null}
+ <AboutLink
+ spdxId={link.spdxId}
+ short={link.short}
+ text={t(
+ "settings.licenses.licenseAboutCompound",
+ "About {{short}}",
+ { short: link.short },
+ )}
+ />
+ </span>
+ ))}
+ </>
+ );
+}
+
+function LicenseCell({
+ dependency,
+ onSelect,
+ wrap = false,
+}: {
+ dependency: DependencyRow;
+ onSelect: (dependency: DependencyRow) => void;
+ wrap?: boolean;
+}) {
+ const full = dependency.moduleLicense || "-";
+ const display = resolveLicenseDisplay(
+ dependency.moduleLicense,
+ dependency.moduleName,
+ );
+ const links = resolveAboutLinks(display);
+ // A phone card has no fixed column to clip against, so the label wraps there
+ // instead of being truncated to 240px like a table cell.
+ const clip = wrap
+ ? {
+ style: {
+ overflowWrap: "anywhere" as const,
+ textAlign: "left" as const,
+ },
+ }
+ : { truncate: "end" as const, maw: 240 };
+ const separator =
+ links.length > 0 ? (
+ <Text size="xs" c="dimmed" span>
+ {" - "}
+ </Text>
+ ) : null;
+ if (dependency.moduleLicenseText) {
+ return (
+ <span>
+ <Anchor
+ component="button"
+ onClick={() => onSelect(dependency)}
+ title={full}
+ {...clip}
+ >
+ {display.short}
+ </Anchor>
+ {separator}
+ <AboutLinks links={links} />
+ </span>
+ );
+ }
+ const licenseHref = resolveModuleLicenseUrl(dependency);
+ return licenseHref ? (
+ <span>
+ <Anchor
+ href={licenseHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={full}
+ {...clip}
+ >
+ {display.short}
+ </Anchor>
+ {separator}
+ <AboutLinks links={links} />
+ </span>
+ ) : (
+ <span>
+ <Text size="sm" title={full} span {...clip}>
+ {display.short}
+ </Text>
+ {separator}
+ <AboutLinks links={links} />
+ </span>
+ );
+}
+
+function VirtualLicenseRow({
+ dependency,
+ index,
+ onSelect,
+ measureRef,
+}: {
+ dependency: DependencyRow;
+ index: number;
+ onSelect: (dependency: DependencyRow) => void;
+ measureRef: (element: HTMLElement | null) => void;
+}) {
+ return (
+ // Measured heights keep the virtualizer honest: table padding and wrapped
+ // license links make real rows taller than the 56px estimate, and without
+ // measuring the position math drifts further with every scrolled row.
+ <Table.Tr ref={measureRef} data-index={index} style={{ height: 56 }}>
+ <Table.Td>
+ {resolveModuleUrl(dependency) ? (
+ <Anchor
+ href={resolveModuleUrl(dependency)}
+ target="_blank"
+ rel="noopener noreferrer"
+ truncate="end"
+ maw="100%"
+ style={{ display: "block" }}
+ title={dependency.moduleName || "-"}
+ >
+ {dependency.moduleName || "-"}
+ </Anchor>
+ ) : (
+ <Text
+ size="sm"
+ truncate="end"
+ maw="100%"
+ style={{ display: "block" }}
+ title={dependency.moduleName || "-"}
+ >
+ {dependency.moduleName || "-"}
+ </Text>
+ )}
+ </Table.Td>
+ <Table.Td>
+ <Text
+ size="sm"
+ c="dimmed"
+ // Rows folding two releases together can carry a long value, and a
+ // version that truncates is unreadable in a way a wrapped one is not.
+ style={{ display: "block", overflowWrap: "anywhere" }}
+ title={dependency.moduleVersion || "-"}
+ >
+ {dependency.moduleVersion || "-"}
+ </Text>
+ </Table.Td>
+ <Table.Td>
+ <LicenseCell dependency={dependency} onSelect={onSelect} />
+ </Table.Td>
+ </Table.Tr>
+ );
+}
+
+// Narrow viewports get a card per dependency instead of the three-column
+// table: at phone widths the fixed 15% version column truncates to nothing and
+// the module and license labels collide.
+function PhoneLicenseRow({
+ dependency,
+ index,
+ onSelect,
+ measureRef,
+}: {
+ dependency: DependencyRow;
+ index: number;
+ onSelect: (dependency: DependencyRow) => void;
+ measureRef: (element: HTMLElement | null) => void;
+}) {
+ const moduleUrl = resolveModuleUrl(dependency);
+ return (
+ // The gap lives inside the measured element: the virtualizer stacks items
+ // edge to edge, so an outer margin would desync the offsets.
+ <div ref={measureRef} data-index={index} style={{ paddingBottom: 8 }}>
+ <Paper withBorder radius="sm" p="sm">
+ {moduleUrl ? (
+ <Anchor
+ href={moduleUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ fw={600}
+ size="sm"
+ title={dependency.moduleName || "-"}
+ style={{ display: "block", overflowWrap: "anywhere" }}
+ >
+ {dependency.moduleName || "-"}
+ </Anchor>
+ ) : (
+ <Text
+ fw={600}
+ size="sm"
+ title={dependency.moduleName || "-"}
+ style={{ overflowWrap: "anywhere" }}
+ >
+ {dependency.moduleName || "-"}
+ </Text>
+ )}
+ <Text size="xs" c="dimmed">
+ {dependency.moduleVersion || "-"}
+ </Text>
+ <Box mt={4}>
+ <LicenseCell dependency={dependency} onSelect={onSelect} wrap />
+ </Box>
+ </Paper>
+ </div>
+ );
+}
+
+function LicenseModal({
+ dependency,
+ onClose,
+}: {
+ dependency: DependencyRow | null;
+ onClose: () => void;
+}) {
+ const selectedDisplay = dependency
+ ? resolveLicenseDisplay(dependency.moduleLicense, dependency.moduleName)
+ : null;
+ const selectedLinks = selectedDisplay
+ ? resolveAboutLinks(selectedDisplay)
+ : [];
+ return (
+ <Modal
+ opened={dependency !== null}
+ onClose={onClose}
+ title={dependency?.moduleName || "-"}
+ size="lg"
+ >
+ <ScrollArea.Autosize mah="min(420px, 70vh)">
+ <Text size="sm" c="dimmed">
+ {dependency?.moduleLicense || "-"}
+ </Text>
+ <Text size="sm" mt="xs" style={{ whiteSpace: "pre-wrap" }}>
+ {dependency?.moduleLicenseText}
+ </Text>
+ {selectedLinks.length > 0 ? (
+ <div style={{ marginTop: 8 }}>
+ <AboutLinks links={selectedLinks} />
+ </div>
+ ) : null}
+ </ScrollArea.Autosize>
+ </Modal>
+ );
+}
+
export function BackendThirdPartyLicensesSection() {
const { t } = useTranslation();
const [dependencies, setDependencies] = useState<Dependency[]>([]);
diff --git a/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.test.ts b/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.test.ts
new file mode 100644
index 0000000000..65a7f08749
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.test.ts
@@ -0,0 +1,280 @@
+import { describe, expect, it } from "vitest";
+import {
+ dedupeDependencies,
+ matchesLicenseQuery,
+ resolveAboutLinks,
+ resolveLicenseDisplay,
+ resolveModuleLicenseUrl,
+ resolveModuleUrl,
+} from "@editor/components/shared/config/configSections/licenseDisplay";
+import type { Dependency } from "@editor/components/shared/config/configSections/ThirdPartyLicensesSection";
+
+function dependency(
+ moduleName: string,
+ moduleLicense?: string,
+ moduleLicenseText?: string,
+): Dependency {
+ return { moduleName, moduleLicense, moduleLicenseText };
+}
+
+describe("resolveLicenseDisplay", () => {
+ it("keeps compound labels intact and links only fully-known OR/AND parts", () => {
+ expect(resolveLicenseDisplay("Apache-2.0 OR MIT")).toEqual({
+ short: "Apache-2.0 OR MIT",
+ spdxIds: ["Apache-2.0", "MIT"],
+ });
+ expect(resolveLicenseDisplay("MIT AND Apache-2.0")).toEqual({
+ short: "MIT AND Apache-2.0",
+ spdxIds: ["MIT", "Apache-2.0"],
+ });
+ expect(resolveLicenseDisplay("MIT OR Some Unknown License")).toEqual({
+ short: "MIT OR Some Unknown License",
+ });
+ expect(resolveLicenseDisplay("Apache-2.0 WITH LLVM-exception")).toEqual({
+ short: "Apache-2.0 WITH LLVM-exception",
+ });
+ expect(resolveLicenseDisplay("(Apache-2.0 AND MIT)")).toEqual({
+ short: "(Apache-2.0 AND MIT)",
+ spdxIds: ["Apache-2.0", "MIT"],
+ });
+ });
+
+ it("links bare ISC to its own SPDX page", () => {
+ expect(resolveLicenseDisplay("ISC")).toEqual({
+ short: "ISC",
+ spdxId: "ISC",
+ });
+ });
+
+ it("links the Broadcom Foundation License name to the Apache-2.0 text it ships", () => {
+ expect(resolveLicenseDisplay("Broadcom Foundation License")).toEqual({
+ short: "Broadcom Foundation License",
+ spdxId: "Apache-2.0",
+ });
+ });
+
+ it("derives about links from single and compound displays", () => {
+ expect(resolveAboutLinks(resolveLicenseDisplay("MIT license"))).toEqual([
+ { spdxId: "MIT", short: "MIT" },
+ ]);
+ expect(
+ resolveAboutLinks(resolveLicenseDisplay("MIT OR Apache-2.0")),
+ ).toEqual([
+ { spdxId: "MIT", short: "MIT" },
+ { spdxId: "Apache-2.0", short: "Apache-2.0" },
+ ]);
+ expect(
+ resolveAboutLinks(resolveLicenseDisplay("Some Unknown License")),
+ ).toEqual([]);
+ });
+
+ it("agrees the only/or-later label with its SPDX id", () => {
+ expect(
+ resolveLicenseDisplay("GNU Lesser General Public License v3.0 only"),
+ ).toEqual({ short: "LGPL-3.0", spdxId: "LGPL-3.0-only" });
+ expect(
+ resolveLicenseDisplay("GNU Lesser General Public License v3.0 or later"),
+ ).toEqual({ short: "LGPL-3.0+", spdxId: "LGPL-3.0-or-later" });
+ });
+
+ it("does not map AGPL to GPL or MPL 1.1 to MPL 2.0", () => {
+ expect(
+ resolveLicenseDisplay("GNU Affero General Public License v3.0 only"),
+ ).toEqual({ short: "AGPL-3.0", spdxId: "AGPL-3.0-only" });
+ expect(resolveLicenseDisplay("Mozilla Public License 1.1")).toEqual({
+ short: "MPL-1.1",
+ spdxId: "MPL-1.1",
+ });
+ });
+
+ it("shortens names without an SPDX page but adds no dead link", () => {
+ expect(resolveLicenseDisplay("Bouncy Castle Licence")).toEqual({
+ short: "BouncyCastle",
+ });
+ });
+
+ it("preserves slash-separated licenses verbatim with no SPDX link", () => {
+ expect(resolveLicenseDisplay("MIT/Old MIT License")).toEqual({
+ short: "MIT/Old MIT License",
+ });
+ expect(resolveLicenseDisplay("Unicode License / ICU License")).toEqual({
+ short: "Unicode License / ICU License",
+ });
+ });
+
+ it("maps The BSD License to BSD-3-Clause for TwelveMonkeys modules only", () => {
+ expect(
+ resolveLicenseDisplay(
+ "The BSD License",
+ "com.twelvemonkeys.imageio:imageio-core",
+ ),
+ ).toEqual({ short: "BSD-3-Clause", spdxId: "BSD-3-Clause" });
+ expect(resolveLicenseDisplay("The BSD License")).toEqual({
+ short: "The BSD License",
+ });
+ expect(
+ resolveLicenseDisplay("The BSD License", "com.example:other"),
+ ).toEqual({ short: "The BSD License" });
+ });
+});
+
+describe("resolveModuleLicenseUrl", () => {
+ it("links the jai-imageio license files the report leaves URL-less", () => {
+ expect(
+ resolveModuleLicenseUrl(
+ dependency("com.github.jai-imageio:jai-imageio-core", "LICENSE.txt"),
+ ),
+ ).toBe(
+ "https://github.com/jai-imageio/jai-imageio-core/blob/master/LICENSE.txt",
+ );
+ expect(
+ resolveModuleLicenseUrl(
+ dependency(
+ "com.github.jai-imageio:jai-imageio-jpeg2000",
+ "LICENSE-JJ2000.txt, LICENSE-Sun.txt",
+ ),
+ ),
+ ).toBe("https://github.com/jai-imageio/jai-imageio-jpeg2000/tree/master");
+ });
+
+ it("prefers the report URL when present", () => {
+ expect(
+ resolveModuleLicenseUrl({
+ ...dependency("com.github.jai-imageio:jai-imageio-core"),
+ moduleLicenseUrl: "https://example.com/license",
+ }),
+ ).toBe("https://example.com/license");
+ });
+});
+
+describe("resolveModuleUrl", () => {
+ it("links native components to their homepages", () => {
+ expect(
+ resolveModuleUrl(
+ dependency("ICU (International Components for Unicode)"),
+ ),
+ ).toBe("https://icu.unicode.org/");
+ expect(resolveModuleUrl(dependency("zstd"))).toBe(
+ "https://facebook.github.io/zstd/",
+ );
+ });
+
+ it("prefers the module URL, then the homepage, then the license URL", () => {
+ expect(
+ resolveModuleUrl({
+ ...dependency("zstd"),
+ moduleLicenseUrl: "https://example.com/license",
+ }),
+ ).toBe("https://facebook.github.io/zstd/");
+ expect(
+ resolveModuleUrl({
+ ...dependency("unknown-module"),
+ moduleLicenseUrl: "https://example.com/license",
+ }),
+ ).toBe("https://example.com/license");
+ expect(resolveModuleUrl(dependency("unknown-module"))).toBeUndefined();
+ });
+});
+
+describe("dedupeDependencies", () => {
+ it("keeps same-name records with different licenses", () => {
+ const result = dedupeDependencies([
+ dependency("logback-classic", "EPL-1.0"),
+ dependency("logback-classic", "LGPL-2.1"),
+ ]);
+ expect(result).toHaveLength(2);
+ });
+
+ it("collapses same-name same-license version rows and shows all versions", () => {
+ const result = dedupeDependencies([
+ { ...dependency("logback-classic", "EPL-1.0"), moduleVersion: "1.5.38" },
+ { ...dependency("logback-classic", "EPL-1.0"), moduleVersion: "1.6.3" },
+ ]);
+ expect(result).toHaveLength(1);
+ expect(result[0]?.moduleVersion).toBe("1.5.38, 1.6.3");
+ });
+
+ it("keeps a versioned textless record instead of lending its version", () => {
+ const result = dedupeDependencies([
+ { ...dependency("PDFium", "BSD-3-Clause"), moduleVersion: "1.0" },
+ dependency("PDFium", "BSD-3-Clause", "full text"),
+ ]);
+ expect(result).toHaveLength(2);
+ const bare = result.find((row) => !row.moduleLicenseText);
+ const text = result.find((row) => row.moduleLicenseText === "full text");
+ expect(bare?.moduleVersion).toBe("1.0");
+ expect(text?.moduleVersion).toBeUndefined();
+ });
+
+ it("attributes each version to the text it arrived with", () => {
+ const result = dedupeDependencies([
+ {
+ ...dependency("PDFium", "BSD-3-Clause", "text A"),
+ moduleVersion: "1.0",
+ },
+ {
+ ...dependency("PDFium", "BSD-3-Clause", "text B"),
+ moduleVersion: "2.0",
+ },
+ ]);
+ expect(result).toHaveLength(2);
+ expect(
+ result.find((row) => row.moduleLicenseText === "text A")?.moduleVersion,
+ ).toBe("1.0");
+ expect(
+ result.find((row) => row.moduleLicenseText === "text B")?.moduleVersion,
+ ).toBe("2.0");
+ });
+
+ it("keeps differing texts for the same component", () => {
+ const result = dedupeDependencies([
+ dependency("PDFium", "BSD-3-Clause", "text A"),
+ dependency("PDFium", "BSD-3-Clause", "text B"),
+ ]);
+ expect(result).toHaveLength(2);
+ });
+
+ it("assigns distinct row ids to hash-colliding texts", () => {
+ const result = dedupeDependencies([
+ dependency("PDFium", "BSD-3-Clause", "Ab"),
+ dependency("PDFium", "BSD-3-Clause", "BA"),
+ ]);
+ expect(result).toHaveLength(2);
+ expect(result[0]?.rowId).not.toBe(result[1]?.rowId);
+ });
+
+ it("keeps row ids stable for the same input", () => {
+ const input = [
+ dependency("PDFium", "BSD-3-Clause", "text A"),
+ dependency("QPDF", "Apache-2.0"),
+ ];
+ const first = dedupeDependencies(input).map((row) => row.rowId);
+ const second = dedupeDependencies(input).map((row) => row.rowId);
+ expect(first).toEqual(second);
+ });
+});
+
+describe("matchesLicenseQuery", () => {
+ it("matches the displayed label when the raw license spells it differently", () => {
+ expect(
+ matchesLicenseQuery(
+ dependency(
+ "spring-session-core",
+ "The Apache Software License, Version 2.0",
+ ),
+ "apache-2.0",
+ ),
+ ).toBe(true);
+ });
+
+ it("still matches name, version and raw license substrings", () => {
+ const row = {
+ ...dependency("@scope/pkg", "MIT"),
+ moduleVersion: "1.2.3",
+ };
+ expect(matchesLicenseQuery(row, "@scope")).toBe(true);
+ expect(matchesLicenseQuery(row, "1.2")).toBe(true);
+ expect(matchesLicenseQuery(row, "mit")).toBe(true);
+ expect(matchesLicenseQuery(row, "nope")).toBe(false);
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.ts b/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.ts
new file mode 100644
index 0000000000..37454cd505
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/licenseDisplay.ts
@@ -0,0 +1,402 @@
+import type { Dependency } from "@editor/components/shared/config/configSections/ThirdPartyLicensesSection";
+
+interface LicenseDisplay {
+ short: string;
+ spdxId?: string;
+ spdxIds?: string[];
+}
+
+// Exact names seen in the generated license report and the native NOTICE files,
+// normalized by normalizeLicenseName. Anything not listed here keeps its full
+// text: OR/AND compounds whose every part is known get one explainer link per
+// part, while WITH/slash compounds and unknown names get none and are never
+// silently rewritten.
+const LICENSE_ALIASES: Record<string, LicenseDisplay> = {
+ "apache 2": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "apache 2.0": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "apache license 2.0": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "apache license version 2.0": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "apache license, version 2.0": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "apache-2.0": { short: "Apache-2.0", spdxId: "Apache-2.0" },
+ "the apache license, version 2.0": {
+ short: "Apache-2.0",
+ spdxId: "Apache-2.0",
+ },
+ "the apache software license, version 2.0": {
+ short: "Apache-2.0",
+ spdxId: "Apache-2.0",
+ },
+ // spring-session-core names its license "Broadcom Foundation License" in the
+ // pom, but the published jar embeds META-INF/LICENSE.txt byte-identical to
+ // the standard Apache-2.0 text, so the About link points at Apache-2.0.
+ "broadcom foundation license": {
+ short: "Broadcom Foundation License",
+ spdxId: "Apache-2.0",
+ },
+ mit: { short: "MIT", spdxId: "MIT" },
+ "mit license": { short: "MIT", spdxId: "MIT" },
+ "the mit license": { short: "MIT", spdxId: "MIT" },
+ "mit-0": { short: "MIT-0", spdxId: "MIT-0" },
+ // ISC is its own SPDX id, not a variant of MIT.
+ isc: { short: "ISC", spdxId: "ISC" },
+ "bsd 3-clause": { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ "bsd-3-clause": { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ "bsd 3 clause": { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ "bsd 3-clause license": { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ "the bsd 3-clause license (bsd3)": {
+ short: "BSD-3-Clause",
+ spdxId: "BSD-3-Clause",
+ },
+ // SPDX calls BSD-3-Clause the "New or Revised License", so the old name maps here.
+ "revised bsd": { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ "bsd 2-clause": { short: "BSD-2-Clause", spdxId: "BSD-2-Clause" },
+ "bsd-2-clause": { short: "BSD-2-Clause", spdxId: "BSD-2-Clause" },
+ "bsd 2 clause": { short: "BSD-2-Clause", spdxId: "BSD-2-Clause" },
+ "bsd 2-clause license": { short: "BSD-2-Clause", spdxId: "BSD-2-Clause" },
+ // The "+" suffix means "or later", so "only" variants must not carry it.
+ "gnu lesser general public license v2.0 only": {
+ short: "LGPL-2.0",
+ spdxId: "LGPL-2.0-only",
+ },
+ "gnu lesser general public license v2.0 or later": {
+ short: "LGPL-2.0+",
+ spdxId: "LGPL-2.0-or-later",
+ },
+ "gnu lesser general public license v2.1 only": {
+ short: "LGPL-2.1",
+ spdxId: "LGPL-2.1-only",
+ },
+ "gnu lesser general public license v2.1 or later": {
+ short: "LGPL-2.1+",
+ spdxId: "LGPL-2.1-or-later",
+ },
+ "lgpl-2.1-only": { short: "LGPL-2.1", spdxId: "LGPL-2.1-only" },
+ "gnu lesser general public license v3.0 only": {
+ short: "LGPL-3.0",
+ spdxId: "LGPL-3.0-only",
+ },
+ "gnu lesser general public license v3.0 or later": {
+ short: "LGPL-3.0+",
+ spdxId: "LGPL-3.0-or-later",
+ },
+ "gnu general public license v2.0 only": {
+ short: "GPL-2.0",
+ spdxId: "GPL-2.0-only",
+ },
+ "gnu general public license v2.0 or later": {
+ short: "GPL-2.0+",
+ spdxId: "GPL-2.0-or-later",
+ },
+ "gnu general public license v3.0 only": {
+ short: "GPL-3.0",
+ spdxId: "GPL-3.0-only",
+ },
+ "gnu general public license v3.0 or later": {
+ short: "GPL-3.0+",
+ spdxId: "GPL-3.0-or-later",
+ },
+ "gpl2 w/ cpe": {
+ short: "GPL-2.0 w/ Classpath",
+ spdxId: "GPL-2.0-with-classpath-exception",
+ },
+ "gnu general public license, version 2 with the gnu classpath exception": {
+ short: "GPL-2.0 w/ Classpath",
+ spdxId: "GPL-2.0-with-classpath-exception",
+ },
+ "gnu affero general public license v3.0 only": {
+ short: "AGPL-3.0",
+ spdxId: "AGPL-3.0-only",
+ },
+ "gnu affero general public license v3.0 or later": {
+ short: "AGPL-3.0+",
+ spdxId: "AGPL-3.0-or-later",
+ },
+ "mozilla public license 2.0": { short: "MPL-2.0", spdxId: "MPL-2.0" },
+ "mozilla public license version 2.0": {
+ short: "MPL-2.0",
+ spdxId: "MPL-2.0",
+ },
+ "mozilla public license, version 2.0": {
+ short: "MPL-2.0",
+ spdxId: "MPL-2.0",
+ },
+ "mozilla public license 2.0 (mpl-2.0)": {
+ short: "MPL-2.0",
+ spdxId: "MPL-2.0",
+ },
+ "mpl 2.0": { short: "MPL-2.0", spdxId: "MPL-2.0" },
+ "mozilla public license 1.1": { short: "MPL-1.1", spdxId: "MPL-1.1" },
+ "mpl 1.1": { short: "MPL-1.1", spdxId: "MPL-1.1" },
+ "eclipse public license - v 2.0": { short: "EPL-2.0", spdxId: "EPL-2.0" },
+ "eclipse public license, version 2.0": {
+ short: "EPL-2.0",
+ spdxId: "EPL-2.0",
+ },
+ "epl-2.0": { short: "EPL-2.0", spdxId: "EPL-2.0" },
+ "common development and distribution license (cddl) version 1.0": {
+ short: "CDDL-1.0",
+ spdxId: "CDDL-1.0",
+ },
+ "public domain, per creative commons cc0": {
+ short: "CC0-1.0",
+ spdxId: "CC0-1.0",
+ },
+ "the w3c license": { short: "W3C", spdxId: "W3C" },
+ // No SPDX page exists for the Bouncy Castle licence, so shorten the label only.
+ "bouncy castle licence": { short: "BouncyCastle" },
+ "freetype license / ftl": { short: "FTL", spdxId: "FTL" },
+ "zlib license": { short: "Zlib", spdxId: "Zlib" },
+ "libpng license": { short: "libpng", spdxId: "Libpng" },
+ "libtiff license": { short: "libtiff", spdxId: "libtiff" },
+ // Custom composite notices have no SPDX page; shorten the label only.
+ "custom (ijg / bsd-style / zlib)": { short: "IJG / BSD / zlib" },
+};
+
+function normalizeLicenseName(license: string): string {
+ return license.toLowerCase().replace(/\s+/g, " ").trim();
+}
+
+// SPDX expressions distinguish alternatives and exceptions, so anything the
+// alias map does not know keeps its full text. Only top-level OR/AND splits
+// qualify for per-part links: WITH names an exception on one license and "/"
+// joins names reviewers asked to keep verbatim, so those stay linkless.
+const COMPOUND_LICENSE_PATTERN = /\bor\b|\band\b|\bwith\b|\//i;
+const OR_AND_SPLIT_PATTERN = /\s+\bor\b\s+|\s+\band\b\s+/i;
+
+function compoundDisplay(full: string): LicenseDisplay {
+ if (!OR_AND_SPLIT_PATTERN.test(full)) {
+ return { short: full };
+ }
+ const ids: string[] = [];
+ for (const part of full.split(OR_AND_SPLIT_PATTERN)) {
+ const name = normalizeLicenseName(part);
+ // Package metadata often parenthesizes SPDX expressions, so an exact
+ // miss retries without grouping parens; the label keeps them verbatim.
+ const alias =
+ LICENSE_ALIASES[name] ??
+ LICENSE_ALIASES[normalizeLicenseName(part.replace(/[()]/g, ""))];
+ if (!alias?.spdxId) {
+ return { short: full };
+ }
+ // Repeated alternatives link once; identical ids would also collide as keys.
+ if (!ids.includes(alias.spdxId)) {
+ ids.push(alias.spdxId);
+ }
+ }
+ return { short: full, spdxIds: ids };
+}
+
+export function resolveLicenseDisplay(
+ license: string | undefined,
+ moduleName?: string,
+): LicenseDisplay {
+ const full = license || "-";
+ const normalized = normalizeLicenseName(full);
+ if (moduleName) {
+ const override = MODULE_LICENSE_OVERRIDES.find(
+ (entry) =>
+ moduleName.startsWith(entry.modulePrefix) &&
+ normalized === entry.license,
+ );
+ if (override) {
+ return override.display;
+ }
+ }
+ const alias = LICENSE_ALIASES[normalized];
+ if (alias) {
+ return alias;
+ }
+ if (COMPOUND_LICENSE_PATTERN.test(full)) {
+ return compoundDisplay(full);
+ }
+ return { short: full };
+}
+
+export interface LicenseAboutLink {
+ spdxId: string;
+ short: string;
+}
+
+/**
+ * True when any searchable field — module name, version, raw license text, or
+ * the license label the UI displays — contains `needle` (lower-cased already).
+ */
+export function matchesLicenseQuery(
+ dependency: Dependency,
+ needle: string,
+): boolean {
+ return [
+ dependency.moduleName,
+ dependency.moduleVersion,
+ dependency.moduleLicense,
+ resolveLicenseDisplay(dependency.moduleLicense, dependency.moduleName)
+ .short,
+ ].some((field) => field?.toLowerCase().includes(needle));
+}
+
+// A single license keeps its short label; a compound gets one link per part
+// with the SPDX id as its own label, so no part hides behind another.
+export function resolveAboutLinks(display: LicenseDisplay): LicenseAboutLink[] {
+ if (display.spdxIds) {
+ return display.spdxIds.map((spdxId) => ({ spdxId, short: spdxId }));
+ }
+ if (display.spdxId) {
+ return [{ spdxId: display.spdxId, short: display.short }];
+ }
+ return [];
+}
+
+// A bare license name shared by unrelated projects cannot select an SPDX
+// page on its own. TwelveMonkeys is the only carrier of "The BSD License" in
+// the generated report and its LICENSE.txt is the BSD 3-clause text, so the
+// override is scoped to that project's modules instead of the bare name.
+const MODULE_LICENSE_OVERRIDES: Array<{
+ modulePrefix: string;
+ license: string;
+ display: LicenseDisplay;
+}> = [
+ {
+ modulePrefix: "com.twelvemonkeys",
+ license: "the bsd license",
+ display: { short: "BSD-3-Clause", spdxId: "BSD-3-Clause" },
+ },
+];
+
+// License files the generated report leaves URL-less, keyed by exact module
+// coordinate. Both locations verified against the jai-imageio GitHub org:
+// the core repo holds LICENSE.txt on master, the jpeg2000 repo holds both
+// named files at its root.
+const MODULE_LICENSE_URLS: Record<string, string> = {
+ "com.github.jai-imageio:jai-imageio-core":
+ "https://github.com/jai-imageio/jai-imageio-core/blob/master/LICENSE.txt",
+ "com.github.jai-imageio:jai-imageio-jpeg2000":
+ "https://github.com/jai-imageio/jai-imageio-jpeg2000/tree/master",
+};
+
+export function resolveModuleLicenseUrl(
+ dependency: Dependency,
+): string | undefined {
+ return (
+ dependency.moduleLicenseUrl ||
+ (dependency.moduleName
+ ? MODULE_LICENSE_URLS[dependency.moduleName]
+ : undefined)
+ );
+}
+
+// Project homepages for entries carrying neither a module nor a license URL,
+// keyed by the exact native notice title (or Maven coordinate).
+const MODULE_HOMEPAGES: Record<string, string> = {
+ PDFium: "https://pdfium.googlesource.com/pdfium/",
+ QPDF: "https://github.com/qpdf/qpdf",
+ libvips: "https://github.com/libvips/libvips",
+ "GLib / GObject": "https://docs.gtk.org/glib/",
+ libheif: "https://github.com/strukturag/libheif",
+ "libjxl (JPEG XL reference implementation)":
+ "https://github.com/libjxl/libjxl",
+ libwebp: "https://developers.google.com/speed/webp",
+ "libjpeg-turbo": "https://libjpeg-turbo.org/",
+ libpng: "http://www.libpng.org/",
+ libtiff: "http://www.libtiff.org/",
+ FreeType: "https://freetype.org/",
+ HarfBuzz: "https://harfbuzz.github.io/",
+ "Little CMS (lcms2)": "https://www.littlecms.com/",
+ "ICU (International Components for Unicode)": "https://icu.unicode.org/",
+ zlib: "https://zlib.net/",
+ zstd: "https://facebook.github.io/zstd/",
+ "libde265 (H.265/HEVC decoder, used for HEIC decoding)":
+ "https://github.com/strukturag/libde265",
+ "Kvazaar (H.265/HEVC encoder, used for HEIC encoding on Linux/macOS)":
+ "https://github.com/ultravideo/Kvazaar",
+ "OpenJPEG (JPEG 2000 codec, used for JPEG2000-in-HEIF)":
+ "https://www.openjpeg.org/",
+ "com.github.jai-imageio:jai-imageio-core":
+ "https://github.com/jai-imageio/jai-imageio-core",
+ "com.github.jai-imageio:jai-imageio-jpeg2000":
+ "https://github.com/jai-imageio/jai-imageio-jpeg2000",
+};
+
+export function resolveModuleUrl(dependency: Dependency): string | undefined {
+ return (
+ dependency.moduleUrl ||
+ (dependency.moduleName
+ ? MODULE_HOMEPAGES[dependency.moduleName]
+ : undefined) ||
+ dependency.moduleLicenseUrl
+ );
+}
+
+export interface DependencyRow extends Dependency {
+ rowId: string;
+}
+
+// The license report lists one row per resolved artifact, so the same module
+// shows up at several versions; a notice names each module once per license.
+// Versions aggregate only within records that already agree on everything else:
+// a version is never borrowed onto a row carrying a different license text, and
+// a textless record keeps its own versions instead of inventing a relationship.
+export function dedupeDependencies(
+ dependencies: Dependency[],
+): DependencyRow[] {
+ const byGroup = new Map<string, Dependency[]>();
+ for (const dependency of dependencies) {
+ // Tuple identity keeps ["ab", "c"] and ["a", "bc"] distinct.
+ const key = JSON.stringify([
+ (dependency.moduleName || "").toLowerCase(),
+ (dependency.moduleLicense || "").toLowerCase(),
+ ]);
+ const group = byGroup.get(key);
+ if (group) {
+ group.push(dependency);
+ } else {
+ byGroup.set(key, [dependency]);
+ }
+ }
+ const deduplicated: Dependency[] = [];
+ for (const group of byGroup.values()) {
+ interface VersionSlot {
+ row: Dependency;
+ versions: string[];
+ seen: Set<string>;
+ }
+ const textSlots = new Map<string, VersionSlot>();
+ let bare: VersionSlot | undefined;
+ for (const dependency of group) {
+ const slot = dependency.moduleLicenseText
+ ? (() => {
+ const existing = textSlots.get(dependency.moduleLicenseText);
+ if (existing) return existing;
+ const created: VersionSlot = {
+ row: dependency,
+ versions: [],
+ seen: new Set(),
+ };
+ textSlots.set(dependency.moduleLicenseText, created);
+ return created;
+ })()
+ : (bare ??= { row: dependency, versions: [], seen: new Set() });
+ if (
+ dependency.moduleVersion &&
+ !slot.seen.has(dependency.moduleVersion)
+ ) {
+ slot.seen.add(dependency.moduleVersion);
+ slot.versions.push(dependency.moduleVersion);
+ }
+ }
+ for (const slot of [...textSlots.values(), ...(bare ? [bare] : [])]) {
+ deduplicated.push(
+ slot.versions.length > 0
+ ? { ...slot.row, moduleVersion: slot.versions.join(", ") }
+ : slot.row,
+ );
+ }
+ }
+ // Ordinal IDs stay stable while the underlying list is unchanged and never
+ // collide however similar two texts are.
+ return deduplicated
+ .sort((a, b) => (a.moduleName || "").localeCompare(b.moduleName || ""))
+ .map((dependency, index) => ({
+ ...dependency,
+ rowId: `license-row-${index}`,
+ }));
+}