#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Bump version to 3.2.2, refresh translations, and backend reliability fixes (#8617)
James Brunton684608d14377
diff --git a/.github/aur/stirling-pdf-desktop/PKGBUILD b/.github/aur/stirling-pdf-desktop/PKGBUILDindex 618b2c75fb..f964779ae6 100644--- a/.github/aur/stirling-pdf-desktop/PKGBUILD+++ b/.github/aur/stirling-pdf-desktop/PKGBUILD@@ -1,6 +1,6 @@# Maintainer: Stirling PDF Inc <[email protected]>pkgname=stirling-pdf-desktop-pkgver=3.2.1+pkgver=3.2.2pkgrel=1pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"arch=('x86_64')diff --git a/.github/aur/stirling-pdf-server-bin/PKGBUILD b/.github/aur/stirling-pdf-server-bin/PKGBUILDindex 38ef47b03b..7f653e0640 100644--- a/.github/aur/stirling-pdf-server-bin/PKGBUILD+++ b/.github/aur/stirling-pdf-server-bin/PKGBUILD@@ -1,6 +1,6 @@# Maintainer: Stirling PDF Inc <[email protected]>pkgname=stirling-pdf-server-bin-pkgver=3.2.1+pkgver=3.2.2pkgrel=1pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"arch=('any')diff --git a/.gitignore b/.gitignoreindex fb5dc3754a..655a0c109e 100644--- a/.gitignore+++ b/.gitignore@@ -288,6 +288,7 @@ node_modulestest_batch.json*.backup.*.jsonfrontend/public/locales/*/translation.backup*.json+/translation_logs/# Development/build artifacts.gradle-cache/diff --git a/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java b/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.javaindex 96293e9c3f..6d2da58b58 100644--- a/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java+++ b/app/common/src/main/java/stirling/software/common/aop/AutoJobAspect.java@@ -12,6 +12,7 @@ import java.util.function.Supplier;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.slf4j.MDC;+import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;@@ -25,6 +26,7 @@ import stirling.software.common.annotations.AutoJobPostMapping;import stirling.software.common.model.api.PDFFile;import stirling.software.common.service.FileStorage;import stirling.software.common.service.JobExecutorService;+import stirling.software.common.service.JobOwnershipService;@Aspect@Component@@ -35,10 +37,15 @@ public class AutoJobAspect {private static final Duration RETRY_BASE_DELAY = Duration.ofMillis(100);+ private static final String AUDIT_PRINCIPAL_MDC_KEY = "auditPrincipal";+private final JobExecutorService jobExecutorService;private final HttpServletRequest request;private final FileStorage fileStorage;+ @Autowired(required = false)+ private JobOwnershipService jobOwnershipService;+@Around("@annotation(autoJobPostMapping)")public Object wrapWithJobExecution(ProceedingJoinPoint joinPoint, AutoJobPostMapping autoJobPostMapping) throws Exception {@@ -332,6 +339,10 @@ public class AutoJobAspect {*/private <T> Supplier<T> wrapWithMDC(Supplier<T> supplier) {final Map<String, String> captured = MDC.getCopyOfContextMap();+ final String caller =+ jobOwnershipService != null+ ? jobOwnershipService.getCurrentUserId().orElse(null)+ : null;return () -> {final Map<String, String> previous = MDC.getCopyOfContextMap();try {@@ -341,6 +352,9 @@ public class AutoJobAspect {} else {MDC.clear();}+ if (caller != null && MDC.get(AUDIT_PRINCIPAL_MDC_KEY) == null) {+ MDC.put(AUDIT_PRINCIPAL_MDC_KEY, caller);+ }return supplier.get();} finally {// Restore previous state (or clear if there was none)diff --git a/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.java b/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.javanew file mode 100644index 0000000000..b11768ab3e--- /dev/null+++ b/app/common/src/main/java/stirling/software/common/util/CalibreSandboxPolicy.java@@ -0,0 +1,162 @@+package stirling.software.common.util;++import java.io.File;+import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.atomic.AtomicBoolean;++import lombok.extern.slf4j.Slf4j;++@Slf4j+final class CalibreSandboxPolicy {++ enum Mode {+ UNSUPPORTED,+ OFF,+ ENFORCE,+ REQUIRED+ }++ static final String LAUNCHER = "calibre_sandbox.py";+ static final String MODE_VARIABLE = "STIRLING_CALIBRE_SANDBOX";+ static final String LAUNCHER_PREFIX = "calibre-sandbox:";+ static final int LAUNCHER_REFUSED_EXIT_CODE = 125;+ static final String REFUSED_MESSAGE = "Calibre conversion refused: its sandbox is unavailable";++ private static final Path CALIBRE_CONVERT = Path.of("/opt/calibre/ebook-convert");++ private static final String HOME_DIR = ".calibre";++ private static final Set<String> ENV_ALLOWLIST =+ Set.of(+ "USER",+ "LOGNAME",+ "PATH",+ "LANG",+ "LANGUAGE",+ "TZ",+ "LD_LIBRARY_PATH",+ "FONTCONFIG_PATH",+ "FONTCONFIG_FILE",+ "MALLOC_ARENA_MAX",+ MODE_VARIABLE);++ private static final List<String> ENV_ALLOWED_PREFIXES = List.of("LC_", "QT_", "QTWEBENGINE_");++ private static final AtomicBoolean unsupportedReported = new AtomicBoolean();++ private CalibreSandboxPolicy() {}++ static Mode configuredMode() {+ return resolveMode(System.getenv(MODE_VARIABLE), Files.isExecutable(CALIBRE_CONVERT));+ }++ static Mode resolveMode(String configured, boolean sandboxExpected) {+ if (configured == null || configured.isBlank()) {+ return sandboxExpected ? Mode.ENFORCE : Mode.UNSUPPORTED;+ }+ return switch (configured.trim().toLowerCase(Locale.ROOT)) {+ case "off" -> Mode.OFF;+ case "required" -> Mode.REQUIRED;+ default -> Mode.ENFORCE;+ };+ }++ static List<String> confine(+ Mode mode, List<String> command, File workingDirectory, Map<String, String> env)+ throws IOException {+ switch (mode) {+ case UNSUPPORTED -> {+ if (unsupportedReported.compareAndSet(false, true)) {+ log.warn(+ "Calibre is not installed under {}, so it runs unconfined; set"+ + " {}=required to confine it anyway",+ CALIBRE_CONVERT.getParent(),+ MODE_VARIABLE);+ }+ return command;+ }+ case OFF -> {+ log.error("Calibre is running unconfined because {}=off", MODE_VARIABLE);+ return command;+ }+ default -> {+ return wrap(mode, command, workingDirectory, env);+ }+ }+ }++ private static List<String> wrap(+ Mode mode, List<String> command, File workingDirectory, Map<String, String> env)+ throws IOException {+ if (workingDirectory == null) {+ throw new IOException("Calibre needs a working directory to be confined to");+ }+ String python = CheckProgramInstall.getAvailablePythonCommand();+ if (python == null) {+ if (mode == Mode.REQUIRED) {+ log.error("Refusing to run Calibre: its sandbox needs Python, which is missing");+ throw new IOException(REFUSED_MESSAGE);+ }+ log.error("Calibre is running unconfined because Python is not installed");+ return command;+ }+ Path workDir = workingDirectory.toPath().toAbsolutePath().normalize();+ Path home = Files.createDirectories(workDir.resolve(HOME_DIR));++ env.keySet().removeIf(name -> !isEnvAllowed(name));+ env.put(MODE_VARIABLE, mode.name().toLowerCase(Locale.ROOT));+ env.put("HOME", home.toString());+ for (String name : List.of("TMPDIR", "TMP", "TEMP", "XDG_RUNTIME_DIR")) {+ env.put(name, home.toString());+ }++ List<String> confined = new ArrayList<>();+ confined.add(python);+ confined.add("-I");+ confined.add(GeneralUtils.extractScript(LAUNCHER).toAbsolutePath().toString());+ confined.add(workDir.toString());+ confined.addAll(command);+ return confined;+ }++ static void checkLauncherOutcome(int exitCode, List<String> errorLines) throws IOException {+ List<String> launcherLines =+ errorLines.stream().filter(line -> line.startsWith(LAUNCHER_PREFIX)).toList();+ if (launcherLines.isEmpty()) {+ return;+ }+ if (exitCode == LAUNCHER_REFUSED_EXIT_CODE) {+ log.error(+ "Refusing to run Calibre: its sandbox is required but unavailable on this"+ + " host: {}",+ String.join("; ", launcherLines));+ throw new IOException(REFUSED_MESSAGE);+ }+ log.error(+ "Calibre ran without part of its sandbox: {}. Set {}=required to refuse such runs",+ String.join("; ", launcherLines),+ MODE_VARIABLE);+ }++ private static boolean isEnvAllowed(String name) {+ if (name == null) {+ return false;+ }+ if (ENV_ALLOWLIST.contains(name)) {+ return true;+ }+ for (String prefix : ENV_ALLOWED_PREFIXES) {+ if (name.startsWith(prefix)) {+ return true;+ }+ }+ return false;+ }+}diff --git a/app/common/src/main/java/stirling/software/common/util/CustomHtmlSanitizer.java b/app/common/src/main/java/stirling/software/common/util/CustomHtmlSanitizer.javaindex 0d0c2c7f6a..416d4fb633 100644--- a/app/common/src/main/java/stirling/software/common/util/CustomHtmlSanitizer.java+++ b/app/common/src/main/java/stirling/software/common/util/CustomHtmlSanitizer.java@@ -1,5 +1,7 @@package stirling.software.common.util;+import java.util.regex.Pattern;+import org.owasp.html.AttributePolicy;import org.owasp.html.HtmlPolicyBuilder;import org.owasp.html.PolicyFactory;@@ -12,6 +14,9 @@ import stirling.software.common.service.SsrfProtectionService;@Componentpublic class CustomHtmlSanitizer {+ private static final Pattern RASTER_IMAGE_DATA_URI =+ Pattern.compile("^data:image/(png|jpe?g|gif|webp|bmp)[;,]", Pattern.CASE_INSENSITIVE);+private final SsrfProtectionService ssrfProtectionService;private final ApplicationProperties applicationProperties;@@ -32,6 +37,11 @@ public class CustomHtmlSanitizer {String trimmedValue = value.trim();+ if (trimmedValue.regionMatches(true, 0, "data:", 0, 5)+ && !RASTER_IMAGE_DATA_URI.matcher(trimmedValue).find()) {+ return null;+ }+// Use the SSRF protection service to validate the URLif (ssrfProtectionService != null&& !ssrfProtectionService.isUrlAllowed(trimmedValue)) {@@ -44,6 +54,7 @@ public class CustomHtmlSanitizer {private final PolicyFactory SSRF_SAFE_IMAGES_POLICY =new HtmlPolicyBuilder()+ .allowUrlProtocols("data").allowElements("img").allowAttributes("alt", "width", "height", "title").onElements("img")@@ -63,7 +74,10 @@ public class CustomHtmlSanitizer {.and(new HtmlPolicyBuilder().disallowElements("noscript").toFactory());public String sanitize(String html) {- boolean disableSanitize = applicationProperties.getSystem().isDisableSanitize();- return disableSanitize ? html : POLICY.sanitize(html);+ return isDisabled() ? html : POLICY.sanitize(html);+ }++ public boolean isDisabled() {+ return applicationProperties.getSystem().isDisableSanitize();}}diff --git a/app/common/src/main/java/stirling/software/common/util/FileToPdf.java b/app/common/src/main/java/stirling/software/common/util/FileToPdf.javaindex 00d431e9f4..c1fd628508 100644--- a/app/common/src/main/java/stirling/software/common/util/FileToPdf.java+++ b/app/common/src/main/java/stirling/software/common/util/FileToPdf.java@@ -1,18 +1,23 @@package stirling.software.common.util;-import java.io.FileOutputStream;import java.io.IOException;-import java.io.UncheckedIOException;+import java.net.URLDecoder;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;+import java.util.ArrayDeque;import java.util.ArrayList;+import java.util.Base64;+import java.util.Comparator;+import java.util.Deque;+import java.util.HashMap;import java.util.List;import java.util.Locale;-import java.util.stream.Stream;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;-import java.util.zip.ZipOutputStream;import io.github.pixee.security.ZipSecurity;@@ -21,6 +26,28 @@ import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;public class FileToPdf {+ static final String SANITIZED_ALLOWED_PROTOCOLS = "data";+ static final String UNSANITIZED_ALLOWED_PROTOCOLS = "data,http,https";++ private static final Pattern UNSAFE_NAME_CHARS = Pattern.compile("[^A-Za-z0-9._-]");+ private static final Pattern IMG_SRC =+ Pattern.compile(+ "(<img\\b[^>]*?\\bsrc\\s*=\\s*)(\"([^\"]*)\"|'([^']*)'|([^\\s\"'>]+))",+ Pattern.CASE_INSENSITIVE);+ private static final Pattern NUMERIC_ENTITY = Pattern.compile("&#(x?)([0-9a-fA-F]+);");+ private static final long MAX_INLINED_IMAGE_CHARS = 64L * 1024 * 1024;+ private static final Map<String, String> IMAGE_MIME_TYPES =+ Map.of(+ "png", "image/png",+ "jpg", "image/jpeg",+ "jpeg", "image/jpeg",+ "gif", "image/gif",+ "webp", "image/webp",+ "bmp", "image/bmp");+ private static final Comparator<String> HTML_ORDER =+ Comparator.comparingInt((String key) -> key.split("/").length)+ .thenComparing(Comparator.naturalOrder());+public static byte[] convertHtmlToPdf(String weasyprintPath,HTMLToPdfRequest request,@@ -30,44 +57,42 @@ public class FileToPdf {CustomHtmlSanitizer customHtmlSanitizer)throws IOException, InterruptedException {- try (TempFile tempOutputFile = new TempFile(tempFileManager, ".pdf")) {- try (TempFile tempInputFile =- new TempFile(- tempFileManager,- fileName.toLowerCase(Locale.ROOT).endsWith(".html")- ? ".html"- : ".zip")) {-- if (fileName.toLowerCase(Locale.ROOT).endsWith(".html")) {- String sanitizedHtml =- sanitizeHtmlContent(- new String(fileBytes, StandardCharsets.UTF_8),- customHtmlSanitizer);- Files.writeString(tempInputFile.getPath(), sanitizedHtml);- } else if (fileName.toLowerCase(Locale.ROOT).endsWith(".zip")) {- Files.write(tempInputFile.getPath(), fileBytes);- sanitizeHtmlFilesInZip(- tempInputFile.getPath(), tempFileManager, customHtmlSanitizer);- } else {- throw ExceptionUtils.createHtmlFileRequiredException();- }+ String lowerName = fileName.toLowerCase(Locale.ROOT);+ String html;+ if (lowerName.endsWith(".html")) {+ html =+ sanitizeHtmlContent(+ new String(fileBytes, StandardCharsets.UTF_8), customHtmlSanitizer);+ } else if (lowerName.endsWith(".zip")) {+ html = htmlFromZip(fileBytes, tempFileManager, customHtmlSanitizer);+ } else {+ throw ExceptionUtils.createHtmlFileRequiredException();+ }++ try (TempFile tempOutputFile = new TempFile(tempFileManager, ".pdf");+ TempFile tempInputFile = new TempFile(tempFileManager, ".html")) {+ Files.writeString(tempInputFile.getPath(), html);++ List<String> command = new ArrayList<>();+ command.add(weasyprintPath);+ command.add("-e");+ command.add("utf-8");+ command.add("-v");+ command.add("--pdf-forms");+ command.add("--allowed-protocols");+ command.add(+ customHtmlSanitizer.isDisabled()+ ? UNSANITIZED_ALLOWED_PROTOCOLS+ : SANITIZED_ALLOWED_PROTOCOLS);+ command.add(tempInputFile.getAbsolutePath());+ command.add(tempOutputFile.getAbsolutePath());- List<String> command = new ArrayList<>();- command.add(weasyprintPath);- command.add("-e");- command.add("utf-8");- command.add("-v");- command.add("--pdf-forms");- command.add(tempInputFile.getAbsolutePath());- command.add(tempOutputFile.getAbsolutePath());-- ProcessExecutorResult returnCode =- ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT)- .runCommandWithOutputHandling(command);-- return Files.readAllBytes(tempOutputFile.getPath());- } // tempInputFile auto-closed- } // tempOutputFile auto-closed+ ProcessExecutorResult returnCode =+ ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT)+ .runCommandWithOutputHandling(command);++ return Files.readAllBytes(tempOutputFile.getPath());+ }}private static String sanitizeHtmlContent(@@ -75,71 +100,166 @@ public class FileToPdf {return customHtmlSanitizer.sanitize(htmlContent);}- private static void sanitizeHtmlFilesInZip(- Path zipFilePath,- TempFileManager tempFileManager,- CustomHtmlSanitizer customHtmlSanitizer)+ private static String htmlFromZip(+ byte[] zipBytes, TempFileManager tempFileManager, CustomHtmlSanitizer sanitizer)throws IOException {try (TempDirectory tempUnzippedDir = new TempDirectory(tempFileManager)) {- try (ZipInputStream zipIn =- ZipSecurity.createHardenedInputStream(Files.newInputStream(zipFilePath))) {- ZipBombGuard.Budget budget = new ZipBombGuard.Budget();- ZipEntry entry = zipIn.getNextEntry();- while (entry != null) {- Path filePath =- tempUnzippedDir.getPath().resolve(sanitizeZipFilename(entry.getName()));- Path normalizedTargetDir =- tempUnzippedDir.getPath().toAbsolutePath().normalize();- Path normalizedFilePath = filePath.toAbsolutePath().normalize();- if (!normalizedFilePath.startsWith(normalizedTargetDir)) {+ Path root = tempUnzippedDir.getPath().toAbsolutePath().normalize();+ Map<String, Path> entries = extractZip(zipBytes, root);++ String mainEntry = selectMainHtml(entries.keySet());+ if (mainEntry == null) {+ throw ExceptionUtils.createHtmlFileRequiredException();+ }+ String html = Files.readString(entries.get(mainEntry), StandardCharsets.UTF_8);+ return sanitizeHtmlContent(inlineLocalImages(html, mainEntry, entries), sanitizer);+ }+ }++ private static Map<String, Path> extractZip(byte[] zipBytes, Path root) throws IOException {+ Map<String, Path> entries = new HashMap<>();+ try (ZipInputStream zipIn =+ ZipSecurity.createHardenedInputStream(new java.io.ByteArrayInputStream(zipBytes))) {+ ZipBombGuard.Budget budget = new ZipBombGuard.Budget();+ ZipEntry entry;+ while ((entry = zipIn.getNextEntry()) != null) {+ String key = normalizeEntryPath(entry.getName());+ String safeName = sanitizeZipFilename(entry.getName());+ if (!entry.isDirectory() && key != null && !safeName.isEmpty()) {+ Path filePath = root.resolve(safeName).normalize();+ if (!filePath.startsWith(root)) {throw new IOException("Zip entry path escapes target directory: " + entry.getName());}- if (!entry.isDirectory()) {- Files.createDirectories(filePath.getParent());- if (entry.getName().toLowerCase(Locale.ROOT).endsWith(".html")- || entry.getName().toLowerCase(Locale.ROOT).endsWith(".htm")) {- String content =- new String(budget.readEntry(zipIn), StandardCharsets.UTF_8);- String sanitizedContent =- sanitizeHtmlContent(content, customHtmlSanitizer);- Files.writeString(filePath, sanitizedContent);- } else {- budget.copyEntry(zipIn, filePath);- }- }- zipIn.closeEntry();- entry = zipIn.getNextEntry();+ Files.createDirectories(filePath.getParent());+ budget.copyEntry(zipIn, filePath);+ entries.put(key, filePath);+ }+ zipIn.closeEntry();+ }+ }+ return entries;+ }++ static String selectMainHtml(Iterable<String> entryKeys) {+ String best = null;+ for (String key : entryKeys) {+ String lower = key.toLowerCase(Locale.ROOT);+ if (lower.equals("index.html") || lower.equals("index.htm")) {+ return key;+ }+ if ((lower.endsWith(".html") || lower.endsWith(".htm"))+ && (best == null || HTML_ORDER.compare(key, best) < 0)) {+ best = key;+ }+ }+ return best;+ }++ private static String inlineLocalImages(+ String html, String mainEntry, Map<String, Path> entries) throws IOException {+ int slash = mainEntry.lastIndexOf('/');+ String baseDir = slash < 0 ? "" : mainEntry.substring(0, slash + 1);++ Matcher matcher = IMG_SRC.matcher(html);+ StringBuilder out = new StringBuilder();+ Map<String, String> encoded = new HashMap<>();+ long inlined = 0;+ while (matcher.find()) {+ String raw =+ matcher.group(3) != null+ ? matcher.group(3)+ : matcher.group(4) != null ? matcher.group(4) : matcher.group(5);+ String ref = decodeHtmlAttribute(raw);+ String dataUri;+ if (encoded.containsKey(ref)) {+ dataUri = encoded.get(ref);+ } else {+ dataUri = toDataUri(ref, baseDir, entries);+ encoded.put(ref, dataUri);+ }+ if (dataUri != null) {+ inlined += dataUri.length();+ if (inlined > MAX_INLINED_IMAGE_CHARS) {+ throw new IOException("Inlined image content exceeds the permitted size");}}+ String replacement =+ dataUri == null ? matcher.group() : matcher.group(1) + "\"" + dataUri + "\"";+ matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));+ }+ matcher.appendTail(out);+ return out.toString();+ }- // Repack the sanitized files- zipDirectory(tempUnzippedDir.getPath(), zipFilePath);- } // tempUnzippedDir auto-cleaned+ private static String toDataUri(String ref, String baseDir, Map<String, Path> entries)+ throws IOException {+ if (ref.isEmpty() || ref.startsWith("//") || ref.matches("^[A-Za-z][A-Za-z0-9+.-]*:.*")) {+ return null;+ }+ String path = ref.replaceAll("[?#].*$", "");+ try {+ path = URLDecoder.decode(path.replace("+", "%2B"), StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ return null;+ }+ String key = normalizeEntryPath(path.startsWith("/") ? path : baseDir + path);+ Path file = key == null ? null : entries.get(key);+ String extension = key == null ? "" : key.substring(key.lastIndexOf('.') + 1);+ String mime = IMAGE_MIME_TYPES.get(extension.toLowerCase(Locale.ROOT));+ if (file == null || mime == null) {+ return null;+ }+ return "data:"+ + mime+ + ";base64,"+ + Base64.getEncoder().encodeToString(Files.readAllBytes(file));}- private static void zipDirectory(Path sourceDir, Path zipFilePath) throws IOException {- try (ZipOutputStream zos =- new ZipOutputStream(new FileOutputStream(zipFilePath.toFile()))) {- try (Stream<Path> walk = Files.walk(sourceDir)) {- walk.filter(path -> !Files.isDirectory(path))- .forEach(- path -> {- ZipEntry zipEntry =- new ZipEntry(sourceDir.relativize(path).toString());- try {- zos.putNextEntry(zipEntry);- Files.copy(path, zos);- zos.closeEntry();- } catch (IOException e) {- throw new UncheckedIOException(e);- }- });+ private static String decodeHtmlAttribute(String value) {+ Matcher matcher = NUMERIC_ENTITY.matcher(value);+ StringBuilder out = new StringBuilder();+ while (matcher.find()) {+ String replacement;+ try {+ int codePoint =+ Integer.parseInt(matcher.group(2), matcher.group(1).isEmpty() ? 10 : 16);+ replacement = new String(Character.toChars(codePoint));+ } catch (IllegalArgumentException e) {+ replacement = matcher.group();}+ matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));}+ matcher.appendTail(out);+ return out.toString()+ .replace(""", "\"")+ .replace("<", "<")+ .replace(">", ">")+ .replace("&", "&");}- static String sanitizeZipFilename(String entryName) {+ static String normalizeEntryPath(String entryName) {+ if (entryName == null) {+ return null;+ }+ Deque<String> segments = new ArrayDeque<>();+ for (String segment : entryName.replace('\\', '/').split("/")) {+ if (segment.isEmpty() || segment.equals(".")) {+ continue;+ }+ if (segment.equals("..")) {+ if (segments.isEmpty()) {+ return null;+ }+ segments.removeLast();+ } else {+ segments.addLast(segment);+ }+ }+ return segments.isEmpty() ? null : String.join("/", segments);+ }++ public static String sanitizeZipFilename(String entryName) {if (entryName == null || entryName.trim().isEmpty()) {return "";}@@ -154,17 +274,20 @@ public class FileToPdf {.getLeadingSlashesPattern().matcher(entryName).replaceAll("");-- // Recursively remove path traversal sequences- while (entryName.contains("../") || entryName.contains("..\\")) {- entryName = entryName.replace("../", "").replace("..\\", "");- }// Normalize all backslashes to forward slashesentryName =RegexPatternUtils.getInstance().getBackslashPattern().matcher(entryName).replaceAll("/");- return entryName;++ List<String> safeSegments = new ArrayList<>();+ for (String segment : entryName.split("/")) {+ String safe = UNSAFE_NAME_CHARS.matcher(segment).replaceAll("_");+ if (!safe.isEmpty() && !safe.equals(".") && !safe.equals("..")) {+ safeSegments.add(safe);+ }+ }+ return String.join("/", safeSegments);}}diff --git a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.javaindex b153ee1391..1b64ea76f0 100644--- a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java@@ -45,7 +45,8 @@ public class GeneralUtils {private static final BigDecimal KIB = BigDecimal.valueOf(1024L);private static final BigDecimal LONG_MAX_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE);- private final Set<String> DEFAULT_VALID_SCRIPTS = Set.of("png_to_webp.py", "split_photos.py");+ private final Set<String> DEFAULT_VALID_SCRIPTS =+ Set.of("calibre_sandbox.py", "png_to_webp.py", "split_photos.py");private final Set<String> DEFAULT_VALID_PIPELINE =Set.of("OCR images.json",@@ -58,7 +59,7 @@ public class GeneralUtils {// Extracted once per run. Rewriting a script while another request is exec-ing it// races wherever rename is not atomic, such as 9p or NFS bind mounts.- private final Map<String, Path> EXTRACTED_SCRIPTS = new ConcurrentHashMap<>();+ private final Map<String, byte[]> BUNDLED_SCRIPTS = new ConcurrentHashMap<>();private final RegexPatternUtils patternCache = RegexPatternUtils.getInstance();// Valid size units used for convertSizeToBytes validation and parsingprivate final Set<String> VALID_SIZE_UNITS = Set.of("B", "KB", "MB", "GB", "TB");@@ -1062,36 +1063,57 @@ public class GeneralUtils {if (!DEFAULT_VALID_SCRIPTS.contains(scriptName)) {throw new IllegalArgumentException(- "scriptName must be either 'png_to_webp.py' or 'split_photos.py'");+ "scriptName must be one of 'calibre_sandbox.py', 'png_to_webp.py' or"+ + " 'split_photos.py'");}Path scriptsDir = Path.of(InstallationPathConfig.getScriptsPath(), PYTHON_SCRIPTS_DIR);Path target = scriptsDir.resolve(scriptName);- Path cached = EXTRACTED_SCRIPTS.get(scriptName);- if (cached != null && Files.isRegularFile(cached)) {- return cached;+ ClassPathResource res =+ new ClassPathResource("static/" + PYTHON_SCRIPTS_DIR + "/" + scriptName);+ byte[] bundled = bundledScript(scriptName, res);+ if (holdsBundledScript(target, bundled)) {+ return target;}- synchronized (EXTRACTED_SCRIPTS) {- cached = EXTRACTED_SCRIPTS.get(scriptName);- if (cached != null && Files.isRegularFile(cached)) {- return cached;+ synchronized (BUNDLED_SCRIPTS) {+ if (holdsBundledScript(target, bundled)) {+ return target;}-Files.createDirectories(scriptsDir);- ClassPathResource res =- new ClassPathResource("static/" + PYTHON_SCRIPTS_DIR + "/" + scriptName);- if (!res.exists()) {- log.error("Resource not found: {}", res.getPath());- throw new IOException("Resource not found: " + res.getPath());- }copyResourceToFile(res, target);- EXTRACTED_SCRIPTS.put(scriptName, target);return target;}}+ private byte[] bundledScript(String scriptName, ClassPathResource res) throws IOException {+ byte[] cached = BUNDLED_SCRIPTS.get(scriptName);+ if (cached != null) {+ return cached;+ }+ if (!res.exists()) {+ log.error("Resource not found: {}", res.getPath());+ throw new IOException("Resource not found: " + res.getPath());+ }+ byte[] contents;+ try (InputStream in = res.getInputStream()) {+ contents = in.readAllBytes();+ }+ BUNDLED_SCRIPTS.putIfAbsent(scriptName, contents);+ return BUNDLED_SCRIPTS.get(scriptName);+ }++ private boolean holdsBundledScript(Path target, byte[] bundled) {+ try {+ return Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)+ && Files.size(target) == bundled.length+ && Arrays.equals(Files.readAllBytes(target), bundled);+ } catch (IOException e) {+ return false;+ }+ }+/** Copies a resource from the classpath to a specified target file.*diff --git a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.javaindex 0e278b780e..7538c0e3fb 100644--- a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java+++ b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java@@ -40,6 +40,9 @@ public class ProcessExecutor {private static volatile boolean libreOfficeSandboxed =Files.isExecutable(Path.of("/usr/local/lib/stirling/lo-sandbox"));+ private static volatile CalibreSandboxPolicy.Mode calibreSandboxMode =+ CalibreSandboxPolicy.configuredMode();+// Made by the init script (create_office_profile_template in init-without-ocr.sh).private static final Path libreOfficeProfileTemplate = profileTemplateFromEnvironment();private final Semaphore semaphore;@@ -185,7 +188,7 @@ public class ProcessExecutor {.getProcessExecutor().getTimeoutMinutes().getOcrMyPdfTimeoutMinutes();- case CFF_CONVERTER -> 5L;+ case CFF_CONVERTER -> 1L;case FFMPEG ->applicationProperties.getProcessExecutor()@@ -205,6 +208,10 @@ public class ProcessExecutor {libreOfficeSandboxed = sandboxed;}+ static void setCalibreSandboxMode(CalibreSandboxPolicy.Mode mode) {+ calibreSandboxMode = mode;+ }+private static Path profileTemplateFromEnvironment() {String template = System.getenv("STIRLING_LO_PROFILE_TEMPLATE");if (template == null || template.isBlank()) {@@ -321,6 +328,14 @@ public class ProcessExecutor {log.info("Running command: {}", String.join(" ", commandToRun));ProcessBuilder processBuilder = new ProcessBuilder(commandToRun);scrubEnvironment(processBuilder);+ if (processType == Processes.CALIBRE) {+ processBuilder.command(+ CalibreSandboxPolicy.confine(+ calibreSandboxMode,+ commandToRun,+ workingDirectory,+ processBuilder.environment()));+ }if (processType == Processes.LIBRE_OFFICE && libreOfficeSandboxed) {jobPolicy =LibreOfficeSandboxPolicy.forCommand(commandToRun, libreOfficeWorkRoots)@@ -366,7 +381,7 @@ public class ProcessExecutor {errorReader, 5_000_000))!= null) {errorLines.add(line);- if (liveUpdates) log.info(line);+ if (liveUpdates) logLiveLine(line);}} catch (InterruptedIOException e) {log.warn(@@ -391,7 +406,7 @@ public class ProcessExecutor {outputReader, 5_000_000))!= null) {outputLines.add(line);- if (liveUpdates) log.info(line);+ if (liveUpdates) logLiveLine(line);}} catch (InterruptedIOException e) {log.warn(@@ -455,6 +470,10 @@ public class ProcessExecutor {errorReaderThread.join();outputReaderThread.join();+ if (processType == Processes.CALIBRE) {+ return finishCalibreRun(exitCode, outputLines, errorLines);+ }+boolean isQpdf =commandToRun != null&& !commandToRun.isEmpty()@@ -513,6 +532,30 @@ public class ProcessExecutor {return new ProcessExecutorResult(exitCode, messages);}+ private void logLiveLine(String line) {+ if (processType == Processes.CALIBRE) {+ log.debug(line);+ } else {+ log.info(line);+ }+ }++ private ProcessExecutorResult finishCalibreRun(+ int exitCode, List<String> outputLines, List<String> errorLines) throws IOException {+ String output = String.join("\n", outputLines);+ String errors = String.join("\n", errorLines);+ if (!liveUpdates) {+ log.debug("Calibre output:\n{}", output);+ log.debug("Calibre error output:\n{}", errors);+ }+ CalibreSandboxPolicy.checkLauncherOutcome(exitCode, errorLines);+ if (exitCode != 0) {+ log.warn("Calibre exited with code {}; its output is logged at debug level", exitCode);+ throw new IOException("Calibre conversion failed with exit code " + exitCode);+ }+ return new ProcessExecutorResult(exitCode, output + errors);+ }+private static final Set<String> LIBRE_OFFICE_ENV_ALLOWLIST =Set.of("HOME",diff --git a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.javaindex 5f9f0133ff..aca5b68fd2 100644--- a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java@@ -1,7 +1,10 @@package stirling.software.common.util;+import java.nio.charset.StandardCharsets;import java.util.regex.Pattern;+import org.springframework.web.util.UriUtils;+public class RequestUriUtils {// Share tokens are 36-char lowercase UUIDs (UUID.randomUUID().toString()); match exactly@@ -22,12 +25,11 @@ public class RequestUriUtils {}public static boolean isStaticResource(String contextPath, String requestURI) {- if (requestURI == null) {+ String normalizedUri = normalizeUriOrNull(contextPath, requestURI);+ if (normalizedUri == null) {return false;}- String normalizedUri = stripContextPath(contextPath, requestURI);-// API routes are never static except for the public status endpointif (normalizedUri.startsWith("/api/")) {return normalizedUri.startsWith("/api/v1/info/status");@@ -96,12 +98,11 @@ public class RequestUriUtils {}public static boolean isFrontendRoute(String contextPath, String requestURI) {- if (requestURI == null) {+ String normalizedUri = normalizeUriOrNull(contextPath, requestURI);+ if (normalizedUri == null) {return false;}- String normalizedUri = stripContextPath(contextPath, requestURI);-// APIs are never treated as frontend routesif (normalizedUri.startsWith("/api/")) {return false;@@ -180,11 +181,10 @@ public class RequestUriUtils {* @return true if the endpoint is public and doesn't require authentication*/public static boolean isPublicAuthEndpoint(String requestURI, String contextPath) {- // Remove context path from URI to normalize path matching- String trimmedUri =- requestURI.startsWith(contextPath)- ? requestURI.substring(contextPath.length())- : requestURI;+ String trimmedUri = normalizeUriOrNull(contextPath, requestURI);+ if (trimmedUri == null) {+ return false;+ }// Public auth endpoints that don't require authenticationreturn trimmedUri.startsWith("/login")@@ -223,10 +223,30 @@ public class RequestUriUtils {|| INVITE_LINK_PATTERN.matcher(trimmedUri).matches();}- private static String stripContextPath(String contextPath, String requestURI) {- if (contextPath != null && !contextPath.isBlank() && requestURI.startsWith(contextPath)) {- return requestURI.substring(contextPath.length());+ public static String normalizeUri(String contextPath, String requestURI) {+ String decodedUri = UriUtils.decode(requestURI, StandardCharsets.UTF_8);+ if (contextPath != null && !contextPath.isBlank()) {+ String decodedContextPath = UriUtils.decode(contextPath, StandardCharsets.UTF_8);+ if (decodedUri.startsWith(decodedContextPath)) {+ return decodedUri.substring(decodedContextPath.length());+ }+ }+ return decodedUri;+ }++ public static boolean isApiRequest(String contextPath, String requestURI) {+ String normalizedUri = normalizeUriOrNull(contextPath, requestURI);+ return normalizedUri == null || normalizedUri.startsWith("/api/");+ }++ private static String normalizeUriOrNull(String contextPath, String requestURI) {+ if (requestURI == null) {+ return null;+ }+ try {+ return normalizeUri(contextPath, requestURI);+ } catch (IllegalArgumentException e) {+ return null;}- return requestURI;}}diff --git a/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java b/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.javaindex 124671062d..4e7b983046 100644--- a/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java+++ b/app/common/src/test/java/stirling/software/common/annotations/AutoJobPostMappingIntegrationTest.java@@ -10,6 +10,8 @@ import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.util.Optional;+import java.util.concurrent.CompletableFuture;import java.util.function.Supplier;import org.aspectj.lang.ProceedingJoinPoint;@@ -20,7 +22,9 @@ import org.mockito.ArgumentCaptor;import org.mockito.Captor;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.slf4j.MDC;import org.springframework.http.ResponseEntity;+import org.springframework.test.util.ReflectionTestUtils;import org.springframework.web.multipart.MultipartFile;import jakarta.servlet.http.HttpServletRequest;@@ -29,6 +33,7 @@ import stirling.software.common.aop.AutoJobAspect;import stirling.software.common.model.api.PDFFile;import stirling.software.common.service.FileStorage;import stirling.software.common.service.JobExecutorService;+import stirling.software.common.service.JobOwnershipService;@ExtendWith(MockitoExtension.class)class AutoJobPostMappingIntegrationTest {@@ -173,4 +178,30 @@ class AutoJobPostMappingIntegrationTest {verify(fileStorage).storeFile(any(MultipartFile.class));verify(fileStorage).retrieveFile("stored-file-id");}++ @Test+ void shouldCarryCallerToWorkerThreadWhenAuditAspectDidNotStampMdc() throws Throwable {+ MDC.clear();+ JobOwnershipService jobOwnershipService = mock(JobOwnershipService.class);+ when(jobOwnershipService.getCurrentUserId()).thenReturn(Optional.of("alice"));+ ReflectionTestUtils.setField(autoJobAspect, "jobOwnershipService", jobOwnershipService);++ when(joinPoint.getArgs()).thenReturn(new Object[0]);+ when(request.getParameter("async")).thenReturn("false");+ when(autoJobPostMapping.retryCount()).thenReturn(1);+ when(joinPoint.proceed(any())).thenAnswer(invocation -> MDC.get("auditPrincipal"));++ when(jobExecutorService.runJobGeneric(+ anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))+ .thenAnswer(+ invocation -> {+ Supplier<Object> work = invocation.getArgument(1);+ return ResponseEntity.ok(CompletableFuture.supplyAsync(work).get());+ });++ Object result = autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);++ assertEquals(ResponseEntity.ok("alice"), result);+ assertNull(MDC.get("auditPrincipal"), "Request thread MDC should be left untouched");+ }}diff --git a/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.java b/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.javanew file mode 100644index 0000000000..0b98555b42--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/CalibreSandboxPolicyTest.java@@ -0,0 +1,267 @@+package stirling.software.common.util;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Path;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.TimeUnit;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.mockito.MockedConstruction;+import org.mockito.MockedStatic;+import org.mockito.Mockito;++import stirling.software.common.util.CalibreSandboxPolicy.Mode;++class CalibreSandboxPolicyTest {++ private static final Path LAUNCHER = Path.of("/configs/scripts/python/calibre_sandbox.py");+ private static final String LEAKED_SECRET = "13d99fb9-25db-44bc-beb5-1c504957b9df";++ @TempDir Path workDir;++ private List<String> command;+ private List<String> confinedCommand;+ private MockedStatic<GeneralUtils> generalUtils;+ private MockedStatic<CheckProgramInstall> checkProgramInstall;++ @BeforeEach+ void setUp() {+ command =+ List.of(+ "ebook-convert",+ workDir.resolve("book.mobi").toString(),+ workDir.resolve("book.pdf").toString());+ confinedCommand =+ List.of(+ "python3",+ "-I",+ LAUNCHER.toString(),+ workDir.toString(),+ command.get(0),+ command.get(1),+ command.get(2));+ generalUtils = Mockito.mockStatic(GeneralUtils.class);+ generalUtils+ .when(() -> GeneralUtils.extractScript(CalibreSandboxPolicy.LAUNCHER))+ .thenReturn(LAUNCHER);+ checkProgramInstall = Mockito.mockStatic(CheckProgramInstall.class);+ checkProgramInstall+ .when(CheckProgramInstall::getAvailablePythonCommand)+ .thenReturn("python3");+ }++ @AfterEach+ void tearDown() {+ checkProgramInstall.close();+ generalUtils.close();+ ProcessExecutor.setCalibreSandboxMode(CalibreSandboxPolicy.configuredMode());+ }++ @Test+ void sandboxEnforcesByDefaultWhereItIsExpected() {+ assertThat(CalibreSandboxPolicy.resolveMode(null, true)).isEqualTo(Mode.ENFORCE);+ assertThat(CalibreSandboxPolicy.resolveMode(" ", true)).isEqualTo(Mode.ENFORCE);+ assertThat(CalibreSandboxPolicy.resolveMode(null, false)).isEqualTo(Mode.UNSUPPORTED);+ }++ @Test+ void configuredModeIsHonouredAndUnknownValuesEnforce() {+ assertThat(CalibreSandboxPolicy.resolveMode("off", true)).isEqualTo(Mode.OFF);+ assertThat(CalibreSandboxPolicy.resolveMode("ENFORCE", true)).isEqualTo(Mode.ENFORCE);+ assertThat(CalibreSandboxPolicy.resolveMode("required", false)).isEqualTo(Mode.REQUIRED);+ assertThat(CalibreSandboxPolicy.resolveMode("disabled", true)).isEqualTo(Mode.ENFORCE);+ }++ @Test+ void commandIsWrappedInTheLauncherAndConfinedToTheWorkingDirectory() throws IOException {+ for (Mode mode : List.of(Mode.ENFORCE, Mode.REQUIRED)) {+ assertThat(+ CalibreSandboxPolicy.confine(+ mode, command, workDir.toFile(), new HashMap<>()))+ .isEqualTo(confinedCommand);+ }+ }++ @Test+ void unconfinedModesLeaveTheCommandAlone() throws IOException {+ for (Mode mode : List.of(Mode.OFF, Mode.UNSUPPORTED)) {+ assertThat(+ CalibreSandboxPolicy.confine(+ mode, command, workDir.toFile(), new HashMap<>()))+ .isEqualTo(command);+ }+ }++ @Test+ void secretsInTheEnvironmentDoNotReachCalibre() throws IOException {+ Map<String, String> env = new HashMap<>();+ env.put("SECURITY_CUSTOMGLOBALAPIKEY", "secret");+ env.put("PYTHONPATH", "/opt/venv/lib/python3.12/site-packages");+ env.put("XDG_CONFIG_HOME", "/home/stirlingpdfuser/.config");+ env.put("HOME", "/home/stirlingpdfuser");+ env.put("TMPDIR", "/tmp/stirling-pdf");+ env.put("PATH", "/usr/bin");+ env.put("LC_ALL", "C.UTF-8");+ env.put("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu");++ CalibreSandboxPolicy.confine(Mode.REQUIRED, command, workDir.toFile(), env);++ String home = workDir.resolve(".calibre").toString();+ assertThat(env)+ .containsOnly(+ Map.entry("HOME", home),+ Map.entry("TMPDIR", home),+ Map.entry("TMP", home),+ Map.entry("TEMP", home),+ Map.entry("XDG_RUNTIME_DIR", home),+ Map.entry("PATH", "/usr/bin"),+ Map.entry("LC_ALL", "C.UTF-8"),+ Map.entry("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-gpu"),+ Map.entry(CalibreSandboxPolicy.MODE_VARIABLE, "required"));+ assertThat(Path.of(home)).isDirectory();+ }++ @Test+ void aJobWithoutAWorkingDirectoryIsRefused() {+ assertThatThrownBy(+ () ->+ CalibreSandboxPolicy.confine(+ Mode.REQUIRED, command, null, new HashMap<>()))+ .isInstanceOf(IOException.class)+ .hasMessageContaining("working directory");+ }++ @Test+ void withoutPythonARequiredSandboxRefusesToRunCalibre() {+ checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);++ assertThatThrownBy(+ () ->+ CalibreSandboxPolicy.confine(+ Mode.REQUIRED, command, workDir.toFile(), new HashMap<>()))+ .isInstanceOf(IOException.class)+ .hasMessage(CalibreSandboxPolicy.REFUSED_MESSAGE);+ }++ @Test+ void withoutPythonAnEnforcedSandboxRunsCalibreUnconfined() throws IOException {+ checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);++ assertThat(+ CalibreSandboxPolicy.confine(+ Mode.ENFORCE, command, workDir.toFile(), new HashMap<>()))+ .isEqualTo(command);+ }++ private static MockedConstruction<ProcessBuilder> calibre(int exitCode, String stderr) {+ return Mockito.mockConstruction(+ ProcessBuilder.class,+ (builder, context) -> {+ Process process = mock(Process.class);+ when(process.getInputStream())+ .thenReturn(new ByteArrayInputStream(new byte[0]));+ when(process.getErrorStream())+ .thenReturn(+ new ByteArrayInputStream(+ stderr.getBytes(StandardCharsets.UTF_8)));+ when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true);+ when(process.exitValue()).thenReturn(exitCode);+ when(builder.environment()).thenReturn(new HashMap<>());+ when(builder.start()).thenReturn(process);+ });+ }++ private void runCalibre() throws Exception {+ ProcessExecutor.getInstance(ProcessExecutor.Processes.CALIBRE)+ .runCommandWithOutputHandling(command, workDir.toFile());+ }++ @Test+ void processExecutorLaunchesCalibreConfined() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ runCalibre();++ verify(builders.constructed().getFirst()).command(confinedCommand);+ }+ }++ @Test+ void bareInstallLaunchesCalibreUnchanged() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.UNSUPPORTED);+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ runCalibre();++ verify(builders.constructed().getFirst()).command(command);+ }+ }++ @Test+ void processExecutorDoesNotStartCalibreWhenTheRequiredSandboxNeedsMissingPython()+ throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ checkProgramInstall.when(CheckProgramInstall::getAvailablePythonCommand).thenReturn(null);+ try (MockedConstruction<ProcessBuilder> builders = calibre(0, "")) {+ assertThatThrownBy(this::runCalibre)+ .isInstanceOf(IOException.class)+ .hasMessage(CalibreSandboxPolicy.REFUSED_MESSAGE);++ verify(builders.constructed().getFirst(), never()).start();+ }+ }++ @Test+ void launcherRefusalOnAKernelWithoutLandlockFailsTheJob() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ try (MockedConstruction<ProcessBuilder> ignored =+ calibre(+ CalibreSandboxPolicy.LAUNCHER_REFUSED_EXIT_CODE,+ "calibre-sandbox: landlock unavailable, filesystem unconfined\n")) {+ assertThatThrownBy(this::runCalibre)+ .isInstanceOf(IOException.class)+ .hasMessage(CalibreSandboxPolicy.REFUSED_MESSAGE);+ }+ }++ @Test+ void partialConfinementUnderEnforceStillConverts() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.ENFORCE);+ try (MockedConstruction<ProcessBuilder> ignored =+ calibre(0, "calibre-sandbox: seccomp unavailable, network unconfined\n")) {+ runCalibre();+ }+ }++ @Test+ void calibreErrorOutputIsNotPutInTheExceptionMessage() throws Exception {+ ProcessExecutor.setCalibreSandboxMode(Mode.REQUIRED);+ String stderr =+ "Could not find file missing.png in book\n"+ + "Could not find file uuid-in-the-copy/"+ + LEAKED_SECRET+ + " in book\n";+ try (MockedConstruction<ProcessBuilder> ignored = calibre(134, stderr)) {+ assertThatThrownBy(this::runCalibre)+ .isInstanceOf(IOException.class)+ .hasMessage("Calibre conversion failed with exit code 134")+ .message()+ .doesNotContain(LEAKED_SECRET);+ }+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/CustomHtmlSanitizerTest.java b/app/common/src/test/java/stirling/software/common/util/CustomHtmlSanitizerTest.javaindex 00ae5878fc..b536d0e032 100644--- a/app/common/src/test/java/stirling/software/common/util/CustomHtmlSanitizerTest.java+++ b/app/common/src/test/java/stirling/software/common/util/CustomHtmlSanitizerTest.java@@ -206,6 +206,31 @@ class CustomHtmlSanitizerTest {"Data URLs with potentially malicious content should be removed");}+ @Test+ void testSanitizeKeepsRasterDataUrlImages() {+ String html = "<img src=\"data:image/png;base64,iVBORw0KGgo=\" alt=\"logo\">";++ String sanitizedHtml = customHtmlSanitizer.sanitize(html);++ assertTrue(sanitizedHtml.contains("src=\"data:image/png;base64,iVBORw0KGgo=\""));+ }++ @ParameterizedTest+ @MethodSource("nonRasterDataUrls")+ void testSanitizeDropsNonRasterDataUrlImages(String src) {+ String sanitizedHtml = customHtmlSanitizer.sanitize("<img src=\"" + src + "\" alt=\"x\">");++ assertFalse(sanitizedHtml.contains("src="), sanitizedHtml);+ }++ private static Stream<String> nonRasterDataUrls() {+ return Stream.of(+ "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=",+ "data:image/svg+xml,%3Csvg%3E%3C/svg%3E",+ "data:text/html;base64,PGI+eDwvYj4=",+ "data:,plain");+ }+@Testvoid testSanitizeRemovesJavaScriptInAttributes() {// Arrangediff --git a/app/common/src/test/java/stirling/software/common/util/FileToPdfMoreTest.java b/app/common/src/test/java/stirling/software/common/util/FileToPdfMoreTest.javaindex 04e66f31f9..8af9b62b2f 100644--- a/app/common/src/test/java/stirling/software/common/util/FileToPdfMoreTest.java+++ b/app/common/src/test/java/stirling/software/common/util/FileToPdfMoreTest.java@@ -9,10 +9,11 @@ import static org.mockito.Mockito.when;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;import java.nio.file.Path;+import java.util.Base64;import java.util.List;import java.util.zip.ZipEntry;-import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;import org.junit.jupiter.api.BeforeEach;@@ -170,33 +171,22 @@ class FileToPdfMoreTest {}@Test- @DisplayName("non-html entries inside the ZIP are copied through unchanged")- void zipNonHtmlCopied() throws Exception {+ @DisplayName("a ZIP with no HTML document is rejected before any process is started")+ void zipWithoutHtmlRejected() throws Exception {byte[] zip = buildZip(new String[] {"data.txt"}, new String[] {"plain text content"});- ProcessExecutor executor = mock(ProcessExecutor.class);- Mockito.doReturn(successResult())- .when(executor)- .runCommandWithOutputHandling(anyList());-try (MockedStatic<ProcessExecutor> mocked = Mockito.mockStatic(ProcessExecutor.class)) {- mocked.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT))- .thenReturn(executor);-- // Drop the identity-stub invocation recorded during setUp.- Mockito.clearInvocations(sanitizer);-- byte[] result =- FileToPdf.convertHtmlToPdf(- "weasyprint",- new HTMLToPdfRequest(),- zip,- "bundle.zip",- tempFileManager,- sanitizer);-- assertThat(result).isNotNull();- Mockito.verifyNoInteractions(sanitizer);+ assertThatThrownBy(+ () ->+ FileToPdf.convertHtmlToPdf(+ "weasyprint",+ new HTMLToPdfRequest(),+ zip,+ "bundle.zip",+ tempFileManager,+ sanitizer))+ .isInstanceOf(IllegalArgumentException.class);+ mocked.verifyNoInteractions();}}}@@ -239,50 +229,163 @@ class FileToPdfMoreTest {}}+ private CapturedRun run(byte[] input, String fileName) throws Exception {+ CapturedRun captured = new CapturedRun();+ ProcessExecutor executor = mock(ProcessExecutor.class);+ Mockito.doAnswer(+ invocation -> {+ List<String> command = invocation.getArgument(0);+ captured.command = List.copyOf(command);+ captured.html =+ Files.readString(Path.of(command.get(command.size() - 2)));+ return successResult();+ })+ .when(executor)+ .runCommandWithOutputHandling(anyList());++ try (MockedStatic<ProcessExecutor> mocked = Mockito.mockStatic(ProcessExecutor.class)) {+ mocked.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT))+ .thenReturn(executor);+ FileToPdf.convertHtmlToPdf(+ "weasyprint",+ new HTMLToPdfRequest(),+ input,+ fileName,+ tempFileManager,+ sanitizer);+ }+ return captured;+ }++ private static final class CapturedRun {+ List<String> command;+ String html;+ }+@Nested- @DisplayName("repacked ZIP integrity")- class RepackedZipTests {+ @DisplayName("WeasyPrint input hardening")+ class WeasyPrintInputTests {@Test- @DisplayName("the temp input zip handed to weasyprint still contains the html entry")- void repackedZipContainsEntry() throws Exception {- byte[] zip = buildZip(new String[] {"a.html"}, new String[] {"<i>hi</i>"});+ @DisplayName("sanitized HTML input may only fetch data: URIs")+ void htmlRestrictsProtocols() throws Exception {+ CapturedRun run = run("<p>x</p>".getBytes(StandardCharsets.UTF_8), "page.html");- // Inspect the repacked zip from inside the command answer, while the temp file is- // still on disk (it is auto-deleted once convertHtmlToPdf returns).- List<String> entryNames = new java.util.ArrayList<>();- ProcessExecutor executor = mock(ProcessExecutor.class);- Mockito.doAnswer(- invocation -> {- List<String> command = invocation.getArgument(0);- Path inputZip = Path.of(command.get(command.size() - 2));- try (ZipInputStream zis =- new ZipInputStream(- java.nio.file.Files.newInputStream(inputZip))) {- ZipEntry entry;- while ((entry = zis.getNextEntry()) != null) {- entryNames.add(entry.getName());- }- }- return successResult();- })- .when(executor)- .runCommandWithOutputHandling(anyList());+ int flag = run.command.indexOf("--allowed-protocols");+ assertThat(flag).isPositive();+ assertThat(run.command.get(flag + 1)).isEqualTo("data");+ }- try (MockedStatic<ProcessExecutor> mocked = Mockito.mockStatic(ProcessExecutor.class)) {- mocked.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT))- .thenReturn(executor);+ @Test+ @DisplayName("unsanitized HTML input may fetch http(s) but never file:")+ void unsanitizedHtmlExcludesFileProtocol() throws Exception {+ when(sanitizer.isDisabled()).thenReturn(true);- FileToPdf.convertHtmlToPdf(- "weasyprint",- new HTMLToPdfRequest(),- zip,- "bundle.zip",- tempFileManager,- sanitizer);+ CapturedRun run = run("<p>x</p>".getBytes(StandardCharsets.UTF_8), "page.html");- assertThat(entryNames).anyMatch(name -> name.endsWith("a.html"));- }+ int flag = run.command.indexOf("--allowed-protocols");+ assertThat(run.command.get(flag + 1)).isEqualTo("data,http,https");+ }++ @Test+ @DisplayName("ZIP input hands WeasyPrint the main HTML document, never the archive")+ void zipPassesHtmlNotArchive() throws Exception {+ byte[] zip =+ buildZip(+ new String[] {"other.html", "index.html", "style.css"},+ new String[] {"<p>other</p>", "<p>main</p>", "p{}"});++ CapturedRun run = run(zip, "bundle.zip");++ assertThat(run.command.get(run.command.size() - 2)).endsWith(".html");+ assertThat(run.command).contains("--allowed-protocols", "data");+ assertThat(run.html).isEqualTo("<p>main</p>");+ }++ @Test+ @DisplayName("markup in ZIP entry names never reaches the WeasyPrint input")+ void entryNamesNotParsedAsMarkup() throws Exception {+ String markupName = "<link rel=attachment href=\"file:/tmp/canary.txt\">";+ byte[] zip =+ buildZip(+ new String[] {"index.html", markupName},+ new String[] {"<p>main</p>", "x"});++ CapturedRun run = run(zip, "bundle.zip");++ assertThat(run.html).isEqualTo("<p>main</p>");+ }++ @Test+ @DisplayName("relative images in the archive are inlined as data URIs")+ void relativeImagesInlined() throws Exception {+ byte[] zip =+ buildZip(+ new String[] {"site/index.html", "site/img/a b.png"},+ new String[] {"<img src=\"img/a%20b.png\" />", "PNGDATA"});++ CapturedRun run = run(zip, "bundle.zip");++ String expected =+ Base64.getEncoder().encodeToString("PNGDATA".getBytes(StandardCharsets.UTF_8));+ assertThat(run.html)+ .isEqualTo("<img src=\"data:image/png;base64," + expected + "\" />");+ }++ @Test+ @DisplayName("archive images are inlined before sanitizing, so relative src survives it")+ void imagesInlinedBeforeSanitizing() throws Exception {+ byte[] zip =+ buildZip(+ new String[] {"index.html", "logo.png"},+ new String[] {"<img src=logo.png>", "PNGDATA"});++ run(zip, "bundle.zip");++ String expected =+ Base64.getEncoder().encodeToString("PNGDATA".getBytes(StandardCharsets.UTF_8));+ Mockito.verify(sanitizer)+ .sanitize("<img src=\"data:image/png;base64," + expected + "\">");+ }++ @Test+ @DisplayName("image references outside the archive are left for WeasyPrint to refuse")+ void traversalImageNotInlined() throws Exception {+ String html = "<img src=\"../../tmp/canary.png\" />";+ byte[] zip = buildZip(new String[] {"index.html"}, new String[] {html});++ CapturedRun run = run(zip, "bundle.zip");++ assertThat(run.html).isEqualTo(html);+ }+ }++ @Nested+ @DisplayName("entry name helpers")+ class EntryNameHelperTests {++ @Test+ @DisplayName("markup characters are replaced in stored entry names")+ void markupCharactersReplaced() {+ assertThat(FileToPdf.sanitizeZipFilename("<link href=\"file:/x\">.png"))+ .matches("[A-Za-z0-9._/-]+");+ }++ @Test+ @DisplayName("a root index.html is preferred, otherwise the shallowest HTML file")+ void selectsMainHtml() {+ assertThat(FileToPdf.selectMainHtml(List.of("b/x.html", "a.htm", "index.html")))+ .isEqualTo("index.html");+ assertThat(FileToPdf.selectMainHtml(List.of("b/x.html", "z.html", "a.css")))+ .isEqualTo("z.html");+ assertThat(FileToPdf.selectMainHtml(List.of("a.css"))).isNull();+ }++ @Test+ @DisplayName("paths that climb out of the archive normalize to null")+ void normalizeRejectsEscape() {+ assertThat(FileToPdf.normalizeEntryPath("a/./b/../c.png")).isEqualTo("a/c.png");+ assertThat(FileToPdf.normalizeEntryPath("../c.png")).isNull();}}}diff --git a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.javaindex cf05569b62..e0efa53f30 100644--- a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java+++ b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java@@ -58,6 +58,12 @@ class RequestUriUtilsTest {assertFalse(RequestUriUtils.isStaticResource("/api/v1/convert"));}+ @Test+ void testIsStaticResource_percentEncodedApiRoute_notStatic() {+ assertFalse(RequestUriUtils.isStaticResource("/%61pi/v1/general/files/report.png"));+ assertFalse(RequestUriUtils.isStaticResource("/app", "/%61pp/a%70i/v1/x.js"));+ }+@Testvoid testIsStaticResource_apiStatusEndpoint() {assertTrue(RequestUriUtils.isStaticResource("/api/v1/info/status"));@@ -100,6 +106,15 @@ class RequestUriUtilsTest {assertFalse(RequestUriUtils.isFrontendRoute("", "/api/v1/convert"));}+ @Test+ void testIsFrontendRoute_percentEncodedApiPath() {+ assertFalse(RequestUriUtils.isFrontendRoute("", "/%61pi/v1/info/load/all"));+ assertFalse(RequestUriUtils.isFrontendRoute("", "/a%70%69/v1/info/load/all"));+ assertFalse(RequestUriUtils.isFrontendRoute("/app", "/app/%61pi/v1/info/load/all"));+ assertFalse(RequestUriUtils.isFrontendRoute("/app", "/%61pp/api/v1/info/load/all"));+ assertFalse(RequestUriUtils.isFrontendRoute("", "/%61ctuator/prometheus"));+ }+@Testvoid testIsFrontendRoute_backendOnlyPath() {assertFalse(RequestUriUtils.isFrontendRoute("", "/swagger"));@@ -359,4 +374,79 @@ class RequestUriUtilsTest {RequestUriUtils.isPublicAuthEndpoint("/invite/06a20e7e-2e35-4e26-be7d-2dce14f28f1g", ""));}++ @Test+ void testNormalizeUri_decodesAndStripsContextPath() {+ assertEquals(+ "/api/v1/info/load/all",+ RequestUriUtils.normalizeUri("", "/%61pi/v1/info/load/all"));+ assertEquals(+ "/api/v1/info/load/all",+ RequestUriUtils.normalizeUri(null, "/%61pi/v1/info/load/all"));+ assertEquals(+ "/actuator/prometheus", RequestUriUtils.normalizeUri("", "/%61ctuator/prometheus"));+ assertEquals("/api/x.png", RequestUriUtils.normalizeUri("", "/a%70i/x.png"));+ assertEquals("/api/v1/x", RequestUriUtils.normalizeUri("/app", "/app/%61pi/v1/x"));+ assertEquals("/api/v1/x", RequestUriUtils.normalizeUri("/app", "/%61pp/api/v1/x"));+ assertEquals("/files/abc", RequestUriUtils.normalizeUri("/app", "/app/files/abc"));+ assertEquals("/", RequestUriUtils.normalizeUri("", "/"));+ }++ @Test+ void testNormalizeUri_malformedEscapeThrows() {+ assertThrows(+ IllegalArgumentException.class, () -> RequestUriUtils.normalizeUri("", "/%zz"));+ assertThrows(+ IllegalArgumentException.class, () -> RequestUriUtils.normalizeUri("", "/api%"));+ }++ @Test+ void testEncodedApiPaths_areNeitherPublicNorFrontend() {+ for (String uri :+ new String[] {+ "/%61pi/v1/info/load/all", "/%61ctuator/prometheus", "/a%70i/x.png"+ }) {+ assertFalse(RequestUriUtils.isFrontendRoute("", uri), uri);+ assertFalse(RequestUriUtils.isStaticResource("", uri), uri);+ assertFalse(RequestUriUtils.isPublicAuthEndpoint(uri, ""), uri);+ assertFalse(RequestUriUtils.isFrontendRoute("/app", "/app" + uri), uri);+ assertFalse(RequestUriUtils.isStaticResource("/app", "/app" + uri), uri);+ assertFalse(RequestUriUtils.isPublicAuthEndpoint("/app" + uri, "/app"), uri);+ }+ }++ @Test+ void testMalformedEscape_failsClosed() {+ assertFalse(RequestUriUtils.isFrontendRoute("", "/%zz"));+ assertFalse(RequestUriUtils.isStaticResource("", "/%zz.png"));+ assertFalse(RequestUriUtils.isPublicAuthEndpoint("/login%zz", ""));+ assertTrue(RequestUriUtils.isApiRequest("", "/%zz"));+ }++ @Test+ void testIsApiRequest() {+ assertTrue(RequestUriUtils.isApiRequest("", "/api/v1/info/load/all"));+ assertTrue(RequestUriUtils.isApiRequest("", "/%61pi/v1/info/load/all"));+ assertTrue(RequestUriUtils.isApiRequest("/app", "/app/a%70i/v1/x"));+ assertFalse(RequestUriUtils.isApiRequest("", "/"));+ assertFalse(RequestUriUtils.isApiRequest("", "/login"));+ assertFalse(RequestUriUtils.isApiRequest("/app", "/app/files/abc"));+ }++ @Test+ void testLegitimateRoutes_classifyAsBefore() {+ for (String ctx : new String[] {"", "/app"}) {+ assertTrue(RequestUriUtils.isFrontendRoute(ctx, ctx + "/"), ctx);+ assertTrue(RequestUriUtils.isFrontendRoute(ctx, ctx + "/files/abc"), ctx);+ assertTrue(RequestUriUtils.isFrontendRoute(ctx, ctx + "/processor"), ctx);+ assertTrue(RequestUriUtils.isStaticResource(ctx, ctx + "/login"), ctx);+ assertTrue(RequestUriUtils.isStaticResource(ctx, ctx + "/processor"), ctx);+ assertTrue(RequestUriUtils.isPublicAuthEndpoint(ctx + "/login", ctx), ctx);+ assertTrue(RequestUriUtils.isStaticResource(ctx, ctx + "/api/v1/info/status"), ctx);+ assertFalse(RequestUriUtils.isFrontendRoute(ctx, ctx + "/api/v1/info/load/all"), ctx);+ assertFalse(RequestUriUtils.isFrontendRoute(ctx, ctx + "/actuator/prometheus"), ctx);+ assertFalse(+ RequestUriUtils.isPublicAuthEndpoint(ctx + "/api/v1/info/load/all", ctx), ctx);+ }+ }}diff --git a/app/core/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java b/app/core/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.javaindex db1e718c5d..1f1956315a 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java@@ -9,6 +9,8 @@ import jakarta.servlet.http.HttpServletResponse;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;+import stirling.software.common.util.RequestUriUtils;+@Component@Slf4j@RequiredArgsConstructor@@ -20,7 +22,14 @@ public class EndpointInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {- String requestURI = request.getRequestURI();+ String requestURI;+ try {+ requestURI =+ RequestUriUtils.normalizeUri(request.getContextPath(), request.getRequestURI());+ } catch (IllegalArgumentException e) {+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);+ return false;+ }// Prevent API responses from being stored by browsers or intermediary caches by defaultString servletPath = request.getServletPath();diff --git a/app/core/src/main/java/stirling/software/SPDF/config/MetricsFilter.java b/app/core/src/main/java/stirling/software/SPDF/config/MetricsFilter.javaindex 7813222e2a..be8920ed2c 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/MetricsFilter.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/MetricsFilter.java@@ -4,6 +4,7 @@ import java.io.IOException;import org.springframework.stereotype.Component;import org.springframework.web.filter.OncePerRequestFilter;+import org.springframework.web.servlet.HandlerMapping;import io.micrometer.core.instrument.Counter;import io.micrometer.core.instrument.MeterRegistry;@@ -28,21 +29,46 @@ public class MetricsFilter extends OncePerRequestFilter {protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {- String uri = request.getRequestURI();-- if (RequestUriUtils.isTrackableResource(request.getContextPath(), uri)) {- HttpSession session = request.getSession(false);- String sessionId = (session != null) ? session.getId() : "no-session";- Counter counter =- Counter.builder("http.requests")- .tag("session", sessionId)- .tag("method", request.getMethod())- .tag("uri", uri)- .register(meterRegistry);-- counter.increment();+ if (!RequestUriUtils.isTrackableResource(+ request.getContextPath(), request.getRequestURI())) {+ filterChain.doFilter(request, response);+ return;}- filterChain.doFilter(request, response);+ try {+ filterChain.doFilter(request, response);+ } finally {+ String uri = countedUri(request);++ if (uri != null) {+ HttpSession session = request.getSession(false);+ String sessionId = (session != null) ? session.getId() : "no-session";+ Counter counter =+ Counter.builder("http.requests")+ .tag("session", sessionId)+ .tag("method", request.getMethod())+ .tag("uri", uri)+ .register(meterRegistry);++ counter.increment();+ }+ }+ }++ private static String countedUri(HttpServletRequest request) {+ String contextPath = request.getContextPath();+ String requestUri = request.getRequestURI();+ String path =+ requestUri.startsWith(contextPath)+ ? requestUri.substring(contextPath.length())+ : requestUri;++ if (path.startsWith("/api/")) {+ Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);+ return pattern instanceof String s && s.startsWith("/api/") ? contextPath + s : null;+ }++ int secondSlash = path.indexOf('/', 1);+ return contextPath + (secondSlash < 0 ? path : path.substring(0, secondSlash));}}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.javaindex a835fc4307..f6733bb0e0 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java@@ -33,6 +33,7 @@ import stirling.software.common.model.tool.ToolFormat;import stirling.software.common.model.tool.ToolIO;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.util.GeneralUtils;+import stirling.software.common.util.OfficeDocumentSanitizer;import stirling.software.common.util.ProcessExecutor;import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;import stirling.software.common.util.TempFile;@@ -50,6 +51,7 @@ public class ConvertEbookToPDFController {private final CustomPDFDocumentFactory pdfDocumentFactory;private final TempFileManager tempFileManager;private final EndpointConfiguration endpointConfiguration;+ private final OfficeDocumentSanitizer officeDocumentSanitizer;private boolean isCalibreEnabled() {return endpointConfiguration.isGroupEnabled("Calibre");@@ -115,8 +117,14 @@ public class ConvertEbookToPDFController {Path inputPath = workingDirectory.resolve(baseName + "." + lowerExtension);Path outputPath = workingDirectory.resolve(baseName + ".pdf");- try (InputStream inputStream = inputFile.getInputStream()) {- Files.copy(inputStream, inputPath, StandardCopyOption.REPLACE_EXISTING);+ if (officeDocumentSanitizer.isSanitizableExtension(lowerExtension)) {+ Files.write(+ inputPath,+ officeDocumentSanitizer.sanitize(inputFile.getBytes(), lowerExtension));+ } else {+ try (InputStream inputStream = inputFile.getInputStream()) {+ Files.copy(inputStream, inputPath, StandardCopyOption.REPLACE_EXISTING);+ }}List<String> command =@@ -135,11 +143,7 @@ public class ConvertEbookToPDFController {}if (result.getRc() != 0) {- String errorMessage = result.getMessages();- if (errorMessage == null || errorMessage.isBlank()) {- errorMessage = "Calibre conversion failed";- }- throw new IllegalStateException(errorMessage);+ throw new IllegalStateException("Calibre conversion failed");}if (!Files.exists(outputPath) || Files.size(outputPath) == 0L) {diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.javaindex c95c2b932f..0788402480 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java@@ -157,11 +157,7 @@ public class ConvertPDFToEpubController {}if (result.getRc() != 0) {- String errorMessage = result.getMessages();- if (errorMessage == null || errorMessage.isBlank()) {- errorMessage = "Calibre conversion failed";- }- throw new IllegalStateException(errorMessage);+ throw new IllegalStateException("Calibre conversion failed");}if (!Files.exists(outputPath) || Files.size(outputPath) == 0L) {diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.javaindex 1902dcf053..659fdc8dd8 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java@@ -138,6 +138,8 @@ public class ConvertWebsiteToPDF {command.add("--base-url");command.add(URL);command.add("--pdf-forms");+ command.add("--allowed-protocols");+ command.add("data,http,https");command.add(tempOutputFile.toString());ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT)diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.javaindex bd613ab844..84c57ed4e8 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessor.java@@ -6,6 +6,7 @@ import java.nio.file.FileSystemException;import java.nio.file.FileVisitOption;import java.nio.file.FileVisitResult;import java.nio.file.Files;+import java.nio.file.InvalidPathException;import java.nio.file.Path;import java.nio.file.SimpleFileVisitor;import java.nio.file.StandardCopyOption;@@ -443,15 +444,35 @@ public class PipelineDirectoryProcessor {return outputFileName;}- private Path determineOutputPath(PipelineConfig config, Path dir) {+ Path determineOutputPath(PipelineConfig config, Path dir) {+ Path outputRoot = Path.of(finishedFoldersDir).toAbsolutePath().normalize();+ String configured = config.getOutputDir();+ if (configured == null || configured.isBlank()) {+ return outputRoot;+ }String outputDir =WATCHED_FOLDERS_PATTERN.matcher(- config.getOutputDir()+ configured.replace("{outputFolder}", finishedFoldersDir).replace("{folderName}", dir.toString())).replaceAll("");- return Path.of(outputDir).isAbsolute() ? Path.of(outputDir) : Path.of(".", outputDir);+ Path resolved;+ try {+ resolved = Path.of(outputDir).toAbsolutePath().normalize();+ } catch (InvalidPathException e) {+ log.warn("Ignoring invalid outputDir '{}' in {}", configured, dir);+ return outputRoot;+ }+ if (!resolved.startsWith(outputRoot)) {+ log.warn(+ "Ignoring outputDir '{}' in {}: it resolves outside {}",+ configured,+ dir,+ outputRoot);+ return outputRoot;+ }+ return resolved;}private void deleteOriginalFiles(List<File> filesToProcess, Path processingDir)diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.javaindex bc2e49853e..ff5fcc527e 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.java@@ -2282,7 +2282,14 @@ public class PdfJsonConversionService {String webFormat = null;String pdfBase64 = null;String pdfFormat = null;- if (format != null && isCffFormat(format)) {+ boolean labelledCff = format != null && isCffFormat(format);+ boolean cffProgram = labelledCff && fontService.isCffFontProgram(data);+ if (labelledCff && !cffProgram) {+ log.warn(+ "Font program labelled {} has no CFF header; skipping CFF conversion",+ format);+ }+ if (cffProgram) {log.debug("[FONT-DEBUG] Font is CFF format, attempting conversion. CFF conversion enabled: {}, method: {}",fontService.isCffConversionEnabled(),diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.javaindex e47c18ff48..2cca1a535d 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java@@ -82,9 +82,15 @@ public class JobOwnershipServiceImplpublic boolean validateJobAccess(String scopedJobKey) {Optional<String> userId = getCurrentUserId();- // If no user authenticated, allow access (backwards compatibility)if (userId.isEmpty()) {- log.debug("No authentication required, allowing access to job: {}", scopedJobKey);+ if (keyCarriesOwner(scopedJobKey)) {+ log.warn(+ "Access denied: no authenticated user resolved for owned job key {}",+ scopedJobKey);+ throw new SecurityException(+ "Access denied: You do not have permission to access this job");+ }+ log.debug("Unowned job key with no user, allowing access to job: {}", scopedJobKey);return true;}@@ -116,4 +122,8 @@ public class JobOwnershipServiceImpl}return scopedJobKey;}++ private boolean keyCarriesOwner(String scopedJobKey) {+ return scopedJobKey != null && scopedJobKey.indexOf(':') > 0;+ }}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.javaindex ee6217de0d..3cd7fa4acb 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.java@@ -193,6 +193,20 @@ public class PdfJsonFontService {return null;}+ public boolean isCffFontProgram(byte[] fontBytes) {+ if (fontBytes == null || fontBytes.length < 4) {+ return false;+ }+ int majorVersion = fontBytes[0] & 0xFF;+ int headerSize = fontBytes[2] & 0xFF;+ int offsetSize = fontBytes[3] & 0xFF;+ return majorVersion == 1+ && headerSize >= 4+ && headerSize <= fontBytes.length+ && offsetSize >= 1+ && offsetSize <= 4;+ }+private byte[] convertCffUsingPython(byte[] fontBytes, String toUnicode) {if (!pythonCffConverterAvailable) {log.debug("[FONT-DEBUG] Python CFF converter not available");@@ -274,6 +288,10 @@ public class PdfJsonFontService {log.debug("FontForge CFF converter not available");return null;}+ if (!isCffFontProgram(fontBytes)) {+ log.warn("Font program labelled as CFF has no CFF header; skipping FontForge");+ return null;+ }try (TempFile inputFile = new TempFile(tempFileManager, ".cff");TempFile outputFile = new TempFile(tempFileManager, ".ttf")) {diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 267e4d07d2..810f4693df 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -437,10 +437,10 @@ policies:# security boundary. On a multi-user server EVERY authenticated user (not only team leaders) can# attach folder processing to directories under these roots - listing their contents and replacing# files in place - so only list directories all users may touch.- # Leave allowedFolderRoots empty (default) to disable folder sources/outputs,- # other than from directories that are always permitted like server file-storage and watched folders.+ # Leave allowedFolderRoots empty (default) to disable folder sources/outputs.# List absolute directories to permit folder access within them.- # Stirling's own config directory is always off-limits, and folder access is always+ # Stirling's own config directory, the server file-storage directory and the pipeline watched+ # folders are always off-limits, even inside an allowed root, and folder access is always# disabled in SaaS mode.allowedFolderRoots: [] # e.g. ["/data/inbox", "/data/outbox"]scheduleSweepSeconds: 60 # How often (seconds) scheduled policies are checked for being duediff --git a/app/core/src/main/resources/static/python/calibre_sandbox.py b/app/core/src/main/resources/static/python/calibre_sandbox.pynew file mode 100644index 0000000000..66ebf11422--- /dev/null+++ b/app/core/src/main/resources/static/python/calibre_sandbox.py@@ -0,0 +1,222 @@+import ctypes+import errno+import os+import platform+import stat+import struct+import sys++READ_ONLY = (+ "/opt/calibre",+ "/usr",+ "/bin",+ "/lib",+ "/lib64",+ "/etc/fonts",+ "/etc/ld.so.cache",+ "/etc/localtime",+ "/etc/mime.types",+ "/etc/passwd",+ "/etc/nsswitch.conf",+ "/etc/locale.alias",+ "/var/cache/fontconfig",+ "/proc",+ "/sys/devices/system/cpu",+)+READ_WRITE = ("/dev",)++NR_LANDLOCK_CREATE_RULESET = 444+NR_LANDLOCK_ADD_RULE = 445+NR_LANDLOCK_RESTRICT_SELF = 446+LANDLOCK_CREATE_RULESET_VERSION = 1+LANDLOCK_RULE_PATH_BENEATH = 1+ACCESS_FS_EXECUTE = 1 << 0+ACCESS_FS_WRITE_FILE = 1 << 1+ACCESS_FS_READ_FILE = 1 << 2+ACCESS_FS_READ_DIR = 1 << 3+ACCESS_FS_ABI_1 = (1 << 13) - 1+ACCESS_FS_REFER = 1 << 13+ACCESS_FS_TRUNCATE = 1 << 14+ACCESS_FS_IOCTL_DEV = 1 << 15+ACCESS_NET_BIND_TCP = 1 << 0+ACCESS_NET_CONNECT_TCP = 1 << 1+SCOPE_ABSTRACT_UNIX_SOCKET = 1 << 0+SCOPE_SIGNAL = 1 << 1+ACCESS_RO = ACCESS_FS_EXECUTE | ACCESS_FS_READ_FILE | ACCESS_FS_READ_DIR+ACCESS_FILE = ACCESS_FS_EXECUTE | ACCESS_FS_WRITE_FILE | ACCESS_FS_READ_FILE | ACCESS_FS_TRUNCATE | ACCESS_FS_IOCTL_DEV++PR_SET_SECCOMP = 22+PR_SET_NO_NEW_PRIVS = 38+SECCOMP_MODE_FILTER = 2+SECCOMP_RET_KILL_PROCESS = 0x80000000+SECCOMP_RET_ERRNO = 0x00050000+SECCOMP_RET_ALLOW = 0x7FFF0000+X32_SYSCALL_BIT = 0x40000000+AF_UNIX = 1+BPF_LD_W_ABS = 0x20+BPF_JEQ_K = 0x15+BPF_JGE_K = 0x35+BPF_RET_K = 0x06+ARCHITECTURES = {+ "x86_64": {+ "audit_arch": 0xC000003E,+ "socket": 41,+ "socketpair": 53,+ "ptrace": 101,+ "process_vm_readv": 310,+ "process_vm_writev": 311,+ },+ "aarch64": {+ "audit_arch": 0xC00000B7,+ "socket": 198,+ "socketpair": 199,+ "ptrace": 117,+ "process_vm_readv": 270,+ "process_vm_writev": 271,+ },+}+NR_IO_URING_SETUP, NR_IO_URING_ENTER, NR_IO_URING_REGISTER = 425, 426, 427++libc = ctypes.CDLL(None, use_errno=True)+++class RulesetAttr(ctypes.Structure):+ _fields_ = [+ ("handled_access_fs", ctypes.c_uint64),+ ("handled_access_net", ctypes.c_uint64),+ ("scoped", ctypes.c_uint64),+ ]+++class PathBeneathAttr(ctypes.Structure):+ _pack_ = 1+ _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]+++class SockFprog(ctypes.Structure):+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.c_char_p)]+++def call(function, *args):+ args = [ctypes.c_long(arg) if isinstance(arg, int) else arg for arg in args]+ result = function(*args)+ if result < 0:+ raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))+ return result+++def allow(ruleset, path, access):+ try:+ parent = os.open(path, os.O_PATH | os.O_CLOEXEC)+ except OSError:+ return+ try:+ if not stat.S_ISDIR(os.fstat(parent).st_mode):+ access &= ACCESS_FILE+ rule = PathBeneathAttr(access, parent)+ call(+ libc.syscall,+ NR_LANDLOCK_ADD_RULE,+ ruleset,+ LANDLOCK_RULE_PATH_BENEATH,+ ctypes.byref(rule),+ 0,+ )+ finally:+ os.close(parent)+++def confine_file_system(work_dir):+ try:+ abi = call(libc.syscall, NR_LANDLOCK_CREATE_RULESET, None, 0, LANDLOCK_CREATE_RULESET_VERSION)+ except OSError:+ return 0+ access = ACCESS_FS_ABI_1+ if abi >= 2:+ access |= ACCESS_FS_REFER+ if abi >= 3:+ access |= ACCESS_FS_TRUNCATE+ if abi >= 5:+ access |= ACCESS_FS_IOCTL_DEV+ attr = RulesetAttr(access, 0, 0)+ size = ctypes.sizeof(ctypes.c_uint64)+ if abi >= 4:+ attr.handled_access_net = ACCESS_NET_BIND_TCP | ACCESS_NET_CONNECT_TCP+ size = 2 * ctypes.sizeof(ctypes.c_uint64)+ if abi >= 6:+ attr.scoped = SCOPE_ABSTRACT_UNIX_SOCKET | SCOPE_SIGNAL+ size = ctypes.sizeof(attr)+ ruleset = call(libc.syscall, NR_LANDLOCK_CREATE_RULESET, ctypes.byref(attr), size, 0)+ try:+ for path in READ_ONLY:+ allow(ruleset, path, ACCESS_RO)+ for path in (*READ_WRITE, work_dir):+ allow(ruleset, path, access)+ call(libc.syscall, NR_LANDLOCK_RESTRICT_SELF, ruleset, 0)+ finally:+ os.close(ruleset)+ return abi+++def confine_network():+ if platform.machine() not in ARCHITECTURES:+ return False+ nr = ARCHITECTURES[platform.machine()]+ ld, jeq, jge, ret = BPF_LD_W_ABS, BPF_JEQ_K, BPF_JGE_K, BPF_RET_K+ program = [+ (ld, 0, 0, 4),+ (jeq, 1, 0, nr["audit_arch"]),+ (ret, 0, 0, SECCOMP_RET_KILL_PROCESS),+ (ld, 0, 0, 0),+ (jge, 0, 1, X32_SYSCALL_BIT),+ (ret, 0, 0, SECCOMP_RET_KILL_PROCESS),+ (jeq, 9, 0, nr["socket"]),+ (jeq, 8, 0, nr["socketpair"]),+ (jeq, 6, 0, NR_IO_URING_SETUP),+ (jeq, 5, 0, NR_IO_URING_ENTER),+ (jeq, 4, 0, NR_IO_URING_REGISTER),+ (jeq, 3, 0, nr["ptrace"]),+ (jeq, 2, 0, nr["process_vm_readv"]),+ (jeq, 1, 0, nr["process_vm_writev"]),+ (ret, 0, 0, SECCOMP_RET_ALLOW),+ (ret, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),+ (ld, 0, 0, 20),+ (jeq, 1, 0, 0),+ (ret, 0, 0, SECCOMP_RET_ERRNO | errno.EAFNOSUPPORT),+ (ld, 0, 0, 16),+ (jeq, 1, 0, AF_UNIX),+ (ret, 0, 0, SECCOMP_RET_ERRNO | errno.EAFNOSUPPORT),+ (ret, 0, 0, SECCOMP_RET_ALLOW),+ ]+ code = b"".join(struct.pack("HBBI", *instruction) for instruction in program)+ filter_program = SockFprog(len(program), code)+ try:+ call(libc.prctl, PR_SET_SECCOMP, SECCOMP_MODE_FILTER, ctypes.byref(filter_program), 0, 0)+ except OSError as e:+ if e.errno in (errno.ENOSYS, errno.EINVAL):+ return False+ raise+ return True+++def main():+ if len(sys.argv) < 3:+ print("usage: calibre_sandbox.py <working directory> <command...>", file=sys.stderr)+ return 2+ work_dir, command = sys.argv[1], sys.argv[2:]+ required = os.environ.get("STIRLING_CALIBRE_SANDBOX") == "required"++ call(libc.prctl, PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)+ if not confine_file_system(work_dir):+ print("calibre-sandbox: landlock unavailable, filesystem unconfined", file=sys.stderr)+ if required:+ return 125+ if not confine_network():+ print("calibre-sandbox: seccomp unavailable, network unconfined", file=sys.stderr)+ if required:+ return 125+ os.execvp(command[0], command)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/app/core/src/test/java/stirling/software/SPDF/config/EndpointInterceptorTest.java b/app/core/src/test/java/stirling/software/SPDF/config/EndpointInterceptorTest.javaindex b064a169e6..6494a7135b 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/EndpointInterceptorTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/EndpointInterceptorTest.java@@ -42,4 +42,31 @@ class EndpointInterceptorTest {assertFalse(interceptor.preHandle(request, response, new Object()));verify(response).sendError(HttpServletResponse.SC_FORBIDDEN, "This endpoint is disabled");}++ @Test+ void preHandleBlocksPercentEncodedDisabledEndpoint() throws Exception {+ when(request.getRequestURI()).thenReturn("/api/v1/convert/html/pd%66");+ when(endpointConfiguration.isEndpointEnabledForUri("/api/v1/convert/html/pdf"))+ .thenReturn(false);+ assertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendError(HttpServletResponse.SC_FORBIDDEN, "This endpoint is disabled");+ }++ @Test+ void preHandleChecksPathRelativeToContextPath() throws Exception {+ when(request.getContextPath()).thenReturn("/pdf");+ when(request.getRequestURI()).thenReturn("/pdf/api/v1/general/rotate-pdf");+ when(endpointConfiguration.isEndpointEnabledForUri("/api/v1/general/rotate-pdf"))+ .thenReturn(false);+ assertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendError(HttpServletResponse.SC_FORBIDDEN, "This endpoint is disabled");+ }++ @Test+ void preHandleRejectsMalformedEscape() throws Exception {+ when(request.getRequestURI()).thenReturn("/api/v1/general/rotate-pdf%zz");+ assertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendError(HttpServletResponse.SC_BAD_REQUEST);+ verifyNoInteractions(endpointConfiguration);+ }}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/MetricsFilterTest.java b/app/core/src/test/java/stirling/software/SPDF/config/MetricsFilterTest.javaindex 48036e74ed..1fd30e2dec 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/MetricsFilterTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/MetricsFilterTest.java@@ -1,5 +1,11 @@package stirling.software.SPDF.config;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;@@ -9,6 +15,7 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;+import org.springframework.web.servlet.HandlerMapping;import io.micrometer.core.instrument.simple.SimpleMeterRegistry;@@ -44,6 +51,8 @@ class MetricsFilterTest {HttpSession session = mock(HttpSession.class);when(session.getId()).thenReturn("sess-1");when(request.getRequestURI()).thenReturn("/api/v1/general/rotate-pdf");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn("/api/v1/general/rotate-pdf");when(request.getContextPath()).thenReturn("");when(request.getMethod()).thenReturn("POST");when(request.getSession(false)).thenReturn(session);@@ -51,12 +60,22 @@ class MetricsFilterTest {filter.doFilterInternal(request, response, chain);verify(chain).doFilter(request, response);+ assertEquals(+ 1.0,+ registry.get("http.requests")+ .tag("session", "sess-1")+ .tag("method", "POST")+ .tag("uri", "/api/v1/general/rotate-pdf")+ .counter()+ .count());}@Test@DisplayName("uses no-session tag when session is absent")void countsWithoutSession() throws Exception {when(request.getRequestURI()).thenReturn("/api/v1/general/merge-pdfs");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn("/api/v1/general/merge-pdfs");when(request.getContextPath()).thenReturn("");when(request.getMethod()).thenReturn("POST");when(request.getSession(false)).thenReturn(null);@@ -64,6 +83,91 @@ class MetricsFilterTest {filter.doFilterInternal(request, response, chain);verify(chain).doFilter(request, response);+ assertNotNull(registry.find("http.requests").tag("session", "no-session").counter());+ }++ @Test+ @DisplayName("tags API calls with the route pattern, not the path variable values")+ void tagsRoutePatternInsteadOfPathVariables() throws Exception {+ String route = "/api/v1/mobile-scanner/files/{sessionId}";+ when(request.getRequestURI()).thenReturn("/api/v1/mobile-scanner/files/secret-id");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn(route);+ when(request.getContextPath()).thenReturn("");+ when(request.getMethod()).thenReturn("GET");++ filter.doFilterInternal(request, response, chain);++ assertEquals(1, registry.find("http.requests").counters().size());+ assertNotNull(registry.find("http.requests").tag("uri", route).counter());+ }++ @Test+ @DisplayName("keeps the context path in front of the route pattern")+ void keepsContextPath() throws Exception {+ when(request.getRequestURI()).thenReturn("/pdf/api/v1/general/job/abc");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn("/api/v1/general/job/{jobId}");+ when(request.getContextPath()).thenReturn("/pdf");+ when(request.getMethod()).thenReturn("GET");++ filter.doFilterInternal(request, response, chain);++ assertNotNull(+ registry.find("http.requests")+ .tag("uri", "/pdf/api/v1/general/job/{jobId}")+ .counter());+ }++ @Test+ @DisplayName("keeps the URI of top-level SPA pages")+ void tagsUriForSpaPages() throws Exception {+ when(request.getRequestURI()).thenReturn("/merge-pdfs");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn("/{path:[^\\.]*$}");+ when(request.getContextPath()).thenReturn("");+ when(request.getMethod()).thenReturn("GET");++ filter.doFilterInternal(request, response, chain);++ assertNotNull(registry.find("http.requests").tag("uri", "/merge-pdfs").counter());+ }++ @Test+ @DisplayName("tags SPA pages carrying a token in the path with the first segment only")+ void tagsFirstSegmentForTokenPages() throws Exception {+ when(request.getRequestURI()).thenReturn("/workflow/sign/secret-token");+ when(request.getContextPath()).thenReturn("");+ when(request.getMethod()).thenReturn("GET");++ filter.doFilterInternal(request, response, chain);++ assertEquals(1, registry.find("http.requests").counters().size());+ assertNotNull(registry.find("http.requests").tag("uri", "/workflow").counter());+ assertNull(+ registry.find("http.requests")+ .tag("uri", "/workflow/sign/secret-token")+ .counter());+ }++ @Test+ @DisplayName("counts the request even when the chain throws")+ void countsWhenChainThrows() throws Exception {+ when(request.getRequestURI()).thenReturn("/api/v1/general/rotate-pdf");+ when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))+ .thenReturn("/api/v1/general/rotate-pdf");+ when(request.getContextPath()).thenReturn("");+ when(request.getMethod()).thenReturn("POST");+ doThrow(new RuntimeException("boom")).when(chain).doFilter(request, response);++ assertThrows(+ RuntimeException.class,+ () -> filter.doFilterInternal(request, response, chain));++ assertNotNull(+ registry.find("http.requests")+ .tag("uri", "/api/v1/general/rotate-pdf")+ .counter());}}@@ -82,5 +186,17 @@ class MetricsFilterTest {verify(chain).doFilter(request, response);verify(request, never()).getMethod();}++ @Test+ @DisplayName("API call that matched no route is not counted")+ void unmatchedApiCallSkipped() throws Exception {+ when(request.getRequestURI()).thenReturn("/api/v1/unknown/some-value");+ when(request.getContextPath()).thenReturn("");++ filter.doFilterInternal(request, response, chain);++ verify(chain).doFilter(request, response);+ assertTrue(registry.find("http.requests").counters().isEmpty());+ }}}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.javaindex f92f691636..57205dd0d3 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java@@ -1,5 +1,6 @@package stirling.software.SPDF.controller.api.converters;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertSame;@@ -40,6 +41,7 @@ import stirling.software.SPDF.config.EndpointConfiguration;import stirling.software.SPDF.model.api.converters.ConvertEbookToPdfRequest;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.util.GeneralUtils;+import stirling.software.common.util.OfficeDocumentSanitizer;import stirling.software.common.util.ProcessExecutor;import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;import stirling.software.common.util.ProcessExecutor.Processes;@@ -64,6 +66,7 @@ class ConvertEbookToPDFControllerTest {@Mock private CustomPDFDocumentFactory pdfDocumentFactory;@Mock private TempFileManager tempFileManager;@Mock private EndpointConfiguration endpointConfiguration;+ @Mock private OfficeDocumentSanitizer officeDocumentSanitizer;@InjectMocks private ConvertEbookToPDFController controller;@@ -291,4 +294,88 @@ class ConvertEbookToPDFControllerTest {}}}++ @Test+ void convertEbookToPdf_sanitizesDocxBeforeCalibreReadsIt() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(true);+ byte[] uploaded = "linked-picture-docx".getBytes(StandardCharsets.UTF_8);+ byte[] sanitized = "sanitized-docx".getBytes(StandardCharsets.UTF_8);+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);+ when(officeDocumentSanitizer.sanitize(uploaded, "docx")).thenReturn(sanitized);++ ConvertEbookToPdfRequest request = new ConvertEbookToPdfRequest();+ request.setFileInput(+ new MockMultipartFile("fileInput", "book.docx", "application/zip", uploaded));++ Path workingDir = Files.createTempDirectory("ebook-convert-docx-test-");+ when(tempFileManager.createTempDirectory()).thenReturn(workingDir);+ AtomicReference<byte[]> seenByCalibre = new AtomicReference<>();++ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {+ ProcessExecutor executor = Mockito.mock(ProcessExecutor.class);+ pe.when(() -> ProcessExecutor.getInstance(Processes.CALIBRE)).thenReturn(executor);+ when(executor.runCommandWithOutputHandling(any(List.class), eq(workingDir.toFile())))+ .thenAnswer(+ invocation -> {+ seenByCalibre.set(+ Files.readAllBytes(workingDir.resolve("book.docx")));+ throw new IOException("Calibre conversion failed with exit code 1");+ });++ assertThrows(IOException.class, () -> controller.convertEbookToPdf(request));+ } finally {+ deleteRecursively(workingDir);+ }++ assertArrayEquals(sanitized, seenByCalibre.get());+ }++ @Test+ void convertEbookToPdf_failedRunDoesNotEchoCalibreOutput() throws Exception {+ when(endpointConfiguration.isGroupEnabled("Calibre")).thenReturn(true);++ ConvertEbookToPdfRequest request = new ConvertEbookToPdfRequest();+ request.setFileInput(+ new MockMultipartFile(+ "fileInput", "book.mobi", "application/octet-stream", new byte[] {1}));++ Path workingDir = Files.createTempDirectory("ebook-convert-fail-test-");+ when(tempFileManager.createTempDirectory()).thenReturn(workingDir);++ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {+ ProcessExecutor executor = Mockito.mock(ProcessExecutor.class);+ pe.when(() -> ProcessExecutor.getInstance(Processes.CALIBRE)).thenReturn(executor);+ ProcessExecutorResult execResult = Mockito.mock(ProcessExecutorResult.class);+ when(execResult.getRc()).thenReturn(2);+ lenient()+ .when(execResult.getMessages())+ .thenReturn("Could not find file uuid-in-the-copy/secret-uuid in book");+ when(executor.runCommandWithOutputHandling(any(List.class), eq(workingDir.toFile())))+ .thenReturn(execResult);++ IllegalStateException e =+ assertThrows(+ IllegalStateException.class,+ () -> controller.convertEbookToPdf(request));+ assertEquals("Calibre conversion failed", e.getMessage());+ } finally {+ deleteRecursively(workingDir);+ }+ }++ private static void deleteRecursively(Path dir) throws IOException {+ if (!Files.exists(dir)) {+ return;+ }+ try (Stream<Path> paths = Files.walk(dir)) {+ paths.sorted(Comparator.reverseOrder())+ .forEach(+ path -> {+ try {+ Files.deleteIfExists(path);+ } catch (IOException ignored) {+ }+ });+ }+ }}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorOutputPathTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorOutputPathTest.javanew file mode 100644index 0000000000..46e274d228--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/pipeline/PipelineDirectoryProcessorOutputPathTest.java@@ -0,0 +1,88 @@+package stirling.software.SPDF.controller.api.pipeline;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.nio.file.Path;+import java.util.List;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import stirling.software.SPDF.model.PipelineConfig;+import stirling.software.SPDF.service.ApiDocService;+import stirling.software.common.configuration.RuntimePathConfig;+import stirling.software.common.service.PostHogService;+import stirling.software.common.service.ToolMetadataService;+import stirling.software.common.util.FileReadinessChecker;++import tools.jackson.databind.ObjectMapper;++class PipelineDirectoryProcessorOutputPathTest {++ @TempDir Path tempDir;++ private Path finished;+ private Path jobDir;+ private PipelineDirectoryProcessor processor;++ @BeforeEach+ void setUp() {+ finished = tempDir.resolve("pipeline").resolve("finishedFolders").toAbsolutePath();+ Path watched = tempDir.resolve("pipeline").resolve("watchedFolders").toAbsolutePath();+ jobDir = watched.resolve("job");+ RuntimePathConfig paths = mock(RuntimePathConfig.class);+ when(paths.getPipelineWatchedFoldersPaths()).thenReturn(List.of(watched.toString()));+ when(paths.getPipelineFinishedFoldersPath()).thenReturn(finished.toString());+ processor =+ new PipelineDirectoryProcessor(+ new ObjectMapper(),+ mock(ApiDocService.class),+ mock(ToolMetadataService.class),+ mock(PipelineProcessor.class),+ mock(PostHogService.class),+ mock(FileReadinessChecker.class),+ paths);+ }++ private Path outputFor(String outputDir) {+ PipelineConfig config = new PipelineConfig();+ config.setOutputDir(outputDir);+ return processor.determineOutputPath(config, jobDir);+ }++ @Test+ void keepsTheFinishedFolderForTheStandardPlaceholders() {+ assertEquals(finished.normalize(), outputFor("{outputFolder}"));+ assertEquals(finished.resolve("sub").normalize(), outputFor("{outputFolder}/sub"));+ assertEquals(+ Path.of(finished + "/" + jobDir.toString().replace("watchedFolders", ""))+ .normalize(),+ outputFor("{outputFolder}/{folderName}"));+ }++ @Test+ void fallsBackToTheFinishedFolderForAnAbsolutePathOutsideIt() {+ assertEquals(+ finished.normalize(),+ outputFor(tempDir.resolve("configs").resolve("scripts").toString()));+ }++ @Test+ void fallsBackToTheFinishedFolderForARelativePathOutsideIt() {+ assertEquals(finished.normalize(), outputFor("configs/scripts/python"));+ }++ @Test+ void fallsBackToTheFinishedFolderForTraversalOutOfIt() {+ assertEquals(finished.normalize(), outputFor("{outputFolder}/../../configs"));+ }++ @Test+ void fallsBackToTheFinishedFolderWhenNoOutputDirIsGiven() {+ assertEquals(finished.normalize(), outputFor(null));+ assertEquals(finished.normalize(), outputFor(" "));+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.javanew file mode 100644index 0000000000..7aa5c09ccd--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.java@@ -0,0 +1,260 @@+package stirling.software.SPDF.service;++import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.atLeastOnce;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.IOException;+import java.io.OutputStream;+import java.lang.reflect.Field;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;++import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSDictionary;+import org.apache.pdfbox.cos.COSFloat;+import org.apache.pdfbox.cos.COSInteger;+import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.cos.COSStream;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.PDResources;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.MockedStatic;+import org.mockito.junit.jupiter.MockitoExtension;+import org.mockito.junit.jupiter.MockitoSettings;+import org.mockito.quality.Strictness;+import org.springframework.mock.web.MockMultipartFile;++import stirling.software.SPDF.config.EndpointConfiguration;+import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;+import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;+import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.service.TaskManager;+import stirling.software.common.util.ProcessExecutor;+import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;+import stirling.software.common.util.TempFileManager;++import tools.jackson.databind.DeserializationFeature;+import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.json.JsonMapper;++@ExtendWith(MockitoExtension.class)+@MockitoSettings(strictness = Strictness.LENIENT)+class PdfJsonConversionServiceCffFontTest {++ private static final byte[] SFD_PAYLOAD =+ ("SplineFontDB: 3.2\n"+ + "FontName: Evil\n"+ + "PickledData: \"cos\nsystem\n(S'true'\ntR.\"\n"+ + "EndSplineFont\n")+ .getBytes(StandardCharsets.US_ASCII);++ private static final byte[] CFF_PAYLOAD = {1, 0, 4, 1, 0, 0, 0, 0};++ @Mock private CustomPDFDocumentFactory pdfDocumentFactory;+ @Mock private EndpointConfiguration endpointConfiguration;+ @Mock private TempFileManager tempFileManager;+ @Mock private TaskManager taskManager;+ @Mock private PdfJsonFallbackFontService fallbackFontService;+ @Mock private Type3FontConversionService type3FontConversionService;+ @Mock private Type3GlyphExtractor type3GlyphExtractor;+ @Mock private ApplicationProperties applicationProperties;++ private final ObjectMapper objectMapper =+ JsonMapper.builder()+ .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)+ .build();++ private final List<Path> createdTempFiles = new ArrayList<>();++ private PdfJsonFontService fontService;+ private PdfJsonConversionService service;++ @BeforeEach+ void setUp() throws Exception {+ fontService = spy(new PdfJsonFontService(tempFileManager, new ApplicationProperties()));+ setFontServiceField("cffConversionEnabled", true);+ setFontServiceField("cffConverterMethod", "fontforge");+ setFontServiceField("fontforgeCommand", "fontforge");+ setFontServiceField("fontForgeCffConverterAvailable", true);+ setFontServiceField("pythonCffConverterAvailable", false);++ service =+ new PdfJsonConversionService(+ pdfDocumentFactory,+ objectMapper,+ endpointConfiguration,+ tempFileManager,+ taskManager,+ new PdfJsonCosMapper(),+ fallbackFontService,+ fontService,+ type3FontConversionService,+ type3GlyphExtractor,+ applicationProperties);++ when(tempFileManager.createTempFile(anyString()))+ .thenAnswer(+ invocation -> {+ Path path =+ Files.createTempFile(+ "pdfjson-cff-test", invocation.getArgument(0));+ createdTempFiles.add(path);+ return path.toFile();+ });+ when(tempFileManager.deleteTempFile(any(File.class)))+ .thenAnswer(+ invocation -> {+ File file = invocation.getArgument(0);+ return file != null && file.delete();+ });+ }++ @AfterEach+ void tearDown() throws IOException {+ for (Path path : createdTempFiles) {+ Files.deleteIfExists(path);+ }+ createdTempFiles.clear();+ }++ @Test+ void sfdLabelledType1cNeverReachesFontForge() throws Exception {+ try (MockedStatic<ProcessExecutor> processExecutor = mockStatic(ProcessExecutor.class);+ PDDocument pdf = pdfWithType3FontFile3(SFD_PAYLOAD)) {+ stubCffConverter(processExecutor);+ when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);++ service.convertPdfToJson(pdfMultipart(), new ByteArrayOutputStream());++ verify(fontService, atLeastOnce()).isCffFontProgram(SFD_PAYLOAD);+ verify(fontService, never()).convertCffProgramToTrueType(any(), any());+ verify(fontService, never()).convertCffUsingFontForge(any());+ processExecutor.verify(+ () -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER),+ never());+ }+ }++ @Test+ void cffLabelledType1cStillReachesFontForge() throws Exception {+ try (MockedStatic<ProcessExecutor> processExecutor = mockStatic(ProcessExecutor.class);+ PDDocument pdf = pdfWithType3FontFile3(CFF_PAYLOAD)) {+ stubCffConverter(processExecutor);+ when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);++ ByteArrayOutputStream out = new ByteArrayOutputStream();+ service.convertPdfToJson(pdfMultipart(), out);++ verify(fontService, atLeastOnce()).convertCffUsingFontForge(CFF_PAYLOAD);+ processExecutor.verify(+ () -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER),+ atLeastOnce());+ assertTrue(out.toString(StandardCharsets.UTF_8).contains("\"pages\""));+ }+ }++ private void stubCffConverter(MockedStatic<ProcessExecutor> processExecutor) throws Exception {+ ProcessExecutor executor = mock(ProcessExecutor.class);+ ProcessExecutorResult result = mock(ProcessExecutorResult.class);+ when(result.getRc()).thenReturn(1);+ when(executor.runCommandWithOutputHandling(anyList())).thenReturn(result);+ processExecutor+ .when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER))+ .thenReturn(executor);+ }++ private void setFontServiceField(String name, Object value) throws Exception {+ Field field = PdfJsonFontService.class.getDeclaredField(name);+ field.setAccessible(true);+ field.set(fontService, value);+ }++ private PDDocument pdfWithType3FontFile3(byte[] fontProgram) throws IOException {+ PDDocument document = new PDDocument();+ PDPage page = new PDPage(PDRectangle.LETTER);+ document.addPage(page);++ COSStream fontFile3 = document.getDocument().createCOSStream();+ fontFile3.setItem(COSName.SUBTYPE, COSName.getPDFName("Type1C"));+ try (OutputStream stream = fontFile3.createOutputStream()) {+ stream.write(fontProgram);+ }++ COSDictionary descriptor = new COSDictionary();+ descriptor.setItem(COSName.TYPE, COSName.FONT_DESC);+ descriptor.setName(COSName.FONT_NAME, "Evil");+ descriptor.setInt(COSName.FLAGS, 4);+ descriptor.setItem(COSName.FONT_BBOX, numbers(0, 0, 1000, 1000));+ descriptor.setInt(COSName.ITALIC_ANGLE, 0);+ descriptor.setInt(COSName.ASCENT, 800);+ descriptor.setInt(COSName.DESCENT, -200);+ descriptor.setInt(COSName.CAP_HEIGHT, 700);+ descriptor.setInt(COSName.STEM_V, 80);+ descriptor.setItem(COSName.FONT_FILE3, fontFile3);++ COSArray fontMatrix = new COSArray();+ fontMatrix.add(new COSFloat(0.001f));+ fontMatrix.add(COSInteger.ZERO);+ fontMatrix.add(COSInteger.ZERO);+ fontMatrix.add(new COSFloat(0.001f));+ fontMatrix.add(COSInteger.ZERO);+ fontMatrix.add(COSInteger.ZERO);++ COSDictionary font = new COSDictionary();+ font.setItem(COSName.TYPE, COSName.FONT);+ font.setItem(COSName.SUBTYPE, COSName.TYPE3);+ font.setItem(COSName.FONT_BBOX, numbers(0, 0, 1000, 1000));+ font.setItem(COSName.FONT_MATRIX, fontMatrix);+ font.setItem(COSName.CHAR_PROCS, new COSDictionary());+ font.setInt(COSName.FIRST_CHAR, 65);+ font.setInt(COSName.LAST_CHAR, 65);+ font.setItem(COSName.WIDTHS, numbers(1000));+ font.setItem(COSName.FONT_DESC, descriptor);++ COSDictionary fonts = new COSDictionary();+ fonts.setItem(COSName.getPDFName("F1"), font);+ COSDictionary resources = new COSDictionary();+ resources.setItem(COSName.FONT, fonts);+ page.setResources(new PDResources(resources));+ return document;+ }++ private static COSArray numbers(int... values) {+ COSArray array = new COSArray();+ for (int value : values) {+ array.add(COSInteger.get(value));+ }+ return array;+ }++ private static MockMultipartFile pdfMultipart() {+ return new MockMultipartFile(+ "fileInput",+ "input.pdf",+ "application/pdf",+ "%PDF-1.4 placeholder".getBytes(StandardCharsets.US_ASCII));+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.javaindex 9db6412cdc..17db644972 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java@@ -107,9 +107,15 @@ class JobOwnershipServiceImplTest {// --- validateJobAccess tests ---@Test- void validateJobAccess_noUser_allowsAccess() {+ void validateJobAccess_noUser_ownedKey_throwsSecurityException() {when(userService.getCurrentUsername()).thenReturn(null);- assertTrue(service.validateJobAccess("any:key"));+ assertThrows(SecurityException.class, () -> service.validateJobAccess("alice:job1"));+ }++ @Test+ void validateJobAccess_noUser_unownedKey_allowsAccess() {+ when(userService.getCurrentUsername()).thenReturn(null);+ assertTrue(service.validateJobAccess("job123"));}@Testdiff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.javaindex f6bc1a462e..3b117f4686 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.java@@ -7,6 +7,7 @@ import static org.mockito.Mockito.*;import java.io.File;import java.lang.reflect.Field;import java.lang.reflect.Method;+import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.util.Base64;import java.util.List;@@ -29,6 +30,8 @@ import stirling.software.common.util.TempFileManager;*/class PdfJsonFontServiceMoreTest {+ private static final byte[] CFF_HEADER = {1, 0, 4, 1};+private TempFileManager tempFileManager;private ApplicationProperties applicationProperties;private PdfJsonFontService service;@@ -334,7 +337,7 @@ class PdfJsonFontServiceMoreTest {ProcessExecutor.Processes.CFF_CONVERTER)).thenReturn(exec);- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));+ assertNull(service.convertCffProgramToTrueType(CFF_HEADER, null));}}@@ -375,7 +378,7 @@ class PdfJsonFontServiceMoreTest {ProcessExecutor.Processes.CFF_CONVERTER)).thenReturn(exec);- byte[] out = service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null);+ byte[] out = service.convertCffProgramToTrueType(CFF_HEADER, null);assertNotNull(out);assertEquals(3, out.length);}@@ -453,7 +456,7 @@ class PdfJsonFontServiceMoreTest {ProcessExecutor.Processes.CFF_CONVERTER)).thenReturn(exec);- assertNull(service.convertCffUsingFontForge(new byte[] {1, 2, 3}));+ assertNull(service.convertCffUsingFontForge(CFF_HEADER));}}@@ -475,11 +478,88 @@ class PdfJsonFontServiceMoreTest {ProcessExecutor.Processes.CFF_CONVERTER)).thenReturn(exec);+ assertNull(service.convertCffUsingFontForge(CFF_HEADER));+ }+ }++ @Test+ @DisplayName("input without a CFF header never reaches FontForge")+ void nonCffInputRejected() throws Exception {+ setField("fontForgeCffConverterAvailable", true);+ setField("fontforgeCommand", "fontforge");++ try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {+ byte[] sfd = "SplineFontDB: 3.2\n".getBytes(StandardCharsets.US_ASCII);+ assertNull(service.convertCffUsingFontForge(sfd));+ assertNull(service.convertCffUsingFontForge(new byte[] {1, 0, 4}));+ assertNull(service.convertCffUsingFontForge(new byte[] {1, 0, 4, 5}));assertNull(service.convertCffUsingFontForge(new byte[] {1, 2, 3}));+ assertNull(service.convertCffUsingFontForge(null));+ mocked.verifyNoInteractions();+ verifyNoInteractions(tempFileManager);}}}+ @Nested+ @DisplayName("isCffFontProgram")+ class CffHeader {++ @Test+ @DisplayName("accepts CFF headers with hdrSize 4")+ void acceptsHeaderSizeFour() {+ assertTrue(service.isCffFontProgram(CFF_HEADER));+ assertTrue(service.isCffFontProgram(new byte[] {1, 0, 4, 4, 0, 0}));+ }++ @Test+ @DisplayName("accepts CFF headers with a larger hdrSize and a nonzero minor version")+ void acceptsLargerHeaderSize() {+ assertTrue(service.isCffFontProgram(new byte[] {1, 0, 5, 1, 0}));+ assertTrue(service.isCffFontProgram(new byte[] {1, 1, 8, 2, 0, 0, 0, 0, 0}));+ }++ @Test+ @DisplayName("rejects a major version other than 1")+ void rejectsWrongMajorVersion() {+ assertFalse(service.isCffFontProgram(new byte[] {2, 0, 5, 1, 0}));+ assertFalse(service.isCffFontProgram(new byte[] {0, 0, 4, 1}));+ }++ @Test+ @DisplayName("rejects an invalid hdrSize or offSize")+ void rejectsInvalidSizes() {+ assertFalse(service.isCffFontProgram(new byte[] {1, 0, 3, 1}));+ assertFalse(service.isCffFontProgram(new byte[] {1, 0, 8, 1}));+ assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4, 0}));+ assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4, 5}));+ }++ @Test+ @DisplayName("rejects FontForge SFD source text")+ void rejectsSfd() {+ assertFalse(+ service.isCffFontProgram(+ "SplineFontDB: 3.2\nFontName: X\n"+ .getBytes(StandardCharsets.US_ASCII)));+ }++ @Test+ @DisplayName("rejects empty, short and null input")+ void rejectsShortInput() {+ assertFalse(service.isCffFontProgram(new byte[0]));+ assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4}));+ assertFalse(service.isCffFontProgram(null));+ }++ @Test+ @DisplayName("rejects OpenType and TrueType wrappers")+ void rejectsSfntWrappers() {+ assertFalse(service.isCffFontProgram(new byte[] {'O', 'T', 'T', 'O', 0, 9, 0, 0}));+ assertFalse(service.isCffFontProgram(new byte[] {0, 1, 0, 0, 0, 12}));+ }+ }+@Nested@DisplayName("detect* extra branches")class DetectExtra {diff --git a/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.java b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.javanew file mode 100644index 0000000000..912ffdf597--- /dev/null+++ b/app/core/src/test/java/stirling/software/SPDF/util/CalibreSandboxScriptTest.java@@ -0,0 +1,98 @@+package stirling.software.SPDF.util;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assumptions.assumeTrue;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.TimeUnit;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.condition.EnabledOnOs;+import org.junit.jupiter.api.condition.OS;+import org.junit.jupiter.api.io.TempDir;++import stirling.software.common.util.GeneralUtils;++@EnabledOnOs(OS.LINUX)+class CalibreSandboxScriptTest {++ @TempDir Path workDir;+ @TempDir Path elsewhere;++ private Path launcher;++ @BeforeEach+ void requireASandboxCapableHost() throws Exception {+ launcher = GeneralUtils.extractScript("calibre_sandbox.py").toAbsolutePath();+ int rc;+ try {+ rc = confined("/usr/bin/true");+ } catch (IOException e) {+ rc = -1;+ }+ assumeTrue(rc == 0, "python3, Landlock or seccomp unavailable");+ }++ private int confined(String... command) throws Exception {+ List<String> full =+ new ArrayList<>(List.of("python3", "-I", launcher.toString(), workDir.toString()));+ full.addAll(List.of(command));+ ProcessBuilder builder = new ProcessBuilder(full).directory(workDir.toFile());+ builder.environment().put("STIRLING_CALIBRE_SANDBOX", "required");+ builder.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD);+ Process process = builder.start();+ if (!process.waitFor(60, TimeUnit.SECONDS)) {+ process.destroyForcibly();+ throw new IllegalStateException("launcher did not finish");+ }+ return process.exitValue();+ }++ @Test+ @DisplayName("the job's own files can be read and written")+ void workingDirectoryIsUsable() throws Exception {+ Path book = Files.writeString(workDir.resolve("book.txt"), "book");++ assertEquals(0, confined("/usr/bin/cp", book.toString(), workDir + "/copy.txt"));+ assertEquals("book", Files.readString(workDir.resolve("copy.txt")));+ }++ @Test+ @DisplayName("a file outside the job cannot be read, directly or through a symlink")+ void filesElsewhereAreUnreadable() throws Exception {+ Path secret = Files.writeString(elsewhere.resolve("settings.yml"), "secret");+ Path link = Files.createSymbolicLink(workDir.resolve("cover.jpg"), secret);++ assertNotEquals(0, confined("/usr/bin/cp", secret.toString(), workDir + "/copy.txt"));+ assertNotEquals(0, confined("/usr/bin/cp", link.toString(), workDir + "/copy.txt"));+ assertNotEquals(0, confined("/usr/bin/ls", elsewhere.toString()));+ }++ @Test+ @DisplayName("nothing outside the job can be written")+ void filesElsewhereAreUnwritable() throws Exception {+ Path book = Files.writeString(workDir.resolve("book.txt"), "book");++ assertNotEquals(0, confined("/usr/bin/cp", book.toString(), elsewhere + "/copy.txt"));+ assertFalse(Files.exists(elsewhere.resolve("copy.txt")));+ }++ @Test+ @DisplayName("only UNIX sockets can be opened")+ void networkIsUnreachable() throws Exception {+ assumeTrue(confined("python3", "-I", "-c", "pass") == 0, "python3 is not under /usr");+ String open = "import socket; socket.socket(socket.%s)";++ assertEquals(0, confined("python3", "-I", "-c", open.formatted("AF_UNIX")));+ assertNotEquals(0, confined("python3", "-I", "-c", open.formatted("AF_INET")));+ assertNotEquals(0, confined("python3", "-I", "-c", open.formatted("AF_INET6")));+ }+}diff --git a/app/core/src/test/java/stirling/software/SPDF/util/ExtractScriptConcurrencyTest.java b/app/core/src/test/java/stirling/software/SPDF/util/ExtractScriptConcurrencyTest.javaindex f0c3ff6f95..b44446194e 100644--- a/app/core/src/test/java/stirling/software/SPDF/util/ExtractScriptConcurrencyTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/util/ExtractScriptConcurrencyTest.java@@ -1,8 +1,10 @@package stirling.software.SPDF.util;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;+import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.util.concurrent.CountDownLatch;@@ -11,6 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Test;+import org.springframework.core.io.ClassPathResource;import stirling.software.common.util.GeneralUtils;@@ -75,4 +78,20 @@ class ExtractScriptConcurrencyTest {assertEquals(modified, Files.getLastModifiedTime(first).toMillis(), "script was rewritten");assertEquals(size, Files.size(first));}++ @Test+ @DisplayName("a modified copy on disk is replaced with the bundled script")+ void modifiedCopyIsReplaced() throws Exception {+ Path script = GeneralUtils.extractScript("png_to_webp.py");+ byte[] bundled;+ try (InputStream in =+ new ClassPathResource("static/python/png_to_webp.py").getInputStream()) {+ bundled = in.readAllBytes();+ }++ Files.writeString(script, "import os\nos.system('id')\n");++ assertEquals(script, GeneralUtils.extractScript("png_to_webp.py"));+ assertArrayEquals(bundled, Files.readAllBytes(script));+ }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.javaindex 6069377024..6532fc8e0b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java@@ -155,7 +155,7 @@ public class AccountLinkController {if (headerValue == null || headerValue.isBlank()) {return null;}- String first = headerValue.split(",")[0].strip();+ String first = headerValue.split(",", 2)[0].strip();return first.isEmpty() ? null : first;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/audit/ControllerAuditAspect.java b/app/proprietary/src/main/java/stirling/software/proprietary/audit/ControllerAuditAspect.javaindex e6af47129f..925afb0493 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/audit/ControllerAuditAspect.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/audit/ControllerAuditAspect.java@@ -141,29 +141,27 @@ public class ControllerAuditAspect {String previousSource = MDC.get("auditSource");String previousIp = MDC.get("auditIp");- // EARLY CAPTURE: Capture from SecurityContext on request thread, store in MDC for async- // propagation- // MDC.put is necessary for background threads to inherit audit context- String capturedPrincipal = previousPrincipal;- if (capturedPrincipal == null) {- capturedPrincipal = auditService.captureCurrentPrincipal();- MDC.put("auditPrincipal", capturedPrincipal);- }+ try {+ String capturedPrincipal = previousPrincipal;+ if (capturedPrincipal == null) {+ capturedPrincipal = auditService.captureCurrentPrincipal();+ MDC.put("auditPrincipal", capturedPrincipal);+ }- String capturedOrigin = previousOrigin;- if (capturedOrigin == null) {- capturedOrigin = auditService.captureCurrentOrigin();- MDC.put("auditOrigin", capturedOrigin);- }+ String capturedOrigin = previousOrigin;+ if (capturedOrigin == null) {+ capturedOrigin = auditService.captureCurrentOrigin();+ MDC.put("auditOrigin", capturedOrigin);+ }- String capturedIp = previousIp;- if (capturedIp == null && req != null) {- capturedIp = auditService.extractClientIp(req);- if (capturedIp != null) {- MDC.put("auditIp", capturedIp);+ String capturedIp = previousIp;+ if (capturedIp == null && req != null) {+ capturedIp = auditService.extractClientIp(req);+ if (capturedIp != null) {+ MDC.put("auditIp", capturedIp);+ }}- }- try {+// Avoid duplicate events for controller methods explicitly annotated with @Audited.// @Audited methods are audited by AuditAspect.if (auditedAnnotation != null) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.javaindex 8b1486f554..f75a8e37b2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java@@ -1,5 +1,7 @@package stirling.software.proprietary.policy.config;+import java.io.IOException;+import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;@@ -40,18 +42,9 @@ public class FolderAccessGuard {public static final String FOLDER_TYPE = "folder";- /** Reason keys for an implied root, surfaced to the admin UI so it can label each one. */- public static final String IMPLIED_SERVER_STORAGE = "serverStorage";-- public static final String IMPLIED_WATCHED_FOLDER = "watchedFolder";-- /** A directory implicitly permitted regardless of {@code allowedFolderRoots}, and why. */- public record ImpliedRoot(Path path, String reason) {}-private final boolean saasActive;private final boolean desktopOperator;private final List<Path> allowedRoots;- private final List<ImpliedRoot> impliedRoots;private final List<Path> protectedRoots;private final SourceStore sourceStore;@@ -64,8 +57,7 @@ public class FolderAccessGuard {this.desktopOperator = isDesktopBundle();this.allowedRoots =normalizeAll(applicationProperties.getPolicies().getAllowedFolderRoots());- this.impliedRoots = impliedRoots(applicationProperties.getStorage(), runtimePathConfig);- this.protectedRoots = List.of(normalize(Path.of(InstallationPathConfig.getConfigPath())));+ this.protectedRoots = protectedRoots(applicationProperties.getStorage(), runtimePathConfig);this.sourceStore = sourceStore;}@@ -88,23 +80,19 @@ public class FolderAccessGuard {throw new IllegalArgumentException("folder sources and outputs are not available in SaaS mode");}+ if (!dir.isAbsolute()) {+ throw new IllegalArgumentException("folder must be an absolute path");+ }Path normalized = normalize(dir);- for (Path protectedRoot : protectedRoots) {- if (normalized.startsWith(protectedRoot)) {- throw new IllegalArgumentException(- "folder may not point inside a protected Stirling directory");- }+ if (isProtected(normalized)) {+ throw new IllegalArgumentException(+ "folder may not point inside a protected Stirling directory");}// The desktop operator's own choice is the authorization on their own machine; only the// SaaS refusal and the protected config dir above outrank it.if (desktopOperator) {return normalized;}- // Stirling-owned implied roots are always permitted, even with no configured roots, so- // automations work against them out of the box.- if (impliedRoots.stream().anyMatch(root -> normalized.startsWith(root.path()))) {- return normalized;- }if (allowedRoots.isEmpty()) {throw new FolderAccessDeniedException("folder access is disabled; set policies.allowedFolderRoots to permit it");@@ -117,9 +105,18 @@ public class FolderAccessGuard {return normalized;}- /** The Stirling-owned directories always permitted, with a reason key for each (read-only). */- public List<ImpliedRoot> impliedRoots() {- return impliedRoots;+ public boolean isProtected(Path path) {+ Path normalized = normalize(path);+ Path resolved = resolveExisting(normalized);+ return protectedRoots.stream()+ .anyMatch(+ root -> {+ Path resolvedRoot = resolveExisting(root);+ return normalized.startsWith(root)+ || normalized.startsWith(resolvedRoot)+ || resolved.startsWith(root)+ || resolved.startsWith(resolvedRoot);+ });}/** Whether this policy touches a folder source/sink, and so is subject to these rules. */@@ -134,32 +131,32 @@ public class FolderAccessGuard {return readsFolder || writesFolder;}- /**- * Stirling-owned directories always permitted regardless of {@code allowedFolderRoots}, so- * folder automations work against them out of the box.- */- private static List<ImpliedRoot> impliedRoots(+ private static List<Path> protectedRoots(ApplicationProperties.Storage storage, RuntimePathConfig runtimePathConfig) {- List<ImpliedRoot> roots = new ArrayList<>();- for (Path path : serverStorageRoots(storage)) {- roots.add(new ImpliedRoot(path, IMPLIED_SERVER_STORAGE));- }- for (Path path : normalizeAll(runtimePathConfig.getPipelineWatchedFoldersPaths())) {- roots.add(new ImpliedRoot(path, IMPLIED_WATCHED_FOLDER));+ List<Path> roots = new ArrayList<>();+ roots.add(normalize(Path.of(InstallationPathConfig.getConfigPath())));+ String basePath = storage.getLocal().getBasePath();+ if (basePath == null || basePath.isBlank()) {+ basePath = InstallationPathConfig.getPath() + "storage";}+ roots.add(normalize(Path.of(basePath)));+ roots.addAll(normalizeAll(runtimePathConfig.getPipelineWatchedFoldersPaths()));return List.copyOf(roots);}- /** The local server file-storage directory, when that storage provider is enabled. */- private static List<Path> serverStorageRoots(ApplicationProperties.Storage storage) {- if (!storage.isEnabled() || !"local".equalsIgnoreCase(storage.getProvider())) {- return List.of();+ private static Path resolveExisting(Path normalized) {+ Path existing = normalized;+ while (existing != null && !Files.exists(existing)) {+ existing = existing.getParent();}- String basePath = storage.getLocal().getBasePath();- if (basePath == null || basePath.isBlank()) {- return List.of();+ if (existing == null) {+ return normalized;+ }+ try {+ return existing.toRealPath().resolve(existing.relativize(normalized)).normalize();+ } catch (IOException | SecurityException e) {+ return normalized;}- return List.of(normalize(Path.of(basePath)));}private static List<Path> normalizeAll(List<String> roots) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/FolderAccessSettingsController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/FolderAccessSettingsController.javadeleted file mode 100644index 1b39aee106..0000000000--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/FolderAccessSettingsController.java+++ /dev/null@@ -1,42 +0,0 @@-package stirling.software.proprietary.policy.controller;--import java.util.List;--import org.springframework.security.access.prepost.PreAuthorize;-import org.springframework.web.bind.annotation.GetMapping;--import io.swagger.v3.oas.annotations.Operation;--import lombok.RequiredArgsConstructor;--import stirling.software.common.annotations.api.AdminApi;-import stirling.software.proprietary.policy.config.FolderAccessGuard;--/**- * Read-only admin view of the folder roots that are always permitted for folder automations,- * regardless of {@code policies.allowedFolderRoots} (server storage, pipeline watched folders). The- * Folder Access settings section renders these so an admin can see what is implicitly allowed and- * why, without them being editable. The editable roots themselves live under the {@code policies}- * settings section.- */-@AdminApi-@PreAuthorize("hasRole('ADMIN')")-@RequiredArgsConstructor-public class FolderAccessSettingsController {-- private final FolderAccessGuard folderAccessGuard;-- @GetMapping("/policies/implied-folder-roots")- @Operation(- summary = "Implied folder roots",- description =- "Stirling-managed directories always permitted for folder automations"- + " regardless of policies.allowedFolderRoots. Read-only.")- public List<ImpliedFolderRoot> impliedFolderRoots() {- return folderAccessGuard.impliedRoots().stream()- .map(root -> new ImpliedFolderRoot(root.path().toString(), root.reason()))- .toList();- }-- public record ImpliedFolderRoot(String path, String reason) {}-}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.javaindex 323e3d31a4..4fce3fbddd 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java@@ -95,7 +95,7 @@ public class FolderInputSource implements InputSource {inputDir.toString(), null, "input directory does not exist");}Path canonicalDir = FolderIdentities.canonicalDir(inputDir);- List<Path> present = listFiles(inputDir, config.recursive());+ List<Path> present = listFiles(inputDir, config.recursive(), accessGuard);// Filtered before anything observes the listing: an out-of-scope file is invisible to the// ledger and the sweep alike, so it neither burns the sweep limit nor parks as a failure.if (!config.extensions().isEmpty()) {@@ -334,7 +334,8 @@ public class FolderInputSource implements InputSource {}}- private static List<Path> listFiles(Path inputDir, boolean recursive) throws IOException {+ private static List<Path> listFiles(+ Path inputDir, boolean recursive, FolderAccessGuard accessGuard) throws IOException {List<Path> files = new ArrayList<>();if (!recursive) {try (Stream<Path> entries = Files.list(inputDir)) {@@ -351,7 +352,8 @@ public class FolderInputSource implements InputSource {@Overridepublic FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attributes) {- if (!dir.equals(inputDir) && hidden(dir)) {+ if (!dir.equals(inputDir)+ && (hidden(dir) || accessGuard.isProtected(dir))) {return FileVisitResult.SKIP_SUBTREE;}return FileVisitResult.CONTINUE;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.javaindex 0524723edb..af81770f68 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/PolicyOutputResolver.java@@ -1,6 +1,7 @@package stirling.software.proprietary.policy.output;import java.util.List;+import java.util.Objects;import org.springframework.stereotype.Service;@@ -27,21 +28,28 @@ public class PolicyOutputResolver {if (outputIds.isEmpty()) {return List.of(policy.output());}- return outputIds.stream().map(this::resolveDestination).toList();+ return outputIds.stream().map(id -> resolveDestination(policy, id)).toList();}/** Resolve each routing rule's destination live; rule order is preserved. */public List<RoutedDestination> resolveRouting(Policy policy) {return policy.routingRules().stream()- .map(rule -> new RoutedDestination(rule, resolveDestination(rule.outputId())))+ .map(+ rule ->+ new RoutedDestination(+ rule, resolveDestination(policy, rule.outputId()))).toList();}- private OutputSpec resolveDestination(String id) {+ private OutputSpec resolveDestination(Policy policy, String id) {return sourceStore.get(id).filter(Source::enabled).filter(source -> !"editor".equals(source.type()))+ .filter(+ source ->+ policy.teamId() == null+ || Objects.equals(source.teamId(), policy.teamId())).orElseThrow(() ->new IllegalArgumentException(diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3ConnectionPool.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3ConnectionPool.javaindex 145295d462..0110159117 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3ConnectionPool.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/s3/S3ConnectionPool.java@@ -51,12 +51,8 @@ public class S3ConnectionPool {}public S3Client clientFor(S3Config config) {- return clients.computeIfAbsent(- config,- c -> {- requirePermittedEndpoint(c);- return clientFactory.apply(c);- });+ requirePermittedEndpoint(config);+ return clients.computeIfAbsent(config, clientFactory);}/**diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/JwtAuthenticationEntryPoint.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/JwtAuthenticationEntryPoint.javaindex 479b544ad5..ae9d278c56 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/JwtAuthenticationEntryPoint.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/JwtAuthenticationEntryPoint.java@@ -9,6 +9,8 @@ import org.springframework.stereotype.Component;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;+import stirling.software.common.util.RequestUriUtils;+@Componentpublic class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {@Override@@ -17,11 +19,8 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {HttpServletResponse response,AuthenticationException authException)throws IOException {- String contextPath = request.getContextPath();- String requestURI = request.getRequestURI();-// For API requests, return JSON error- if (requestURI.startsWith(contextPath + "/api/")) {+ if (RequestUriUtils.isApiRequest(request.getContextPath(), request.getRequestURI())) {response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);response.setContentType("application/json");response.setCharacterEncoding("UTF-8");diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.javaindex f7b6e465b8..58514de424 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java@@ -313,11 +313,10 @@ public class SecurityConfiguration {exceptions ->exceptions.defaultAuthenticationEntryPointFor(jwtAuthenticationEntryPoint,- request -> {- String contextPath = request.getContextPath();- String requestURI = request.getRequestURI();- return requestURI.startsWith(contextPath + "/api/");- }));+ request ->+ RequestUriUtils.isApiRequest(+ request.getContextPath(),+ request.getRequestURI())));http.logout(logout ->diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.javaindex aa3efd266b..dfc007a00e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/DatabaseLicenseFilter.java@@ -15,6 +15,7 @@ import jakarta.servlet.http.HttpServletResponse;import lombok.RequiredArgsConstructor;+import stirling.software.common.util.RequestUriUtils;import stirling.software.proprietary.security.configuration.ee.DatabaseLicenseGuard;/** Restricts an unlicensed external database to reading, setup and account/licence recovery. */@@ -36,7 +37,13 @@ public class DatabaseLicenseFilter extends OncePerRequestFilter {protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {- String path = request.getRequestURI().substring(request.getContextPath().length());+ String path;+ try {+ path = RequestUriUtils.normalizeUri(request.getContextPath(), request.getRequestURI());+ } catch (IllegalArgumentException e) {+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);+ return;+ }if (!path.startsWith("/api/")|| Set.of("GET", "HEAD", "OPTIONS").contains(request.getMethod())|| path.startsWith("/api/v1/auth/")diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.javaindex 4e9112edcb..ef9b554267 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilter.java@@ -14,6 +14,7 @@ import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import stirling.software.common.service.LicenseServiceInterface;+import stirling.software.common.util.RequestUriUtils;@Component@Order(Ordered.HIGHEST_PRECEDENCE + 20)@@ -29,17 +30,16 @@ public class EnterpriseEndpointFilter extends OncePerRequestFilter {HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {- if (isPrometheusEndpointRequest(request) && !licenseService.isRunningProOrHigher()) {- // Allow only health checks to pass through for non-pro users- String uri = request.getRequestURI();-- // Strip the context path- String contextPath = request.getContextPath();- String trimmedUri =- (contextPath != null && uri.startsWith(contextPath))- ? uri.substring(contextPath.length())- : uri;+ String trimmedUri;+ try {+ trimmedUri =+ RequestUriUtils.normalizeUri(request.getContextPath(), request.getRequestURI());+ } catch (IllegalArgumentException e) {+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);+ return;+ }+ if (trimmedUri.contains("/actuator/") && !licenseService.isRunningProOrHigher()) {boolean isHealthCheck =trimmedUri.startsWith("/actuator/health")|| "/health".equals(trimmedUri)@@ -54,8 +54,4 @@ public class EnterpriseEndpointFilter extends OncePerRequestFilter {}filterChain.doFilter(request, response);}-- private boolean isPrometheusEndpointRequest(HttpServletRequest request) {- return request.getRequestURI().contains("/actuator/");- }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.javaindex ed8001df5a..df98cc2f53 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java@@ -1,5 +1,6 @@package stirling.software.proprietary.security.filter;+import static stirling.software.common.util.RequestUriUtils.isApiRequest;import static stirling.software.common.util.RequestUriUtils.isPublicAuthEndpoint;import static stirling.software.common.util.RequestUriUtils.isStaticResource;import static stirling.software.proprietary.security.model.AuthenticationType.OAUTH2;@@ -87,7 +88,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {// No JWT token and not a public endpoint// For API requests, return 401 JSONString acceptHeader = request.getHeader("Accept");- if (requestURI.startsWith(contextPath + "/api/")+ if (isApiRequest(contextPath, requestURI)|| (acceptHeader != null && acceptHeader.contains("application/json"))) {response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);response.setContentType("application/json");diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.javaindex 8fe351ccde..54bea98c2b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/UserAuthenticationFilter.java@@ -300,17 +300,23 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {// For API routes, only skip filter for these public endpointsString[] publicApiPatterns = {- contextPath + "/api/v1/info/status",- contextPath + "/api/v1/auth/login",- contextPath + "/api/v1/auth/refresh",- contextPath + "/api/v1/auth/me",- contextPath + "/api/v1/invite/validate",- contextPath + "/api/v1/invite/accept",- contextPath + "/api/v1/ui-data/footer-info"+ "/api/v1/info/status",+ "/api/v1/auth/login",+ "/api/v1/auth/refresh",+ "/api/v1/auth/me",+ "/api/v1/invite/validate",+ "/api/v1/invite/accept",+ "/api/v1/ui-data/footer-info"};+ String normalizedUri;+ try {+ normalizedUri = RequestUriUtils.normalizeUri(contextPath, uri);+ } catch (IllegalArgumentException e) {+ return false;+ }for (String pattern : publicApiPatterns) {- if (uri.startsWith(pattern)) {+ if (normalizedUri.startsWith(pattern)) {return true;}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.javaindex 94b7421dae..648d3f6d62 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java@@ -3,7 +3,6 @@ package stirling.software.proprietary.security.oauth2;import static stirling.software.proprietary.security.model.AuthenticationType.OAUTH2;import java.io.IOException;-import java.net.URI;import java.sql.SQLException;import java.util.Map;import java.util.Optional;@@ -100,10 +99,7 @@ public class CustomOAuth2AuthenticationSuccessHandlerreturn;}boolean isSsoUser = userService.isSsoAuthenticationTypeByUsername(username);- if (userExists- && userService.hasPassword(username)- && !isSsoUser- && oauth2Properties.getAutoCreateUser()) {+ if (userExists && userService.hasPassword(username) && !isSsoUser) {response.sendRedirect(contextPath + "/logout?oAuth2AuthenticationErrorWeb=true");return;}@@ -206,11 +202,7 @@ public class CustomOAuth2AuthenticationSuccessHandlerString redirectPath = resolveRedirectPath(request, pathPrefix);Optional<String> configuredBase =usesCookiePath ? landingBase.flatMap(RedirectBaseUrl::origin) : landingBase;- String origin =- configuredBase- .or(() -> resolveForwardedOrigin(request))- .or(() -> resolveOriginFromReferer(request))- .orElseGet(() -> buildOriginFromRequest(request));+ String origin = configuredBase.orElse("");clearRedirectCookie(response);// Extract nonce from state for CSRF validation in callback@@ -235,90 +227,9 @@ public class CustomOAuth2AuthenticationSuccessHandlerprivate String cookieRedirectPath(HttpServletRequest request) {String cookiePath = TauriOAuthUtils.extractRedirectPathFromCookie(request);- return cookiePath != null && cookiePath.startsWith("/") ? cookiePath : null;- }-- private Optional<String> resolveForwardedOrigin(HttpServletRequest request) {- String forwardedHostHeader = request.getHeader("X-Forwarded-Host");- if (forwardedHostHeader == null || forwardedHostHeader.isBlank()) {- return Optional.empty();- }- String host = forwardedHostHeader.split(",")[0].trim();- if (host.isEmpty()) {- return Optional.empty();- }-- String forwardedProtoHeader = request.getHeader("X-Forwarded-Proto");- String proto =- (forwardedProtoHeader == null || forwardedProtoHeader.isBlank())- ? request.getScheme()- : forwardedProtoHeader.split(",")[0].trim();-- if (!host.contains(":")) {- String forwardedPort = request.getHeader("X-Forwarded-Port");- if (forwardedPort != null- && !forwardedPort.isBlank()- && !isDefaultPort(proto, forwardedPort.trim())) {- host = host + ":" + forwardedPort.trim();- }- }- return Optional.of(proto + "://" + host);- }-- private Optional<String> resolveOriginFromReferer(HttpServletRequest request) {- String referer = request.getHeader("Referer");- if (referer != null && !referer.isEmpty()) {- try {- URI refererUri = URI.create(referer);- String host = refererUri.getHost();- if (host == null) {- return Optional.empty();- }-- String refererHost = host.toLowerCase();-- if (!isOAuthProviderDomain(refererHost)) {- String origin = refererUri.getScheme() + "://" + host;- int port = refererUri.getPort();- if (port != -1 && port != 80 && port != 443) {- origin += ":" + port;- }- return Optional.of(origin);- }- } catch (IllegalArgumentException e) {- // ignore and fall back- }- }- return Optional.empty();- }-- private String buildOriginFromRequest(HttpServletRequest request) {- String scheme = request.getScheme();- String serverName = request.getServerName();- int serverPort = request.getServerPort();-- StringBuilder origin = new StringBuilder();- origin.append(scheme).append("://").append(serverName);-- if ((!"http".equalsIgnoreCase(scheme) || serverPort != 80)- && (!"https".equalsIgnoreCase(scheme) || serverPort != 443)) {- origin.append(":").append(serverPort);- }-- return origin.toString();- }-- private boolean isDefaultPort(String scheme, String port) {- if (port == null) {- return true;- }- try {- int parsedPort = Integer.parseInt(port);- return ("http".equalsIgnoreCase(scheme) && parsedPort == 80)- || ("https".equalsIgnoreCase(scheme) && parsedPort == 443);- } catch (NumberFormatException e) {- return false;- }+ return cookiePath != null && TauriOAuthUtils.isLocalRedirectPath(cookiePath)+ ? cookiePath+ : null;}private void clearRedirectCookie(HttpServletResponse response) {@@ -330,20 +241,4 @@ public class CustomOAuth2AuthenticationSuccessHandler.build();response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());}-- /**- * Checks if the given hostname belongs to a known OAuth provider.- *- * @param hostname The hostname to check- * @return true if it's an OAuth provider domain, false otherwise- */- private boolean isOAuthProviderDomain(String hostname) {- return hostname.contains("google.com")- || hostname.contains("googleapis.com")- || hostname.contains("github.com")- || hostname.contains("microsoft.com")- || hostname.contains("microsoftonline.com")- || hostname.contains("linkedin.com")- || hostname.contains("apple.com");- }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/TauriOAuthUtils.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/TauriOAuthUtils.javaindex 4d801f90c4..c27dd192bb 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/TauriOAuthUtils.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/TauriOAuthUtils.java@@ -1,5 +1,7 @@package stirling.software.proprietary.security.oauth2;+import java.net.URI;+import jakarta.servlet.http.Cookie;import jakarta.servlet.http.HttpServletRequest;@@ -111,12 +113,33 @@ public final class TauriOAuthUtils {}for (Cookie cookie : cookies) {if (SPA_REDIRECT_COOKIE.equals(cookie.getName())) {- String value =- java.net.URLDecoder.decode(- cookie.getValue(), java.nio.charset.StandardCharsets.UTF_8);- return value.trim().isEmpty() ? null : value.trim();+ try {+ String value =+ java.net.URLDecoder.decode(+ cookie.getValue(), java.nio.charset.StandardCharsets.UTF_8);+ return value.trim().isEmpty() ? null : value.trim();+ } catch (IllegalArgumentException e) {+ return null;+ }}}return null;}++ public static boolean isLocalRedirectPath(String path) {+ try {+ URI uri = URI.create(path);+ String decoded = uri.getPath();+ return !uri.isAbsolute()+ && uri.getRawAuthority() == null+ && uri.getRawFragment() == null+ && decoded != null+ && decoded.startsWith("/")+ && !decoded.startsWith("//")+ && !decoded.contains("\\")+ && decoded.chars().noneMatch(c -> c < 32 || c == 127);+ } catch (IllegalArgumentException e) {+ return false;+ }+ }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.javaindex fc3fe311a0..da4eeea4a5 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/CustomSaml2AuthenticationSuccessHandler.java@@ -3,7 +3,6 @@ package stirling.software.proprietary.security.saml2;import static stirling.software.proprietary.security.model.AuthenticationType.SAML2;import java.io.IOException;-import java.net.URI;import java.net.URLDecoder;import java.nio.charset.StandardCharsets;import java.sql.SQLException;@@ -126,10 +125,7 @@ public class CustomSaml2AuthenticationSuccessHandlerisSsoUser,isSAML2User);- if (userExists- && hasPassword- && !isSsoUser- && saml2Properties.getAutoCreateUser()) {+ if (userExists && hasPassword && !isSsoUser) {log.debug("User {} exists with password but is not an SSO user, redirecting to logout",username);@@ -263,7 +259,7 @@ public class CustomSaml2AuthenticationSuccessHandlerreturn TauriOAuthUtils.defaultTauriCallbackPath(contextPath);}return extractRedirectPathFromCookie(request)- .filter(CustomSaml2AuthenticationSuccessHandler::isLocalRedirectPath)+ .filter(TauriOAuthUtils::isLocalRedirectPath).orElseGet(() -> defaultCallbackPath(contextPath));}@@ -296,23 +292,6 @@ public class CustomSaml2AuthenticationSuccessHandlerreturn contextPath + DEFAULT_CALLBACK_PATH;}- private static boolean isLocalRedirectPath(String path) {- try {- URI uri = URI.create(path);- String decoded = uri.getPath();- return !uri.isAbsolute()- && uri.getRawAuthority() == null- && uri.getRawFragment() == null- && decoded != null- && decoded.startsWith("/")- && !decoded.startsWith("//")- && !decoded.contains("\\")- && decoded.chars().noneMatch(c -> c < 32 || c == 127);- } catch (IllegalArgumentException e) {- return false;- }- }-private void clearRedirectCookie(HttpServletResponse response) {ResponseCookie cookie =ResponseCookie.from(SPA_REDIRECT_COOKIE, "")diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.javaindex 4e4d84ef66..b6ac33676e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java@@ -1099,9 +1099,10 @@ public class AuditService {// Try X-Forwarded-For first (set by proxies/load balancers)String forwardedFor = request.getHeader("X-Forwarded-For");if (StringUtils.isNotBlank(forwardedFor)) {- // X-Forwarded-For can contain multiple IPs, take the first one (original client)- String[] ips = forwardedFor.split(",");- return ips[0].trim();+ String first = forwardedFor.split(",", 2)[0].trim();+ if (!first.isEmpty()) {+ return first;+ }}// Try X-Real-IP (used by some proxies)diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.javaindex ab0c1a8d19..79883527a5 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java@@ -251,6 +251,24 @@ class ControllerAuditAspectTest {assertThat(data).containsEntry("errorType", "IllegalStateException");assertThat(data).containsEntry("errorMessage", "boom");}++ @Test+ @DisplayName("failure while capturing context leaves nothing in the MDC")+ void captureFailureRestoresMdc() throws Throwable {+ ProceedingJoinPoint jp = joinPointFor("postEndpoint");+ when(auditService.shouldAudit(any(), any(Method.class), eq(auditConfig)))+ .thenReturn(true);+ when(auditService.captureCurrentPrincipal()).thenReturn("alice");+ when(auditService.captureCurrentOrigin()).thenThrow(new IllegalStateException("boom"));++ assertThatThrownBy(() -> aspect.auditPostMethod(jp))+ .isInstanceOf(IllegalStateException.class)+ .hasMessage("boom");++ assertThat(MDC.get("auditPrincipal")).isNull();+ assertThat(MDC.get("auditOrigin")).isNull();+ verify(jp, never()).proceed();+ }}@Nesteddiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.javaindex 5bb4c4c8be..3a24cd75a7 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import java.nio.file.Files;import java.nio.file.Path;import java.util.List;@@ -61,9 +62,10 @@ class FolderAccessGuardTest {sourceStore);}- private FolderAccessGuard guardWithWatchedFolder(String watchedDir) {+ private FolderAccessGuard guardWithWatchedFolder(String watchedDir, List<String> allowedRoots) {ApplicationProperties properties = new ApplicationProperties();properties.getSecurity().setEnableLogin(true);+ properties.getPolicies().setAllowedFolderRoots(allowedRoots);properties.getSystem().getCustomPaths()@@ -162,39 +164,127 @@ class FolderAccessGuardTest {}@Test- void permitsTheLocalServerStorageDirectoryEvenWithNoConfiguredRoots() {+ void rejectsTheLocalStorageDirectoryEvenInsideAnAllowedRoot() {Path storageBase = tempDir.resolve("storage");FolderAccessGuard guard =- guardWithStorage(List.of(), true, "local", storageBase.toString());- Path within = storageBase.resolve("inbox");+ guardWithStorage(+ List.of(tempDir.toString()), true, "local", storageBase.toString());- assertEquals(within.toAbsolutePath().normalize(), guard.requirePermitted(within));+ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(storageBase.resolve("4")));+ assertFalse(ex instanceof FolderAccessDeniedException);+ assertThrows(IllegalArgumentException.class, () -> guard.requirePermitted(storageBase));+ assertTrue(guard.isProtected(storageBase.resolve("4").resolve("doc.pdf")));+ assertFalse(guard.isProtected(tempDir));}@Test- void ignoresServerStorageWhenTheStorageFeatureIsDisabled() {+ void rejectsTheStorageDirectoryWhateverTheProviderOrEnabledFlag() {+ Path storageBase = tempDir.resolve("storage");+ for (FolderAccessGuard guard :+ List.of(+ guardWithStorage(+ List.of(tempDir.toString()),+ false,+ "local",+ storageBase.toString()),+ guardWithStorage(+ List.of(tempDir.toString()), true, "s3", storageBase.toString()))) {+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(storageBase.resolve("4")));+ }+ }++ @Test+ void rejectsTheStorageDirectoryWithNoConfiguredRoots() {Path storageBase = tempDir.resolve("storage");FolderAccessGuard guard =- guardWithStorage(List.of(), false, "local", storageBase.toString());+ guardWithStorage(List.of(), true, "local", storageBase.toString());- assertThrows(IllegalArgumentException.class, () -> guard.requirePermitted(storageBase));+ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(storageBase.resolve("3")));+ assertFalse(ex instanceof FolderAccessDeniedException);}@Test- void ignoresServerStorageWhenTheProviderIsNotLocal() {- Path storageBase = tempDir.resolve("storage");- FolderAccessGuard guard = guardWithStorage(List.of(), true, "s3", storageBase.toString());+ void rejectsPipelineWatchedFoldersWithNoConfiguredRoots() {+ Path watched = tempDir.resolve("watched");+ FolderAccessGuard guard = guardWithWatchedFolder(watched.toString(), List.of());- assertThrows(IllegalArgumentException.class, () -> guard.requirePermitted(storageBase));+ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(watched.resolve("drop")));+ assertFalse(ex instanceof FolderAccessDeniedException);+ assertTrue(guard.isProtected(watched.resolve("drop").resolve("config.json")));}@Test- void permitsPipelineWatchedFoldersEvenWithNoConfiguredRoots() {+ void rejectsPipelineWatchedFoldersEvenInsideAnAllowedRoot() {+ Path watched = tempDir.resolve("pipeline").resolve("watchedFolders");+ FolderAccessGuard guard =+ guardWithWatchedFolder(watched.toString(), List.of(tempDir.toString()));++ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(watched.resolve("drop")));+ assertFalse(ex instanceof FolderAccessDeniedException);+ assertThrows(IllegalArgumentException.class, () -> guard.requirePermitted(watched));+ assertEquals(+ tempDir.resolve("pipeline").resolve("finishedFolders").toAbsolutePath().normalize(),+ guard.requirePermitted(tempDir.resolve("pipeline").resolve("finishedFolders")));+ }++ @Test+ void rejectsPipelineWatchedFoldersInTheDesktopBundle() {Path watched = tempDir.resolve("watched");- FolderAccessGuard guard = guardWithWatchedFolder(watched.toString());- Path within = watched.resolve("inbox");+ withDesktopBundle(+ () ->+ assertThrows(+ IllegalArgumentException.class,+ () ->+ guardWithWatchedFolder(watched.toString(), List.of())+ .requirePermitted(watched.resolve("drop"))));+ }- assertEquals(within.toAbsolutePath().normalize(), guard.requirePermitted(within));+ @Test+ void rejectsRelativePaths() {+ FolderAccessGuard guard =+ guardWithStorage(+ List.of(Path.of("").toAbsolutePath().toString()), true, "local", "storage");++ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(Path.of("storage", "3")));+ assertFalse(ex instanceof FolderAccessDeniedException);+ assertThrows(+ IllegalArgumentException.class,+ () -> guard.requirePermitted(Path.of("pipeline", "watchedFolders", "drop")));+ assertTrue(guard.isProtected(Path.of("storage", "3")));+ }++ @Test+ void rejectsASymlinkInsideAnAllowedRootThatPointsIntoAProtectedRoot() throws Exception {+ Path watched = Files.createDirectories(tempDir.resolve("watched"));+ Path allowed = Files.createDirectories(tempDir.resolve("allowed"));+ Path link = Files.createSymbolicLink(allowed.resolve("link"), watched);+ FolderAccessGuard guard =+ guardWithWatchedFolder(watched.toString(), List.of(allowed.toString()));++ assertThrows(IllegalArgumentException.class, () -> guard.requirePermitted(link));+ assertThrows(+ IllegalArgumentException.class, () -> guard.requirePermitted(link.resolve("drop")));+ assertTrue(guard.isProtected(link.resolve("drop")));+ assertEquals(+ allowed.resolve("inbox").toAbsolutePath().normalize(),+ guard.requirePermitted(allowed.resolve("inbox")));}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.javaindex 0ada2d781e..6205178322 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/FolderInputSourceTest.java@@ -312,6 +312,35 @@ class FolderInputSourceTest {assertTrue(ctx.present.stream().noneMatch(identity -> identity.endsWith("half-delivered")));}+ @Test+ void storageDirectoryIsRejectedAndPrunedFromAnAncestorsRecursiveWalk() throws IOException {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getSecurity().setEnableLogin(true);+ properties.getPolicies().setAllowedFolderRoots(List.of(tempDir.toString()));+ Path storage = Files.createDirectories(tempDir.resolve("storage"));+ properties.getStorage().getLocal().setBasePath(storage.toString());+ FolderInputSource guarded =+ new FolderInputSource(+ readinessChecker,+ new FolderAccessGuard(+ properties,+ new RuntimePathConfig(properties),+ new StandardEnvironment(),+ new InProcessSourceStore()));+ Path victimDir = Files.createDirectories(storage.resolve("4"));+ Files.writeString(victimDir.resolve("secret.pdf"), "victim");+ Files.writeString(tempDir.resolve("mine.pdf"), "mine");++ assertThrows(+ IllegalArgumentException.class,+ () -> guarded.resolve(InputSpec.folder(victimDir.toString()), ctx));+ InputSpec ancestor =+ new InputSpec(+ "folder", Map.of("directory", tempDir.toString(), "recursive", "true"));+ assertEquals(1, guarded.resolve(ancestor, ctx).size());+ assertTrue(ctx.present.stream().noneMatch(identity -> identity.endsWith("secret.pdf")));+ }+@Testvoid unreadyFilesAreReportedPresentButNotClaimed() throws IOException {Path inputDir = Files.createDirectories(tempDir.resolve("in"));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.javaindex dfff624ed6..af5a2e1844 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/PolicyOutputResolverTest.java@@ -74,6 +74,33 @@ class PolicyOutputResolverTest {() -> resolver.resolve(policy().withOutputIds(List.of(archive.id(), "missing"))));}+ @Test+ void aDestinationFromAnotherTeamIsRejectedAtRunTime() {+ Source foreign =+ sourceStore.save(+ new Source(+ null,+ "Theirs",+ "folder",+ Map.of("directory", "/out"),+ true,+ "x",+ 2L));+ Policy teamed =+ new Policy(+ "p1",+ "Pipeline",+ "owner",+ true,+ List.of(),+ List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),+ OutputSpec.inline(),+ List.of(foreign.id()),+ 1L);++ assertThrows(IllegalArgumentException.class, () -> resolver.resolve(teamed));+ }+private static Source folder(String name, String directory) {return new Source(null, name, "folder", Map.of("directory", directory), true, "owner", null);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/s3/S3ConnectionPoolTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/s3/S3ConnectionPoolTest.javanew file mode 100644index 0000000000..9e75ea9bfd--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/s3/S3ConnectionPoolTest.java@@ -0,0 +1,122 @@+package stirling.software.proprietary.policy.s3;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatCode;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;++import java.util.concurrent.atomic.AtomicInteger;++import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.cluster.s3.S3Clients;++import software.amazon.awssdk.services.s3.S3Client;++class S3ConnectionPoolTest {++ private static final S3Config LOOPBACK_ENDPOINT =+ new S3Config(+ "inbox",+ null,+ null,+ "http://127.0.0.1:9000",+ "AKIAEXAMPLE",+ "shh",+ false,+ null,+ null);++ private static final S3Config REBINDING_ENDPOINT =+ new S3Config(+ "inbox",+ "us-east-1",+ null,+ "http://bucket.attacker.test:9000",+ "AKIAEXAMPLE",+ "shh",+ false,+ null,+ null);++ @Test+ void rejectsAPrivateEndpointWithoutTheOperatorOptIn() {+ ApplicationProperties properties = new ApplicationProperties();+ AtomicInteger built = new AtomicInteger();+ S3ConnectionPool pool =+ new S3ConnectionPool(+ properties,+ config -> {+ built.incrementAndGet();+ return mock(S3Client.class);+ });++ assertThatThrownBy(() -> pool.clientFor(LOOPBACK_ENDPOINT))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("allowPrivateS3Endpoints");+ assertThat(built).hasValue(0);+ }++ @Test+ void guardsACachedClientOnEveryUse() {+ ApplicationProperties properties = new ApplicationProperties();+ AtomicInteger built = new AtomicInteger();+ S3ConnectionPool pool =+ new S3ConnectionPool(+ properties,+ config -> {+ built.incrementAndGet();+ return mock(S3Client.class);+ });++ properties.getPolicies().setAllowPrivateS3Endpoints(true);+ assertThatCode(() -> pool.clientFor(LOOPBACK_ENDPOINT)).doesNotThrowAnyException();+ assertThat(built).hasValue(1);++ properties.getPolicies().setAllowPrivateS3Endpoints(false);+ assertThatThrownBy(() -> pool.clientFor(LOOPBACK_ENDPOINT))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("allowPrivateS3Endpoints");+ assertThat(built).hasValue(1);+ }++ @Test+ void refusesACachedConfigWhenTheNameRebindsToABlockedAddress() {+ ApplicationProperties properties = new ApplicationProperties();+ AtomicInteger built = new AtomicInteger();+ S3ConnectionPool pool =+ new S3ConnectionPool(+ properties,+ config -> {+ built.incrementAndGet();+ return mock(S3Client.class);+ });++ try (MockedStatic<S3Clients> s3Clients = mockStatic(S3Clients.class)) {+ s3Clients+ .when(() -> S3Clients.validateEndpointHost(any(), anyBoolean(), any(), any()))+ .thenAnswer(invocation -> null);+ assertThatCode(() -> pool.clientFor(REBINDING_ENDPOINT)).doesNotThrowAnyException();+ assertThat(built).hasValue(1);++ s3Clients+ .when(() -> S3Clients.validateEndpointHost(any(), anyBoolean(), any(), any()))+ .thenThrow(+ new IllegalStateException(+ "S3 source endpoint host 'bucket.attacker.test' resolves to"+ + " private/link-local address 127.0.0.1; set"+ + " policies.allowPrivateS3Endpoints=true to opt in"));++ assertThatThrownBy(() -> pool.clientFor(REBINDING_ENDPOINT))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("127.0.0.1")+ .hasMessageContaining("allowPrivateS3Endpoints");+ assertThat(built).hasValue(1);+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/JwtAuthenticationEntryPointTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/JwtAuthenticationEntryPointTest.javaindex 0fcd0f4c68..978545b799 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/JwtAuthenticationEntryPointTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/JwtAuthenticationEntryPointTest.java@@ -1,5 +1,7 @@package stirling.software.proprietary.security;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.*;import java.io.IOException;@@ -9,6 +11,8 @@ import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;@@ -37,4 +41,18 @@ class JwtAuthenticationEntryPointTest {verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, errorMessage);}++ @Test+ void percentEncodedApiPathGetsJsonError() throws IOException {+ when(authException.getMessage()).thenReturn("Authentication required");+ MockHttpServletRequest encoded =+ new MockHttpServletRequest("GET", "/app/%61pi/v1/info/load/all");+ encoded.setContextPath("/app");+ MockHttpServletResponse result = new MockHttpServletResponse();++ jwtAuthenticationEntryPoint.commence(encoded, result, authException);++ assertEquals(HttpServletResponse.SC_UNAUTHORIZED, result.getStatus());+ assertTrue(result.getContentType().startsWith("application/json"));+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.javaindex b270fce3b7..6c2e7a0c46 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/EnterpriseEndpointFilterTest.java@@ -32,4 +32,34 @@ class EnterpriseEndpointFilterTest {assertEquals(404, revoked.getStatus());}}++ @Test+ void percentEncodedActuatorPathIsGatedLikeThePlainPath() throws Exception {+ LicenseServiceInterface license = mock(LicenseServiceInterface.class);+ when(license.isRunningProOrHigher()).thenReturn(false);+ EnterpriseEndpointFilter filter = new EnterpriseEndpointFilter(license);++ MockHttpServletRequest encoded =+ new MockHttpServletRequest("GET", "/%61ctuator/prometheus");+ MockHttpServletResponse blocked = new MockHttpServletResponse();+ filter.doFilter(encoded, blocked, (req, res) -> res.setContentType("passed"));+ assertEquals(404, blocked.getStatus());++ MockHttpServletRequest health = new MockHttpServletRequest("GET", "/%61ctuator/health");+ MockHttpServletResponse allowed = new MockHttpServletResponse();+ filter.doFilter(health, allowed, (req, res) -> res.setContentType("passed"));+ assertEquals("passed", allowed.getContentType());+ }++ @Test+ void malformedEscapeIsRejected() throws Exception {+ EnterpriseEndpointFilter filter =+ new EnterpriseEndpointFilter(mock(LicenseServiceInterface.class));+ MockHttpServletResponse response = new MockHttpServletResponse();+ filter.doFilter(+ new MockHttpServletRequest("GET", "/actuator/%zz"),+ response,+ (req, res) -> res.setContentType("passed"));+ assertEquals(400, response.getStatus());+ }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.javaindex c4d7d09969..7efc30036d 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/LicenseFilterHttpTest.java@@ -99,6 +99,17 @@ class LicenseFilterHttpTest {assertThat(request("POST", "/api/v1/misc/compress-pdf")).isEqualTo(402);}+ @Test+ void percentEncodedPathsAreGatedLikeThePlainPath() throws Exception {+ assertThat(request("GET", "/actuator/prometheus")).isEqualTo(404);+ assertThat(request("GET", "/%61ctuator/prometheus")).isEqualTo(404);+ assertThat(request("GET", "/%61ctuator/health")).isEqualTo(204);+ properties.getSystem().getDatasource().setEnableCustomDatabase(true);+ assertThat(request("POST", "/%61pi/v1/misc/compress-pdf")).isEqualTo(402);+ assertThat(request("POST", "/api/v1/misc/%63ompress-pdf")).isEqualTo(402);+ assertThat(request("POST", "/api/v1/account-link/connect/st%61rt")).isEqualTo(204);+ }+@SpringBootConfiguration@EnableAutoConfiguration@Import({diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.javaindex df87c30e1b..6a6a5aa77f 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/filter/UserAuthenticationFilterTest.java@@ -265,5 +265,42 @@ class UserAuthenticationFilterTest {assertThat(filter(true).shouldNotFilter(request)).isFalse();}++ @Test+ @DisplayName("does not skip a percent-encoded API path on GET")+ void doesNotSkipEncodedApiPathOnGet() {+ request.setMethod("GET");+ request.setRequestURI("/%61pi/v1/info/load/all");++ assertThat(filter(true).shouldNotFilter(request)).isFalse();+ }++ @Test+ @DisplayName("does not skip a percent-encoded API path under a context path")+ void doesNotSkipEncodedApiPathUnderContextPath() {+ request.setMethod("GET");+ request.setContextPath("/app");+ request.setRequestURI("/app/a%70i/v1/general/files/x.png");++ assertThat(filter(true).shouldNotFilter(request)).isFalse();+ }++ @Test+ @DisplayName("does not skip a malformed escape")+ void doesNotSkipMalformedEscape() {+ request.setMethod("GET");+ request.setRequestURI("/%zz");++ assertThat(filter(true).shouldNotFilter(request)).isFalse();+ }++ @Test+ @DisplayName("still skips the frontend root on GET")+ void skipsFrontendRootOnGet() {+ request.setMethod("GET");+ request.setRequestURI("/");++ assertThat(filter(true).shouldNotFilter(request)).isTrue();+ }}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.javaindex df942fd09c..ef734b7f89 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java@@ -96,17 +96,14 @@ class CustomOAuth2AuthenticationSuccessHandlerTest {handler.onAuthenticationSuccess(request, response, authentication);- assertEquals(- "http://localhost:8080/auth/callback/tauri#access_token=jwt",- response.getRedirectedUrl());+ assertEquals("/auth/callback/tauri#access_token=jwt", response.getRedirectedUrl());}@ParameterizedTest@CsvSource(value = {- "'', '', '', http://hcrn-fs01:8080/auth/callback#access_token=jwt",- "'', https://app.example.com, '',"- + " http://hcrn-fs01:8080/auth/callback#access_token=jwt",+ "'', '', '', /auth/callback#access_token=jwt",+ "'', https://app.example.com, '', /auth/callback#access_token=jwt","https://pdf.example.com/, '', '',"+ " https://pdf.example.com/auth/callback#access_token=jwt","https://api.example.com, https://app.example.com/, '',"@@ -169,6 +166,52 @@ class CustomOAuth2AuthenticationSuccessHandlerTest {assertEquals(expected, response.getRedirectedUrl());}+ @ParameterizedTest+ @CsvSource({"true", "false"})+ void localPasswordAccountIsRefusedRegardlessOfAutoCreateUser(boolean autoCreateUser)+ throws Exception {+ LoginAttemptService loginAttemptService = mock(LoginAttemptService.class);+ UserService userService = mock(UserService.class);+ JwtServiceInterface jwtService = mock(JwtServiceInterface.class);+ UserLicenseSettingsService licenseSettingsService = mock(UserLicenseSettingsService.class);+ ApplicationProperties properties = new ApplicationProperties();+ ApplicationProperties.Security.OAUTH2 oauth2 = properties.getSecurity().getOauth2();+ oauth2.setAutoCreateUser(autoCreateUser);+ oauth2.setBlockRegistration(false);++ when(userService.usernameExistsIgnoreCase("admin")).thenReturn(true);+ when(userService.isUserDisabled("admin")).thenReturn(false);+ when(userService.hasPassword("admin")).thenReturn(true);+ when(userService.isSsoAuthenticationTypeByUsername("admin")).thenReturn(false);++ CustomOAuth2AuthenticationSuccessHandler handler =+ new CustomOAuth2AuthenticationSuccessHandler(+ loginAttemptService,+ oauth2,+ userService,+ jwtService,+ licenseSettingsService,+ properties);+ DefaultOAuth2User principal =+ new DefaultOAuth2User(+ List.of(new SimpleGrantedAuthority("ROLE_USER")),+ Map.of("sub", "provider-sub", "name", "admin"),+ "name");+ OAuth2AuthenticationToken authentication =+ new OAuth2AuthenticationToken(principal, principal.getAuthorities(), "google");+ MockHttpServletRequest request = new MockHttpServletRequest();+ request.setContextPath("/stirling");+ MockHttpServletResponse response = new MockHttpServletResponse();++ handler.onAuthenticationSuccess(request, response, authentication);++ assertEquals(+ "/stirling/logout?oAuth2AuthenticationErrorWeb=true", response.getRedirectedUrl());+ verify(userService, never())+ .processSSOPostLogin(anyString(), anyString(), anyString(), anyBoolean(), any());+ verifyNoInteractions(jwtService);+ }+@ParameterizedTest@CsvSource({"NORMAL, 4, false, false, true",diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2RedirectTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2RedirectTest.javanew file mode 100644index 0000000000..ec71aac531--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2RedirectTest.java@@ -0,0 +1,90 @@+package stirling.software.proprietary.security.oauth2;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.*;++import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;+import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockHttpServletResponse;+import org.springframework.security.core.Authentication;+import org.springframework.security.core.authority.SimpleGrantedAuthority;+import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;+import org.springframework.security.oauth2.core.user.DefaultOAuth2User;++import jakarta.servlet.http.Cookie;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.service.JwtServiceInterface;+import stirling.software.proprietary.security.service.LoginAttemptService;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.proprietary.service.UserLicenseSettingsService;++class OAuth2RedirectTest {+ @ParameterizedTest+ @ValueSource(+ strings = {+ "//attacker.example/callback",+ "/\\attacker.example/callback",+ "/%2f%2fattacker.example/callback",+ "/auth/callback#redirect",+ "/%0d%0aLocation:evil",+ "%"+ })+ void untrustedHeadersAndCookiesCannotReceiveTheToken(String path) throws Exception {+ assertThat(login(null, path)).isEqualTo("/auth/callback#access_token=test-token");+ }++ @Test+ void configuredRedirectBaseAndLocalCallbackRemainSupported() throws Exception {+ assertThat(login("https://app.example", "/app/auth/callback"))+ .isEqualTo("https://app.example/app/auth/callback#access_token=test-token");+ assertThat(login(null, "/app/auth/callback"))+ .isEqualTo("/app/auth/callback#access_token=test-token");+ }++ private String login(String redirectBaseUrl, String path) throws Exception {+ var properties = new ApplicationProperties();+ var oauth2 = properties.getSecurity().getOauth2();+ oauth2.setRedirectBaseUrl(redirectBaseUrl);+ oauth2.setAutoCreateUser(true);+ oauth2.setBlockRegistration(false);+ var jwt = mock(JwtServiceInterface.class);+ when(jwt.isJwtEnabled()).thenReturn(true);+ when(jwt.generateToken(any(Authentication.class), anyMap())).thenReturn("test-token");+ var users = mock(UserService.class);+ when(users.usernameExistsIgnoreCase("verified-user")).thenReturn(true);+ var handler =+ new CustomOAuth2AuthenticationSuccessHandler(+ mock(LoginAttemptService.class),+ oauth2,+ users,+ jwt,+ mock(UserLicenseSettingsService.class),+ properties);+ var principal =+ new DefaultOAuth2User(+ List.of(new SimpleGrantedAuthority("ROLE_USER")),+ Map.of("sub", "provider-sub", "name", "verified-user"),+ "name");+ var authentication =+ new OAuth2AuthenticationToken(principal, principal.getAuthorities(), "corpidp");+ var request = new MockHttpServletRequest();+ request.addHeader("Referer", "https://attacker.example/");+ request.addHeader("X-Forwarded-Host", "attacker.example");+ request.addHeader("X-Forwarded-Proto", "https");+ request.setServerName("attacker.example");+ request.setCookies(+ new Cookie(+ "stirling_redirect_path", URLEncoder.encode(path, StandardCharsets.UTF_8)));+ var response = new MockHttpServletResponse();+ handler.onAuthenticationSuccess(request, response, authentication);+ return response.getRedirectedUrl();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AuditServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AuditServiceTest.javaindex ab0b3437bb..e1541c5d24 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AuditServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AuditServiceTest.java@@ -691,6 +691,16 @@ class AuditServiceTest {assertThat(service.extractClientIp(request)).isEqualTo("203.0.113.1");}+ @Test+ @DisplayName("X-Forwarded-For without a first IP falls through")+ void forwardedForWithoutFirstIp() {+ MockHttpServletRequest request = new MockHttpServletRequest();+ request.addHeader("X-Forwarded-For", ",");+ request.setRemoteAddr("127.0.0.5");++ assertThat(service.extractClientIp(request)).isEqualTo("127.0.0.5");+ }+@Test@DisplayName("X-Real-IP used when no forwarded header")void realIp() {diff --git a/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java b/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.javaindex f6181dcebe..0102f3f6f4 100644--- a/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java+++ b/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java@@ -233,6 +233,22 @@ class SupabaseAuthenticationFilterMoreTest {request.setRequestURI("/api/v1/something");assertThat(filter.shouldNotFilter(request)).isFalse();}++ @Test+ @DisplayName("GET percent-encoded api path is filtered")+ void getEncodedApiPathFiltered() {+ request.setMethod("GET");+ request.setRequestURI("/%61pi/v1/info/load/all");+ assertThat(filter.shouldNotFilter(request)).isFalse();+ }++ @Test+ @DisplayName("GET percent-encoded actuator path is filtered")+ void getEncodedActuatorPathFiltered() {+ request.setMethod("GET");+ request.setRequestURI("/%61ctuator/prometheus");+ assertThat(filter.shouldNotFilter(request)).isFalse();+ }}@Nesteddiff --git a/build.gradle b/build.gradleindex b847e7e302..07b7566250 100644--- a/build.gradle+++ b/build.gradle@@ -122,7 +122,7 @@ springBoot {allprojects {group = 'stirling.software'- version = '3.2.1'+ version = '3.2.2'configurations.configureEach {exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"diff --git a/frontend/public/locales/ar-AR/translation.toml b/frontend/public/locales/ar-AR/translation.tomlindex 96469f8f33..979e9be97d 100644--- a/frontend/public/locales/ar-AR/translation.toml+++ b/frontend/public/locales/ar-AR/translation.toml@@ -370,6 +370,11 @@ pageVars = "معلومات الصفحة"position = "الموقع"positionAndFormatting = "الموضع والتنسيق"preview = "معاينة:"+qrCode = "رمز QR"+qrCodeSize = "حجم رمز QR"+qrContent = "محتوى رمز QR"+qrContentDescription = "نص أو رابط للترميز. المتغيرات الديناميكية مثل @filename و @page_number مدعومة."+qrContentTooLong = "طويل جدًا بحيث لا يتناسب مع رمز QR. قصّر المحتوى."quickPosition = "اختر موضعًا على الصفحة لوضع الختم."rotation = "دوران"selectedImageAlt = "صورة الختم المحددة"@@ -1993,6 +1998,7 @@ insertText = "إدراج نص"line = "خط"lineArrow = "سهم"moreActions = "المزيد من الإجراءات"+multiClickShapeHint = "انقر نقرًا مزدوجًا أو اضغط Enter للإنهاء"noBackground = "بدون خلفية"note = "ملاحظة"notesStamps = "ملاحظات وأختام"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "تمكين مرشح سيبيا"engineLoadError = "فشل تهيئة محرك عارض PDF"engineSlowWarning = "تستغرق تهيئة محرك PDF وقتًا أطول من المتوقع. يرجى التحقق من إعدادات WebAssembly وWorker في متصفحك، أو إعادة تحميل الصفحة."firstPage = "الصفحة الأولى"+fitPage = "ملاءمة للصفحة"+fitWidth = "ملاءمة للعرض"lastPage = "الصفحة الأخيرة"loadingEngine = "جارٍ تحميل محرك PDF..."moreOptions = "المزيد"diff --git a/frontend/public/locales/az-AZ/translation.toml b/frontend/public/locales/az-AZ/translation.tomlindex fd323f8bb2..c18ca4837d 100644--- a/frontend/public/locales/az-AZ/translation.toml+++ b/frontend/public/locales/az-AZ/translation.toml@@ -370,6 +370,11 @@ pageVars = "Səhifə məlumatı"position = "Yerləşmə"positionAndFormatting = "Mövqe və formatlama"preview = "Önizləmə:"+qrCode = "QR kod"+qrCodeSize = "QR kod ölçüsü"+qrContent = "QR kod məzmunu"+qrContentDescription = "Kodlaşdırılacaq mətn və ya keçid. @filename və @page_number kimi dinamik dəyişənlər dəstəklənir."+qrContentTooLong = "QR koda sığmayacaq qədər uzundur. Məzmunu qısaldın."quickPosition = "Möhürü yerləşdirmək üçün səhifədə bir mövqe seçin."rotation = "İstiqamət"selectedImageAlt = "Seçilmiş möhür şəkli"@@ -1993,6 +1998,7 @@ insertText = "Mətn əlavə et"line = "Xətt"lineArrow = "Ox"moreActions = "Daha çox əməliyyat"+multiClickShapeHint = "Bitirmək üçün iki dəfə klikləyin və ya Enter düyməsini basın"noBackground = "Arxa fon yoxdur"note = "Qeyd"notesStamps = "Qeydlər və möhürlər"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Sepiya filtrini aktiv et"engineLoadError = "PDF viewer mühərrikini başlatmaq alınmadı"engineSlowWarning = "PDF mühərrikinin başladılması gözləniləndən uzun çəkir. Brauzerinizin WebAssembly və Worker parametrlərini yoxlayın və ya səhifəni yenidən yükləyin."firstPage = "Birinci səhifə"+fitPage = "Səhifəyə sığdır"+fitWidth = "Enə sığdır"lastPage = "Son səhifə"loadingEngine = "PDF Engine yüklənir..."moreOptions = "Daha çox"diff --git a/frontend/public/locales/bg-BG/translation.toml b/frontend/public/locales/bg-BG/translation.tomlindex c2a3d2c8fa..2b650b3b20 100644--- a/frontend/public/locales/bg-BG/translation.toml+++ b/frontend/public/locales/bg-BG/translation.toml@@ -370,6 +370,11 @@ pageVars = "Информация за страницата"position = "Позиция"positionAndFormatting = "Позиция и форматиране"preview = "Преглед:"+qrCode = "QR код"+qrCodeSize = "Размер на QR кода"+qrContent = "Съдържание на QR кода"+qrContentDescription = "Текст или връзка за кодиране. Поддържат се динамични променливи като @filename и @page_number."+qrContentTooLong = "Твърде дълго, за да се побере в QR код. Съкратете съдържанието."quickPosition = "Изберете позиция на страницата, където да поставите печата."rotation = "Ротация"selectedImageAlt = "Избрано изображение за печат"@@ -1993,6 +1998,7 @@ insertText = "Вмъкване на текст"line = "Линия"lineArrow = "Стрелка"moreActions = "Още действия"+multiClickShapeHint = "Щракнете двукратно или натиснете Enter, за да завършите"noBackground = "Без фон"note = "Бележка"notesStamps = "Бележки и печати"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Включи сепия филтър"engineLoadError = "Неуспешно инициализиране на PDF viewer engine"engineSlowWarning = "Инициализирането на PDF engine отнема повече време от очакваното. Проверете настройките за WebAssembly и Worker на браузъра си или презаредете страницата."firstPage = "Първа страница"+fitPage = "Напасване към страницата"+fitWidth = "Напасване по ширина"lastPage = "Последна страница"loadingEngine = "Зареждане на PDF Engine..."moreOptions = "Още"diff --git a/frontend/public/locales/bo-CN/translation.toml b/frontend/public/locales/bo-CN/translation.tomlindex a8136e002d..4ad9cb84e4 100644--- a/frontend/public/locales/bo-CN/translation.toml+++ b/frontend/public/locales/bo-CN/translation.toml@@ -370,6 +370,11 @@ pageVars = "ཤོག་ངོས་ཆ་འཕྲིན།"position = "གནས"positionAndFormatting = "ལས་གནས་དང་རྩ་སྒྲིག།"preview = "སྔོན་ལྟ།:"+qrCode = "QR Code"+qrCodeSize = "QR Code ཆེ་ཆུང་ཚད"+qrContent = "QR Code ནང་དོན"+qrContentDescription = "ཨང་རྟགས་དུ་བསྒྱུར་བའི་ཡིག་ཚིག ཡང་ན་ འབྲེལ་མཐུད། @filename དང་ @page_number སོགས་ཀྱི་འགྱུར་གྲངས་རྒྱབ་སྐྱོར་ཡོད།"+qrContentTooLong = "QR Code ནང་ཚུད་མི་ཐུབ་པའི་ཚད་ལས་རིང་དྲགས་པས། ནང་དོན་བསྡུས་གནང་།"quickPosition = "ཤོག་ངོས་སྟེང་དུ་གནས་ཡུལ་ཞིག་འདེམས་ནས་མཚོན་རྟགས་འཇོག་དགོས།"rotation = "འཁོར་སྐྱོད།"selectedImageAlt = "བདམས་པའི་ཐམ་ག་པར་རིས།"@@ -1993,6 +1998,7 @@ insertText = "ཡིག་གེ་འཇུག"line = "ཐིག"lineArrow = "མདའ་རྟགས"moreActions = "བྱ་བ་མང་པོ"+multiClickShapeHint = "གཉིས་ལྟར་ཨེབ་ ཡང་ན་ Enter ལྡེ་མིག་མནན་ནས་མཇུག་བསྡུ།"noBackground = "རྒྱབ་ལྗོངས་མེད།"note = "དྲན་ཐོ"notesStamps = "དྲན་ཐོ་དང་བྱང་བུ།"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Sepia འཚག་བཟོ་ལྕོགས་འགུengineLoadError = "PDF viewer engine འགོ་སྒྲིག་བྱེད་མ་ཐུབ།"engineSlowWarning = "PDF engine འགོ་སྒྲིག་དུས་ཡུན་སྔོན་དཔག་ལས་རིང་བ་འགོར་བཞིན་འདུག ཁྱེད་ཀྱི browser WebAssembly དང Worker སྒྲིག་འགོད་ལ་ཞིབ་བཤེར་བྱོས། ཡང་ན་ཤོག་ངོས་བསྐྱར་འཇུག་བྱོས།"firstPage = "ཤོག་ངོས་དང་པོ།"+fitPage = "ཤོག་ངོས་ལ་འཚམས་སྒྲིག"+fitWidth = "ཞེང་ཚད་ལ་འཚམས་སྒྲིག"lastPage = "ཤོག་ངོས་མཐའ་མ།"loadingEngine = "PDF Engine འགེལ་བཞིན་པ..."moreOptions = "གདམ་གསེས་མང་བ"diff --git a/frontend/public/locales/ca-CA/translation.toml b/frontend/public/locales/ca-CA/translation.tomlindex f6e8d5a8b7..6de1a99c74 100644--- a/frontend/public/locales/ca-CA/translation.toml+++ b/frontend/public/locales/ca-CA/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informació de la pàgina"position = "Posició"positionAndFormatting = "Posició i format"preview = "Previsualització:"+qrCode = "Codi QR"+qrCodeSize = "Mida del codi QR"+qrContent = "Contingut del codi QR"+qrContentDescription = "Text o enllaç per codificar. S'admeten variables dinàmiques com @filename i @page_number."+qrContentTooLong = "Massa llarg per cabre en un codi QR. Escurça el contingut."quickPosition = "Seleccioneu una posició a la pàgina per col·locar el segell."rotation = "Rotació"selectedImageAlt = "Imatge de segell seleccionada"@@ -1993,6 +1998,7 @@ insertText = "Insereix text"line = "Línia"lineArrow = "Fletxa"moreActions = "Més accions"+multiClickShapeHint = "Fes doble clic o prem Intro per finalitzar"noBackground = "Sense fons"note = "Nota"notesStamps = "Notes i segells"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Activa el filtre sèpia"engineLoadError = "No s’ha pogut inicialitzar el motor del visor de PDF"engineSlowWarning = "La inicialització del motor PDF està trigant més del previst. Comprova la configuració de WebAssembly i Worker del navegador, o torna a carregar la pàgina."firstPage = "Primera pàgina"+fitPage = "Ajustar a la pàgina"+fitWidth = "Ajustar a l'amplada"lastPage = "Última pàgina"loadingEngine = "Carregant el motor PDF..."moreOptions = "Més"diff --git a/frontend/public/locales/cs-CZ/translation.toml b/frontend/public/locales/cs-CZ/translation.tomlindex 24781c751e..d11fe81af4 100644--- a/frontend/public/locales/cs-CZ/translation.toml+++ b/frontend/public/locales/cs-CZ/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informace o stránce"position = "Pozice"positionAndFormatting = "Umístění a formátování"preview = "Náhled:"+qrCode = "QR kód"+qrCodeSize = "Velikost QR kódu"+qrContent = "Obsah QR kódu"+qrContentDescription = "Text nebo odkaz k zakódování. Dynamické proměnné jako @filename a @page_number jsou podporovány."+qrContentTooLong = "Příliš dlouhé pro QR kód. Zkraťte obsah."quickPosition = "Vyberte na stránce pozici pro umístění razítka."rotation = "Otočení"selectedImageAlt = "Vybraný obrázek razítka"@@ -1993,6 +1998,7 @@ insertText = "Vložit text"line = "Čára"lineArrow = "Šipka"moreActions = "Další akce"+multiClickShapeHint = "Dvojitým kliknutím nebo stisknutím klávesy Enter dokončete"noBackground = "Bez pozadí"note = "Poznámka"notesStamps = "Poznámky a razítka"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Zapnout sépiový filtr"engineLoadError = "Nepodařilo se inicializovat engine prohlížeče PDF"engineSlowWarning = "Inicializace PDF enginu trvá déle, než se očekávalo. Zkontrolujte nastavení WebAssembly a Worker ve svém prohlížeči nebo znovu načtěte stránku."firstPage = "První stránka"+fitPage = "Přizpůsobit stránce"+fitWidth = "Přizpůsobit šířce"lastPage = "Poslední stránka"loadingEngine = "Načítání PDF enginu..."moreOptions = "Více"diff --git a/frontend/public/locales/da-DK/translation.toml b/frontend/public/locales/da-DK/translation.tomlindex d6083e460e..186cf24de9 100644--- a/frontend/public/locales/da-DK/translation.toml+++ b/frontend/public/locales/da-DK/translation.toml@@ -370,6 +370,11 @@ pageVars = "Sideoplysninger"position = "Plassering"positionAndFormatting = "Placering og formatering"preview = "Forhåndsvisning:"+qrCode = "QR-kode"+qrCodeSize = "Størrelse på QR-kode"+qrContent = "Indhold i QR-kode"+qrContentDescription = "Tekst eller link, der skal kodes. Dynamiske variabler såsom @filename og @page_number understøttes."+qrContentTooLong = "For lang til at passe i en QR-kode. Forkort indholdet."quickPosition = "Vælg en placering på siden til stemplet."rotation = "Vendelse"selectedImageAlt = "Valgt stempelbillede"@@ -1993,6 +1998,7 @@ insertText = "Indsæt tekst"line = "Linje"lineArrow = "Pil"moreActions = "Flere handlinger"+multiClickShapeHint = "Dobbeltklik eller tryk på Enter for at afslutte"noBackground = "Ingen baggrund"note = "Note"notesStamps = "Noter og stempler"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Aktiver sepiafilter"engineLoadError = "Kunne ikke initialisere PDF-visningsmotor"engineSlowWarning = "Initialisering af PDF-motoren tager længere tid end forventet. Kontrollér din browsers WebAssembly- og Worker-indstillinger, eller genindlæs siden."firstPage = "Første side"+fitPage = "Tilpas til side"+fitWidth = "Tilpas til bredde"lastPage = "Sidste side"loadingEngine = "Indlæser PDF Engine..."moreOptions = "Mere"diff --git a/frontend/public/locales/de-DE/translation.toml b/frontend/public/locales/de-DE/translation.tomlindex 4a61ebf598..e2639f33f6 100644--- a/frontend/public/locales/de-DE/translation.toml+++ b/frontend/public/locales/de-DE/translation.toml@@ -370,6 +370,11 @@ pageVars = "Seiten-Informationen"position = "Position"positionAndFormatting = "Position & Formatierung"preview = "Vorschau:"+qrCode = "QR-Code"+qrCodeSize = "QR-Code-Größe"+qrContent = "QR-Code-Inhalt"+qrContentDescription = "Zu codierender Text oder Link. Dynamische Variablen wie @filename und @page_number werden unterstützt."+qrContentTooLong = "Zu lang für einen QR-Code. Kürzen Sie den Inhalt."quickPosition = "Wählen Sie eine Position auf der Seite, um den Stempel zu platzieren."rotation = "Drehung"selectedImageAlt = "Ausgewähltes Stempelbild"@@ -1993,6 +1998,7 @@ insertText = "Text einfügen"line = "Linie"lineArrow = "Pfeil"moreActions = "Weitere Aktionen"+multiClickShapeHint = "Zum Beenden doppelt klicken oder Eingabetaste drücken"noBackground = "Kein Hintergrund"note = "Notiz"notesStamps = "Notizen & Stempel"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Sepia-Filter aktivieren"engineLoadError = "PDF-Viewer-Engine konnte nicht initialisiert werden"engineSlowWarning = "Die Initialisierung der PDF-Engine dauert länger als erwartet. Bitte prüfen Sie die WebAssembly- und Worker-Einstellungen Ihres Browsers oder laden Sie die Seite neu."firstPage = "Erste Seite"+fitPage = "An Seite anpassen"+fitWidth = "An Breite anpassen"lastPage = "Letzte Seite"loadingEngine = "PDF Engine wird geladen..."moreOptions = "Mehr"diff --git a/frontend/public/locales/el-GR/translation.toml b/frontend/public/locales/el-GR/translation.tomlindex 8f9c02bf9c..7fee87b645 100644--- a/frontend/public/locales/el-GR/translation.toml+++ b/frontend/public/locales/el-GR/translation.toml@@ -370,6 +370,11 @@ pageVars = "Πληροφορίες σελίδας"position = "Θέση"positionAndFormatting = "Θέση & μορφοποίηση"preview = "Προεπισκόπηση:"+qrCode = "Κωδικός QR"+qrCodeSize = "Μέγεθος κωδικού QR"+qrContent = "Περιεχόμενο κωδικού QR"+qrContentDescription = "Κείμενο ή σύνδεσμος προς κωδικοποίηση. Υποστηρίζονται δυναμικές μεταβλητές όπως @filename και @page_number."+qrContentTooLong = "Πολύ μεγάλο για να χωρέσει σε κωδικό QR. Συντομεύστε το περιεχόμενο."quickPosition = "Επιλέξτε μια θέση στη σελίδα για τοποθέτηση της σφραγίδας."rotation = "Περιστροφή"selectedImageAlt = "Επιλεγμένη εικόνα σφραγίδας"@@ -1993,6 +1998,7 @@ insertText = "Εισαγωγή κειμένου"line = "Γραμμή"lineArrow = "Βέλος"moreActions = "Περισσότερες ενέργειες"+multiClickShapeHint = "Κάντε διπλό κλικ ή πατήστε Enter για ολοκλήρωση"noBackground = "Χωρίς φόντο"note = "Σημείωση"notesStamps = "Σημειώσεις & Σφραγίδες"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Ενεργοποίηση φίλτρου σέπια"engineLoadError = "Αποτυχία αρχικοποίησης της μηχανής προβολής PDF"engineSlowWarning = "Η αρχικοποίηση της μηχανής PDF διαρκεί περισσότερο από το αναμενόμενο. Ελέγξτε τις ρυθμίσεις WebAssembly και Worker του προγράμματος περιήγησής σας ή επαναφορτώστε τη σελίδα."firstPage = "Πρώτη σελίδα"+fitPage = "Προσαρμογή στη σελίδα"+fitWidth = "Προσαρμογή στο πλάτος"lastPage = "Τελευταία σελίδα"loadingEngine = "Φόρτωση μηχανής PDF..."moreOptions = "Περισσότερα"diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 9faae849ce..dc98a78f2a 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -1240,15 +1240,9 @@ label = "Certificate Validity (days)"[admin.settings.folderAccess]description = "Directories that folder sources and folder outputs are allowed to read from and write to. This is a security boundary: automations can never be pointed at a server path outside this list."-securityNote = "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory is always off-limits."+securityNote = "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory, server file storage and the pipeline watched folders are always off-limits, and folder access is always disabled in hosted (SaaS) mode."title = "Folder Access"-[admin.settings.folderAccess.implied]-description = "These Stirling-managed directories are always permitted and can't be changed here."-serverStorage = "Server file storage"-title = "Always allowed"-watchedFolder = "Pipeline watched folder"-[admin.settings.folderAccess.roots]add = "Add"empty = "No folders allowed. Folder sources and outputs are currently disabled."diff --git a/frontend/public/locales/es-ES/translation.toml b/frontend/public/locales/es-ES/translation.tomlindex 3edad845f7..d843e13365 100644--- a/frontend/public/locales/es-ES/translation.toml+++ b/frontend/public/locales/es-ES/translation.toml@@ -370,6 +370,11 @@ pageVars = "Información de la página"position = "Posición"positionAndFormatting = "Posición y formato"preview = "Vista previa:"+qrCode = "Código QR"+qrCodeSize = "Tamaño del código QR"+qrContent = "Contenido del código QR"+qrContentDescription = "Texto o enlace a codificar. Se admiten variables dinámicas como @filename y @page_number."+qrContentTooLong = "Demasiado largo para caber en un código QR. Acorta el contenido."quickPosition = "Selecciona una posición en la página para colocar el sello."rotation = "Rotación"selectedImageAlt = "Imagen de sello seleccionada"@@ -1993,6 +1998,7 @@ insertText = "Insertar texto"line = "Línea"lineArrow = "Flecha"moreActions = "Más acciones"+multiClickShapeHint = "Haz doble clic o pulsa Intro para finalizar"noBackground = "Sin fondo"note = "Nota"notesStamps = "Notas y sellos"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Activar filtro sepia"engineLoadError = "No se pudo inicializar el motor del visor de PDF"engineSlowWarning = "La inicialización del motor PDF está tardando más de lo esperado. Comprueba la configuración de WebAssembly y Worker de tu navegador, o recarga la página."firstPage = "Primera Página"+fitPage = "Ajustar a la página"+fitWidth = "Ajustar al ancho"lastPage = "Última Página"loadingEngine = "Cargando motor PDF..."moreOptions = "Más"diff --git a/frontend/public/locales/eu-ES/translation.toml b/frontend/public/locales/eu-ES/translation.tomlindex 6baa38c9fe..87772cf5ee 100644--- a/frontend/public/locales/eu-ES/translation.toml+++ b/frontend/public/locales/eu-ES/translation.toml@@ -370,6 +370,11 @@ pageVars = "Orriaren informazioa"position = "Posizioa"positionAndFormatting = "Kokapena eta formatua"preview = "Aurrebista:"+qrCode = "QR kodea"+qrCodeSize = "QR kodearen tamaina"+qrContent = "QR kodearen edukia"+qrContentDescription = "Kodetzeko testua edo esteka. @filename eta @page_number bezalako aldagai dinamikoak onartzen dira."+qrContentTooLong = "Luzeegia QR kode batean sartzeko. Laburtu edukia."quickPosition = "Hautatu orrian zigiloa kokatzeko posizio bat."rotation = "Biraketa"selectedImageAlt = "Hautatutako zigilu-irudia"@@ -1993,6 +1998,7 @@ insertText = "Testua txertatu"line = "Marra"lineArrow = "Gezia"moreActions = "Ekintza gehiago"+multiClickShapeHint = "Egin klik bikoitza edo sakatu Enter amaitzeko"noBackground = "Atzeko planorik ez"note = "Oharra"notesStamps = "Oharrak eta zigiluak"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Gaitu sepia iragazkia"engineLoadError = "Ezin izan da PDF ikustailearen motorra hasieratu"engineSlowWarning = "PDF motorraren hasieratzeak espero baino gehiago irauten ari da. Egiaztatu zure nabigatzailearen WebAssembly eta Worker ezarpenak, edo kargatu berriro orria."firstPage = "Lehen orria"+fitPage = "Orrialdera egokitu"+fitWidth = "Zabalerara egokitu"lastPage = "Azken orria"loadingEngine = "PDF motorra kargatzen..."moreOptions = "Gehiago"diff --git a/frontend/public/locales/fa-IR/translation.toml b/frontend/public/locales/fa-IR/translation.tomlindex 70d5608959..c5d55cefe5 100644--- a/frontend/public/locales/fa-IR/translation.toml+++ b/frontend/public/locales/fa-IR/translation.toml@@ -370,6 +370,11 @@ pageVars = "اطلاعات صفحه"position = "موقعیت"positionAndFormatting = "موقعیت و قالببندی"preview = "پیشنمایش:"+qrCode = "کد QR"+qrCodeSize = "اندازه کد QR"+qrContent = "محتوای کد QR"+qrContentDescription = "متن یا پیوند برای کدگذاری. متغیرهای پویا مانند @filename و @page_number پشتیبانی میشوند."+qrContentTooLong = "برای قرارگیری در یک کد QR بیش از حد طولانی است. محتوا را کوتاه کنید."quickPosition = "یک موقعیت روی صفحه برای قرار دادن مهر انتخاب کنید."rotation = "چرخش"selectedImageAlt = "تصویر مهر انتخابشده"@@ -1993,6 +1998,7 @@ insertText = "درج متن"line = "خط"lineArrow = "پیکان"moreActions = "اقدامهای بیشتر"+multiClickShapeHint = "برای اتمام، دو بار کلیک کنید یا کلید Enter را فشار دهید"noBackground = "بدون پسزمینه"note = "یادداشت"notesStamps = "یادداشتها و مهرها"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "فعالسازی فیلتر سپیا"engineLoadError = "راهاندازی موتور نمایشگر PDF ناموفق بود"engineSlowWarning = "راهاندازی موتور PDF بیشتر از حد انتظار طول میکشد. لطفاً تنظیمات WebAssembly و Worker مرورگر خود را بررسی کنید، یا صفحه را دوباره بارگذاری کنید."firstPage = "صفحه نخست"+fitPage = "متناسب با صفحه"+fitWidth = "متناسب با عرض"lastPage = "صفحه آخر"loadingEngine = "در حال بارگذاری موتور PDF..."moreOptions = "بیشتر"diff --git a/frontend/public/locales/fr-FR/translation.toml b/frontend/public/locales/fr-FR/translation.tomlindex f7f32559c6..94e0b5f63e 100644--- a/frontend/public/locales/fr-FR/translation.toml+++ b/frontend/public/locales/fr-FR/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informations sur la page"position = "Position"positionAndFormatting = "Position et mise en forme"preview = "Aperçu :"+qrCode = "Code QR"+qrCodeSize = "Taille du code QR"+qrContent = "Contenu du code QR"+qrContentDescription = "Texte ou lien à encoder. Les variables dynamiques telles que @filename et @page_number sont prises en charge."+qrContentTooLong = "Trop long pour tenir dans un code QR. Raccourcissez le contenu."quickPosition = "Sélectionnez une position sur la page pour placer le tampon."rotation = "Rotation"selectedImageAlt = "Image du tampon sélectionnée"@@ -1993,6 +1998,7 @@ insertText = "Insérer du texte"line = "Ligne"lineArrow = "Flèche"moreActions = "Plus d’actions"+multiClickShapeHint = "Double-cliquez ou appuyez sur Entrée pour terminer"noBackground = "Sans arrière-plan"note = "Note"notesStamps = "Notes et tampons"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Activer le filtre sépia"engineLoadError = "Échec de l’initialisation du moteur de visualisation PDF"engineSlowWarning = "L’initialisation du moteur PDF prend plus de temps que prévu. Veuillez vérifier les paramètres WebAssembly et Worker de votre navigateur, ou recharger la page."firstPage = "Première page"+fitPage = "Ajuster à la page"+fitWidth = "Ajuster à la largeur"lastPage = "Dernière page"loadingEngine = "Chargement du moteur PDF..."moreOptions = "Plus"diff --git a/frontend/public/locales/ga-IE/translation.toml b/frontend/public/locales/ga-IE/translation.tomlindex 673ea6991a..8f23a6dcdf 100644--- a/frontend/public/locales/ga-IE/translation.toml+++ b/frontend/public/locales/ga-IE/translation.toml@@ -370,6 +370,11 @@ pageVars = "Eolas Leathanaigh"position = "Post"positionAndFormatting = "Suíomh & Formáidiú"preview = "Réamhamharc:"+qrCode = "Cód QR"+qrCodeSize = "Méid an Chóid QR"+qrContent = "Inneachar an Chóid QR"+qrContentDescription = "Téacs nó nasc le hionchódú. Tacaítear le hathróga dinimiciúla amhail @filename agus @page_number."+qrContentTooLong = "Ró-fhada chun luí i gCód QR. Giorraigh an t-inneachar."quickPosition = "Roghnaigh suíomh ar an leathanach le stampa a chur."rotation = "Rothlú"selectedImageAlt = "Íomhá stampa roghnaithe"@@ -1993,6 +1998,7 @@ insertText = "Ionsáigh Téacs"line = "Líne"lineArrow = "Saighead"moreActions = "Tuilleadh gníomhartha"+multiClickShapeHint = "Cliceáil faoi dhó nó brúigh Enter chun críochnú"noBackground = "Gan chúlra"note = "Nóta"notesStamps = "Nótaí & Stampaí"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Cumasaigh Scagaire Sepia"engineLoadError = "Theip ar inneall amharcóra PDF a thúsú"engineSlowWarning = "Tá túsú inneall PDF ag glacadh níos faide ná mar a bhíothas ag súil. Seiceáil socruithe WebAssembly agus Worker do bhrabhsálaí, nó athluchtaigh an leathanach."firstPage = "An Chéad Leathanach"+fitPage = "Oiriúnaigh don leathanach"+fitWidth = "Oiriúnaigh don leithead"lastPage = "An Leathanach Deireanach"loadingEngine = "Inneall PDF á luchtú..."moreOptions = "Tuilleadh"diff --git a/frontend/public/locales/gl-ES/translation.toml b/frontend/public/locales/gl-ES/translation.tomlindex 98ad0baf5d..f1e2d66bf9 100644--- a/frontend/public/locales/gl-ES/translation.toml+++ b/frontend/public/locales/gl-ES/translation.toml@@ -370,6 +370,11 @@ pageVars = "Información da páxina"position = "Posición"positionAndFormatting = "Posición e formato"preview = "Vista previa:"+qrCode = "Código QR"+qrCodeSize = "Tamaño do código QR"+qrContent = "Contido do código QR"+qrContentDescription = "Texto ou ligazón para codificar. Admítense variables dinámicas como @filename e @page_number."+qrContentTooLong = "Demasiado longo para caber nun código QR. Acorte o contido."quickPosition = "Selecciona unha posición na páxina para colocar o selo."rotation = "Rotación"selectedImageAlt = "Imaxe do selo seleccionada"@@ -1993,6 +1998,7 @@ insertText = "Inserir texto"line = "Liña"lineArrow = "Frecha"moreActions = "Máis accións"+multiClickShapeHint = "Faga dobre clic ou prema Intro para rematar"noBackground = "Sen fondo"note = "Nota"notesStamps = "Notas e selos"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Activar o filtro sepia"engineLoadError = "Non se puido inicializar o motor do visor de PDF"engineSlowWarning = "A inicialización do motor PDF está a levar máis tempo do esperado. Comproba a configuración de WebAssembly e Worker do navegador ou recarga a páxina."firstPage = "Primeira páxina"+fitPage = "Axustar á páxina"+fitWidth = "Axustar ao ancho"lastPage = "Última páxina"loadingEngine = "Cargando o motor PDF..."moreOptions = "Máis"diff --git a/frontend/public/locales/hi-IN/translation.toml b/frontend/public/locales/hi-IN/translation.tomlindex dc58289f1b..f027b747d2 100644--- a/frontend/public/locales/hi-IN/translation.toml+++ b/frontend/public/locales/hi-IN/translation.toml@@ -370,6 +370,11 @@ pageVars = "पृष्ठ जानकारी"position = "स्थिति"positionAndFormatting = "स्थिति और फ़ॉर्मैटिंग"preview = "पूर्वावलोकन:"+qrCode = "QR कोड"+qrCodeSize = "QR कोड का आकार"+qrContent = "QR कोड की सामग्री"+qrContentDescription = "एन्कोड करने के लिए टेक्स्ट या लिंक। @filename और @page_number जैसी डायनेमिक वेरिएबल्स समर्थित हैं।"+qrContentTooLong = "QR कोड में फिट होने के लिए बहुत लंबा है। सामग्री को छोटा करें।"quickPosition = "मुहर रखने के लिए पृष्ठ पर एक स्थान चुनें।"rotation = "घुमाव"selectedImageAlt = "चयनित स्टैम्प छवि"@@ -1993,6 +1998,7 @@ insertText = "पाठ डालें"line = "रेखा"lineArrow = "तीर"moreActions = "अधिक क्रियाएँ"+multiClickShapeHint = "समाप्त करने के लिए डबल-क्लिक करें या Enter दबाएँ"noBackground = "कोई पृष्ठभूमि नहीं"note = "नोट"notesStamps = "नोट्स और मुहरें"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "सेपिया फ़िल्टर सक्षमengineLoadError = "PDF viewer engine initialize करने में विफल"engineSlowWarning = "PDF engine initialization अपेक्षा से अधिक समय ले रहा है। कृपया अपने browser WebAssembly और Worker settings check करें, या page reload करें।"firstPage = "पहला पृष्ठ"+fitPage = "पृष्ठ पर फिट करें"+fitWidth = "चौड़ाई के अनुसार फिट करें"lastPage = "अंतिम पृष्ठ"loadingEngine = "PDF Engine load हो रहा है..."moreOptions = "अधिक"diff --git a/frontend/public/locales/hr-HR/translation.toml b/frontend/public/locales/hr-HR/translation.tomlindex aaf59dfc67..52ca1b10d2 100644--- a/frontend/public/locales/hr-HR/translation.toml+++ b/frontend/public/locales/hr-HR/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informacije o stranici"position = "Položaj"positionAndFormatting = "Položaj i oblikovanje"preview = "Pregled:"+qrCode = "QR kod"+qrCodeSize = "Veličina QR koda"+qrContent = "Sadržaj QR koda"+qrContentDescription = "Tekst ili poveznica za kodiranje. Podržane su dinamičke varijable kao što su @filename i @page_number."+qrContentTooLong = "Predugačko da stane u QR kod. Skratite sadržaj."quickPosition = "Odaberite položaj na stranici za postavljanje pečata."rotation = "Rotacija"selectedImageAlt = "Odabrana slika pečata"@@ -1993,6 +1998,7 @@ insertText = "Umetni tekst"line = "Linija"lineArrow = "Strelica"moreActions = "Više radnji"+multiClickShapeHint = "Dvaput kliknite ili pritisnite Enter za dovršetak"noBackground = "Bez pozadine"note = "Napomena"notesStamps = "Napomene i pečati"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Omogući sepija filtar"engineLoadError = "Inicijalizacija PDF preglednika nije uspjela"engineSlowWarning = "Inicijalizacija PDF enginea traje dulje od očekivanog. Provjerite postavke WebAssembly i Worker u pregledniku ili ponovno učitajte stranicu."firstPage = "Prva stranica"+fitPage = "Prilagodi stranici"+fitWidth = "Prilagodi širini"lastPage = "Zadnja stranica"loadingEngine = "Učitavanje PDF Engine..."moreOptions = "Više"diff --git a/frontend/public/locales/hu-HU/translation.toml b/frontend/public/locales/hu-HU/translation.tomlindex a16d64ce0a..00c8d369d0 100644--- a/frontend/public/locales/hu-HU/translation.toml+++ b/frontend/public/locales/hu-HU/translation.toml@@ -370,6 +370,11 @@ pageVars = "Oldalinformációk"position = "Pozíció"positionAndFormatting = "Pozíció és formázás"preview = "Előnézet:"+qrCode = "QR-kód"+qrCodeSize = "QR-kód mérete"+qrContent = "QR-kód tartalma"+qrContentDescription = "Kódolandó szöveg vagy hivatkozás. A dinamikus változók, például az @filename és az @page_number támogatottak."+qrContentTooLong = "Túl hosszú, nem fér el egy QR-kódban. Rövidítse a tartalmat."quickPosition = "Válasszon pozíciót az oldalon a bélyeg elhelyezéséhez."rotation = "Forgatás"selectedImageAlt = "Kiválasztott bélyegzőkép"@@ -1993,6 +1998,7 @@ insertText = "Szöveg beszúrása"line = "Vonal"lineArrow = "Nyíl"moreActions = "További műveletek"+multiClickShapeHint = "Befejezéshez kattintson duplán, vagy nyomja meg az Entert"noBackground = "Nincs háttér"note = "Jegyzet"notesStamps = "Jegyzetek és bélyegek"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Szépia szűrő engedélyezése"engineLoadError = "Nem sikerült inicializálni a PDF-megjelenítő motort"engineSlowWarning = "A PDF motor inicializálása a vártnál tovább tart. Ellenőrizze a böngésző WebAssembly- és Worker-beállításait, vagy töltse be újra az oldalt."firstPage = "Első oldal"+fitPage = "Oldalhoz igazítás"+fitWidth = "Szélességhez igazítás"lastPage = "Utolsó oldal"loadingEngine = "PDF Engine betöltése..."moreOptions = "Továbbiak"diff --git a/frontend/public/locales/id-ID/translation.toml b/frontend/public/locales/id-ID/translation.tomlindex 02b47abca6..83db70085d 100644--- a/frontend/public/locales/id-ID/translation.toml+++ b/frontend/public/locales/id-ID/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informasi Halaman"position = "Posisi"positionAndFormatting = "Posisi & Pemformatan"preview = "Pratinjau:"+qrCode = "Kode QR"+qrCodeSize = "Ukuran Kode QR"+qrContent = "Konten Kode QR"+qrContentDescription = "Teks atau tautan untuk dienkode. Variabel dinamis seperti @filename dan @page_number didukung."+qrContentTooLong = "Terlalu panjang untuk dimuat dalam Kode QR. Pendekkan kontennya."quickPosition = "Pilih posisi pada halaman untuk menempatkan stempel."rotation = "Rotasi"selectedImageAlt = "Gambar stempel yang dipilih"@@ -1993,6 +1998,7 @@ insertText = "Sisipkan Teks"line = "Garis"lineArrow = "Panah"moreActions = "Tindakan lainnya"+multiClickShapeHint = "Klik dua kali atau tekan Enter untuk menyelesaikan"noBackground = "Tanpa latar belakang"note = "Catatan"notesStamps = "Catatan & Stempel"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Aktifkan Filter Sepia"engineLoadError = "Gagal menginisialisasi mesin penampil PDF"engineSlowWarning = "Inisialisasi mesin PDF memakan waktu lebih lama dari yang diharapkan. Periksa pengaturan WebAssembly dan Worker browser Anda, atau muat ulang halaman."firstPage = "Halaman Pertama"+fitPage = "Sesuaikan ke halaman"+fitWidth = "Sesuaikan ke lebar"lastPage = "Halaman Terakhir"loadingEngine = "Memuat PDF Engine..."moreOptions = "Lainnya"diff --git a/frontend/public/locales/it-IT/translation.toml b/frontend/public/locales/it-IT/translation.tomlindex e50b5fda7e..7410e51dd3 100644--- a/frontend/public/locales/it-IT/translation.toml+++ b/frontend/public/locales/it-IT/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informazioni sulla pagina"position = "Posizione"positionAndFormatting = "Posizione e formattazione"preview = "Anteprima:"+qrCode = "Codice QR"+qrCodeSize = "Dimensione del codice QR"+qrContent = "Contenuto del codice QR"+qrContentDescription = "Testo o link da codificare. Sono supportate variabili dinamiche come @filename e @page_number."+qrContentTooLong = "Troppo lungo per essere inserito in un codice QR. Riduci il contenuto."quickPosition = "Seleziona una posizione sulla pagina in cui posizionare il timbro."rotation = "Rotazione"selectedImageAlt = "Immagine timbro selezionata"@@ -1993,6 +1998,7 @@ insertText = "Inserisci testo"line = "Linea"lineArrow = "Freccia"moreActions = "Altre azioni"+multiClickShapeHint = "Fai doppio clic o premi Invio per terminare"noBackground = "Nessuno sfondo"note = "Nota"notesStamps = "Note e timbri"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Abilita filtro seppia"engineLoadError = "Impossibile inizializzare il motore del visualizzatore PDF"engineSlowWarning = "L'inizializzazione del motore PDF sta richiedendo più tempo del previsto. Controlla le impostazioni WebAssembly e Worker del browser oppure ricarica la pagina."firstPage = "Prima pagina"+fitPage = "Adatta alla pagina"+fitWidth = "Adatta alla larghezza"lastPage = "Ultima pagina"loadingEngine = "Caricamento motore PDF..."moreOptions = "Altro"diff --git a/frontend/public/locales/ja-JP/translation.toml b/frontend/public/locales/ja-JP/translation.tomlindex 1d7359f504..fec1c0b5db 100644--- a/frontend/public/locales/ja-JP/translation.toml+++ b/frontend/public/locales/ja-JP/translation.toml@@ -370,6 +370,11 @@ pageVars = "ページ情報"position = "位置"positionAndFormatting = "位置と書式"preview = "プレビュー:"+qrCode = "QRコード"+qrCodeSize = "QRコードのサイズ"+qrContent = "QRコードの内容"+qrContentDescription = "エンコードするテキストまたはリンク。@filename や @page_number などの動的変数に対応しています。"+qrContentTooLong = "長すぎてQRコードに収まりません。内容を短くしてください。"quickPosition = "ページ上の配置位置を選択してください。"rotation = "回転"selectedImageAlt = "選択されたスタンプ画像"@@ -1993,6 +1998,7 @@ insertText = "テキストを挿入"line = "直線"lineArrow = "矢印"moreActions = "その他の操作"+multiClickShapeHint = "ダブルクリックするか Enter キーを押して完了"noBackground = "背景なし"note = "ノート"notesStamps = "ノートとスタンプ"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "セピアフィルターを有効化"engineLoadError = "PDF ビューアーエンジンの初期化に失敗しました"engineSlowWarning = "PDF エンジンの初期化に予想以上の時間がかかっています。ブラウザーの WebAssembly と Worker の設定を確認するか、ページを再読み込みしてください。"firstPage = "最初のページ"+fitPage = "ページに合わせる"+fitWidth = "幅に合わせる"lastPage = "最後のページ"loadingEngine = "PDF エンジンを読み込み中..."moreOptions = "その他"diff --git a/frontend/public/locales/ko-KR/translation.toml b/frontend/public/locales/ko-KR/translation.tomlindex af937f14c7..0a2da7f83c 100644--- a/frontend/public/locales/ko-KR/translation.toml+++ b/frontend/public/locales/ko-KR/translation.toml@@ -370,6 +370,11 @@ pageVars = "페이지 정보"position = "위치"positionAndFormatting = "위치 및 서식"preview = "미리보기:"+qrCode = "QR 코드"+qrCodeSize = "QR 코드 크기"+qrContent = "QR 코드 내용"+qrContentDescription = "인코딩할 텍스트 또는 링크. @filename 및 @page_number 같은 동적 변수를 지원합니다."+qrContentTooLong = "QR 코드에 맞지 않을 만큼 너무 깁니다. 내용을 줄여 주세요."quickPosition = "페이지에서 스탬프 위치를 선택하세요."rotation = "회전"selectedImageAlt = "선택한 스탬프 이미지"@@ -1993,6 +1998,7 @@ insertText = "텍스트 삽입"line = "선"lineArrow = "화살표"moreActions = "추가 작업"+multiClickShapeHint = "더블 클릭하거나 Enter를 눌러 완료하세요"noBackground = "배경 없음"note = "메모"notesStamps = "메모 및 스탬프"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "세피아 필터 활성화"engineLoadError = "PDF viewer engine을 초기화하지 못했습니다"engineSlowWarning = "PDF engine 초기화가 예상보다 오래 걸리고 있습니다. 브라우저 WebAssembly 및 Worker 설정을 확인하거나 페이지를 새로 고치세요."firstPage = "첫 페이지"+fitPage = "페이지에 맞춤"+fitWidth = "너비에 맞춤"lastPage = "마지막 페이지"loadingEngine = "PDF Engine 불러오는 중..."moreOptions = "더 보기"diff --git a/frontend/public/locales/ml-ML/translation.toml b/frontend/public/locales/ml-ML/translation.tomlindex d502e5061a..38a3f8d254 100644--- a/frontend/public/locales/ml-ML/translation.toml+++ b/frontend/public/locales/ml-ML/translation.toml@@ -370,6 +370,11 @@ pageVars = "പേജ് വിവരങ്ങൾ"position = "സ്ഥാനം"positionAndFormatting = "സ്ഥാനം & ഫോർമാറ്റിംഗ്"preview = "പ്രിവ്യൂ:"+qrCode = "QR കോഡ്"+qrCodeSize = "QR കോഡ് വലിപ്പം"+qrContent = "QR കോഡ് ഉള്ളടക്കം"+qrContentDescription = "എൻകോഡ് ചെയ്യാനുള്ള ടെക്സ്റ്റ് അല്ലെങ്കിൽ ലിങ്ക്. @filename, @page_number പോലുള്ള ഡൈനാമിക് വേരിയബിളുകൾ പിന്തുണയ്ക്കുന്നു."+qrContentTooLong = "QR കോഡിൽ ഒതുങ്ങാൻ വളരെ നീളമാണ്. ഉള്ളടക്കം ചുരുക്കുക."quickPosition = "സ്റ്റാമ്പ് വയ്ക്കാൻ പേജിലെ ഒരു സ്ഥാനം തിരഞ്ഞെടുക്കുക."rotation = "തിരിക്കൽ"selectedImageAlt = "തിരഞ്ഞെടുത്ത സ്റ്റാമ്പ് ചിത്രം"@@ -1993,6 +1998,7 @@ insertText = "ടെക്സ്റ്റ് ചേർക്കുക"line = "രേഖ"lineArrow = "അമ്പ്"moreActions = "കൂടുതൽ പ്രവർത്തനങ്ങൾ"+multiClickShapeHint = "പൂർത്തിയാക്കാൻ ഡബിൾ-ക്ലിക്ക് ചെയ്യുക അല്ലെങ്കിൽ Enter അമർത്തുക"noBackground = "ബാക്ക്ഗ്രൗണ്ട് ഇല്ല"note = "കുറിപ്പ്"notesStamps = "കുറിപ്പുകളും സ്റ്റാമ്പുകളും"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "സെപിയ ഫിൽട്ടർ പ്രവർത്engineLoadError = "PDF viewer engine initialize ചെയ്യുന്നതിൽ പരാജയപ്പെട്ടു"engineSlowWarning = "PDF engine initialization പ്രതീക്ഷിച്ചതിലും കൂടുതൽ സമയം എടുക്കുന്നു. നിങ്ങളുടെ browser WebAssembly, Worker settings പരിശോധിക്കുക, അല്ലെങ്കിൽ page reload ചെയ്യുക."firstPage = "ആദ്യ പേജ്"+fitPage = "പേജിൽ ഒതുക്കുക"+fitWidth = "വീതിയിൽ ഒതുക്കുക"lastPage = "അവസാന പേജ്"loadingEngine = "PDF Engine ലോഡ് ചെയ്യുന്നു..."moreOptions = "കൂടുതൽ"diff --git a/frontend/public/locales/nl-NL/translation.toml b/frontend/public/locales/nl-NL/translation.tomlindex 22ce178a90..14fc7c526b 100644--- a/frontend/public/locales/nl-NL/translation.toml+++ b/frontend/public/locales/nl-NL/translation.toml@@ -370,6 +370,11 @@ pageVars = "Pagina-informatie"position = "Positie"positionAndFormatting = "Positie & opmaak"preview = "Voorbeeld:"+qrCode = "QR-code"+qrCodeSize = "Grootte van QR-code"+qrContent = "Inhoud van QR-code"+qrContentDescription = "Tekst of link om te coderen. Dynamische variabelen zoals @filename en @page_number worden ondersteund."+qrContentTooLong = "Te lang voor een QR-code. Verkort de inhoud."quickPosition = "Selecteer een positie op de pagina om de stempel te plaatsen."rotation = "Rotatie"selectedImageAlt = "Geselecteerde stempelafbeelding"@@ -1993,6 +1998,7 @@ insertText = "Tekst invoegen"line = "Lijn"lineArrow = "Pijl"moreActions = "Meer acties"+multiClickShapeHint = "Dubbelklik of druk op Enter om te voltooien"noBackground = "Geen achtergrond"note = "Notitie"notesStamps = "Notities & Stempels"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Sepiafilter inschakelen"engineLoadError = "Kan PDF-viewerengine niet initialiseren"engineSlowWarning = "Het initialiseren van de PDF-engine duurt langer dan verwacht. Controleer de WebAssembly- en Worker-instellingen van je browser of laad de pagina opnieuw."firstPage = "Eerste pagina"+fitPage = "Aan pagina aanpassen"+fitWidth = "Aan breedte aanpassen"lastPage = "Laatste pagina"loadingEngine = "PDF Engine laden..."moreOptions = "Meer"diff --git a/frontend/public/locales/no-NB/translation.toml b/frontend/public/locales/no-NB/translation.tomlindex c12c541651..2ff8f3edd7 100644--- a/frontend/public/locales/no-NB/translation.toml+++ b/frontend/public/locales/no-NB/translation.toml@@ -370,6 +370,11 @@ pageVars = "Sideinformasjon"position = "Posisjon"positionAndFormatting = "Plassering og formatering"preview = "Forhåndsvisning:"+qrCode = "QR-kode"+qrCodeSize = "Størrelse på QR-kode"+qrContent = "Innhold i QR-kode"+qrContentDescription = "Tekst eller lenke som skal kodes. Dynamiske variabler som @filename og @page_number støttes."+qrContentTooLong = "For langt til å få plass i en QR-kode. Kort ned innholdet."quickPosition = "Velg en posisjon på siden for å plassere stempelet."rotation = "Rotasjon"selectedImageAlt = "Valgt stempelbilde"@@ -1993,6 +1998,7 @@ insertText = "Sett inn tekst"line = "Linje"lineArrow = "Pil"moreActions = "Flere handlinger"+multiClickShapeHint = "Dobbeltklikk eller trykk Enter for å fullføre"noBackground = "Ingen bakgrunn"note = "Notat"notesStamps = "Notater og stempler"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Aktiver sepiafilter"engineLoadError = "Kunne ikke initialisere PDF-visningsmotoren"engineSlowWarning = "Initialisering av PDF-motoren tar lengre tid enn forventet. Kontroller innstillingene for WebAssembly og Worker i nettleseren, eller last inn siden på nytt."firstPage = "Første side"+fitPage = "Tilpass til side"+fitWidth = "Tilpass til bredde"lastPage = "Siste side"loadingEngine = "Laster PDF-motor ..."moreOptions = "Mer"diff --git a/frontend/public/locales/pl-PL/translation.toml b/frontend/public/locales/pl-PL/translation.tomlindex 7718ec2cf1..ee9156f806 100644--- a/frontend/public/locales/pl-PL/translation.toml+++ b/frontend/public/locales/pl-PL/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informacje o stronie"position = "Pozycja"positionAndFormatting = "Pozycja i formatowanie"preview = "Podgląd:"+qrCode = "Kod QR"+qrCodeSize = "Rozmiar kodu QR"+qrContent = "Zawartość kodu QR"+qrContentDescription = "Tekst lub link do zakodowania. Obsługiwane są zmienne dynamiczne, takie jak @filename i @page_number."+qrContentTooLong = "Zbyt długie, aby zmieściło się w kodzie QR. Skróć zawartość."quickPosition = "Wybierz pozycję na stronie, aby umieścić stempel."rotation = "Obrót"selectedImageAlt = "Wybrany obraz stempla"@@ -1993,6 +1998,7 @@ insertText = "Wstaw tekst"line = "Linia"lineArrow = "Strzałka"moreActions = "Więcej akcji"+multiClickShapeHint = "Kliknij dwukrotnie lub naciśnij Enter, aby zakończyć"noBackground = "Brak tła"note = "Notatka"notesStamps = "Notatki i stemple"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Włącz filtr sepii"engineLoadError = "Nie udało się zainicjować silnika przeglądarki PDF"engineSlowWarning = "Inicjalizacja silnika PDF trwa dłużej niż oczekiwano. Sprawdź ustawienia WebAssembly i Worker w przeglądarce albo odśwież stronę."firstPage = "Pierwsza strona"+fitPage = "Dopasuj do strony"+fitWidth = "Dopasuj do szerokości"lastPage = "Ostatnia strona"loadingEngine = "Wczytywanie silnika PDF..."moreOptions = "Więcej"diff --git a/frontend/public/locales/pt-BR/translation.toml b/frontend/public/locales/pt-BR/translation.tomlindex f0fc43f8c3..1e88c92c9b 100644--- a/frontend/public/locales/pt-BR/translation.toml+++ b/frontend/public/locales/pt-BR/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informações da página"position = "Posição:"positionAndFormatting = "Posição e formatação"preview = "Prévia:"+qrCode = "QR Code"+qrCodeSize = "Tamanho do QR Code"+qrContent = "Conteúdo do QR Code"+qrContentDescription = "Texto ou link para codificar. Variáveis dinâmicas como @filename e @page_number são suportadas."+qrContentTooLong = "Muito longo para caber em um QR Code. Encurte o conteúdo."quickPosition = "Selecione uma posição na página para colocar o carimbo."rotation = "Rotação:"selectedImageAlt = "Imagem de carimbo selecionada"@@ -1993,6 +1998,7 @@ insertText = "Inserir texto"line = "Linha"lineArrow = "Seta"moreActions = "Mais ações"+multiClickShapeHint = "Clique duas vezes ou pressione Enter para finalizar"noBackground = "Sem fundo"note = "Nota"notesStamps = "Notas e carimbos"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Ativar filtro sépia"engineLoadError = "Falha ao inicializar o mecanismo do visualizador de PDF"engineSlowWarning = "A inicialização do mecanismo de PDF está demorando mais do que o esperado. Verifique as configurações de WebAssembly e Worker do seu navegador ou recarregue a página."firstPage = "Primeira página"+fitPage = "Ajustar à página"+fitWidth = "Ajustar à largura"lastPage = "Última página"loadingEngine = "Carregando mecanismo de PDF..."moreOptions = "Mais"diff --git a/frontend/public/locales/pt-PT/translation.toml b/frontend/public/locales/pt-PT/translation.tomlindex a0ee4bdd45..0133627af2 100644--- a/frontend/public/locales/pt-PT/translation.toml+++ b/frontend/public/locales/pt-PT/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informações da página"position = "Posição"positionAndFormatting = "Posição e formatação"preview = "Pré-visualização:"+qrCode = "Código QR"+qrCodeSize = "Tamanho do Código QR"+qrContent = "Conteúdo do Código QR"+qrContentDescription = "Texto ou ligação a codificar. Variáveis dinâmicas como @filename e @page_number são suportadas."+qrContentTooLong = "Demasiado longo para caber num código QR. Reduza o conteúdo."quickPosition = "Selecione uma posição na página para colocar o carimbo."rotation = "Rotação"selectedImageAlt = "Imagem de carimbo selecionada"@@ -1993,6 +1998,7 @@ insertText = "Inserir texto"line = "Linha"lineArrow = "Seta"moreActions = "Mais ações"+multiClickShapeHint = "Faça duplo clique ou prima Enter para terminar"noBackground = "Sem fundo"note = "Nota"notesStamps = "Notas e carimbos"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Ativar filtro sépia"engineLoadError = "Falha ao inicializar o motor do visualizador de PDF"engineSlowWarning = "A inicialização do motor PDF está a demorar mais do que o esperado. Verifique as definições de WebAssembly e Worker do seu navegador ou recarregue a página."firstPage = "Primeira página"+fitPage = "Ajustar à página"+fitWidth = "Ajustar à largura"lastPage = "Última página"loadingEngine = "A carregar o motor PDF..."moreOptions = "Mais"diff --git a/frontend/public/locales/ro-RO/translation.toml b/frontend/public/locales/ro-RO/translation.tomlindex 040173d2f8..37319c892c 100644--- a/frontend/public/locales/ro-RO/translation.toml+++ b/frontend/public/locales/ro-RO/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informații pagină"position = "Poziție"positionAndFormatting = "Poziție și formatare"preview = "Previzualizare:"+qrCode = "Cod QR"+qrCodeSize = "Dimensiune cod QR"+qrContent = "Conținut cod QR"+qrContentDescription = "Text sau link de codificat. Variabile dinamice precum @filename și @page_number sunt acceptate."+qrContentTooLong = "Prea lung pentru a încăpea într-un cod QR. Scurtați conținutul."quickPosition = "Selectați o poziție pe pagină pentru a plasa ștampila."rotation = "Rotație"selectedImageAlt = "Imaginea ștampilei selectate"@@ -1993,6 +1998,7 @@ insertText = "Inserare text"line = "Linie"lineArrow = "Săgeată"moreActions = "Mai multe acțiuni"+multiClickShapeHint = "Faceți dublu clic sau apăsați Enter pentru a finaliza"noBackground = "Fără fundal"note = "Notă"notesStamps = "Note și ștampile"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Activați filtrul sepia"engineLoadError = "Inițializarea motorului de vizualizare PDF a eșuat"engineSlowWarning = "Inițializarea motorului PDF durează mai mult decât se aștepta. Verificați setările WebAssembly și Worker ale browserului sau reîncărcați pagina."firstPage = "Prima pagină"+fitPage = "Încadrare la pagină"+fitWidth = "Încadrare la lățime"lastPage = "Ultima pagină"loadingEngine = "Se încarcă motorul PDF..."moreOptions = "Mai multe"diff --git a/frontend/public/locales/ru-RU/translation.toml b/frontend/public/locales/ru-RU/translation.tomlindex 6806457a6e..be69b4fb0b 100644--- a/frontend/public/locales/ru-RU/translation.toml+++ b/frontend/public/locales/ru-RU/translation.toml@@ -370,6 +370,11 @@ pageVars = "Информация о странице"position = "Позиция"positionAndFormatting = "Положение и форматирование"preview = "Предпросмотр:"+qrCode = "QR-код"+qrCodeSize = "Размер QR-кода"+qrContent = "Содержимое QR-кода"+qrContentDescription = "Текст или ссылка для кодирования. Поддерживаются динамические переменные, такие как @filename и @page_number."+qrContentTooLong = "Слишком длинное, чтобы поместиться в QR-код. Сократите содержимое."quickPosition = "Выберите положение на странице для размещения штампа."rotation = "Поворот"selectedImageAlt = "Выбранное изображение штампа"@@ -1993,6 +1998,7 @@ insertText = "Вставить текст"line = "Линия"lineArrow = "Стрелка"moreActions = "Дополнительные действия"+multiClickShapeHint = "Дважды щелкните или нажмите Enter, чтобы завершить"noBackground = "Без фона"note = "Заметка"notesStamps = "Заметки и штампы"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Включить фильтр сепия"engineLoadError = "Не удалось инициализировать движок просмотра PDF"engineSlowWarning = "Инициализация движка PDF занимает больше времени, чем ожидалось. Проверьте настройки WebAssembly и Worker в браузере или перезагрузите страницу."firstPage = "Первая страница"+fitPage = "По размеру страницы"+fitWidth = "По ширине"lastPage = "Последняя страница"loadingEngine = "Загрузка PDF Engine..."moreOptions = "Ещё"diff --git a/frontend/public/locales/sk-SK/translation.toml b/frontend/public/locales/sk-SK/translation.tomlindex e80889c515..4eed1dbd35 100644--- a/frontend/public/locales/sk-SK/translation.toml+++ b/frontend/public/locales/sk-SK/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informácie o strane"position = "Poloha"positionAndFormatting = "Poloha a formátovanie"preview = "Náhľad:"+qrCode = "QR kód"+qrCodeSize = "Veľkosť QR kódu"+qrContent = "Obsah QR kódu"+qrContentDescription = "Text alebo odkaz na zakódovanie. Podporované sú dynamické premenné ako @filename a @page_number."+qrContentTooLong = "Príliš dlhé, aby sa zmestilo do QR kódu. Skráťte obsah."quickPosition = "Vyberte polohu na stránke pre umiestnenie pečiatky."rotation = "Rotácia"selectedImageAlt = "Vybraný obrázok pečiatky"@@ -1993,6 +1998,7 @@ insertText = "Vložiť text"line = "Čiara"lineArrow = "Šípka"moreActions = "Ďalšie akcie"+multiClickShapeHint = "Dvakrát kliknite alebo stlačte Enter na dokončenie"noBackground = "Bez pozadia"note = "Poznámka"notesStamps = "Poznámky a pečiatky"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Povoliť sépiový filter"engineLoadError = "Nepodarilo sa inicializovať engine prehliadača PDF"engineSlowWarning = "Inicializácia enginu PDF trvá dlhšie, než sa očakávalo. Skontrolujte nastavenia WebAssembly a Worker vo svojom prehliadači alebo stránku znova načítajte."firstPage = "Prvá strana"+fitPage = "Prispôsobiť stránke"+fitWidth = "Prispôsobiť šírke"lastPage = "Posledná strana"loadingEngine = "Načítava sa PDF Engine..."moreOptions = "Viac"diff --git a/frontend/public/locales/sl-SI/translation.toml b/frontend/public/locales/sl-SI/translation.tomlindex 1faac7e00c..aa2c1a7763 100644--- a/frontend/public/locales/sl-SI/translation.toml+++ b/frontend/public/locales/sl-SI/translation.toml@@ -370,6 +370,11 @@ pageVars = "Podatki o strani"position = "Položaj"positionAndFormatting = "Položaj in oblikovanje"preview = "Predogled:"+qrCode = "QR koda"+qrCodeSize = "Velikost QR kode"+qrContent = "Vsebina QR kode"+qrContentDescription = "Besedilo ali povezava za kodiranje. Podprte so dinamične spremenljivke, kot sta @filename in @page_number."+qrContentTooLong = "Predolgo, da bi se prilegalo v QR kodo. Skrajšajte vsebino."quickPosition = "Izberite položaj na strani za postavitev žiga."rotation = "Rotacija"selectedImageAlt = "Izbrana slika žiga"@@ -1993,6 +1998,7 @@ insertText = "Vstavi besedilo"line = "Črta"lineArrow = "Puščica"moreActions = "Več dejanj"+multiClickShapeHint = "Za dokončanje dvokliknite ali pritisnite Enter"noBackground = "Brez ozadja"note = "Opomba"notesStamps = "Opombe in žigi"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Omogoči sepia filter"engineLoadError = "Inicializacija mehanizma pregledovalnika PDF ni uspela"engineSlowWarning = "Inicializacija mehanizma PDF traja dlje od pričakovanega. Preverite nastavitve WebAssembly in Worker v brskalniku ali znova naložite stran."firstPage = "Prva stran"+fitPage = "Prilagodi na stran"+fitWidth = "Prilagodi širini"lastPage = "Zadnja stran"loadingEngine = "Nalaganje mehanizma PDF ..."moreOptions = "Več"diff --git a/frontend/public/locales/sr-Latn-RS/translation.toml b/frontend/public/locales/sr-Latn-RS/translation.tomlindex a17c91a50c..8e03dc71c1 100644--- a/frontend/public/locales/sr-Latn-RS/translation.toml+++ b/frontend/public/locales/sr-Latn-RS/translation.toml@@ -370,6 +370,11 @@ pageVars = "Informacije o stranici"position = "Pozicija:"positionAndFormatting = "Pozicija i formatiranje"preview = "Pregled:"+qrCode = "QR kod"+qrCodeSize = "Veličina QR koda"+qrContent = "Sadržaj QR koda"+qrContentDescription = "Tekst ili link za kodiranje. Dinamičke promenljive kao što su @filename i @page_number su podržane."+qrContentTooLong = "Predugo da stane u QR kod. Skratite sadržaj."quickPosition = "Izaberite poziciju na stranici za postavljanje pečata."rotation = "Rotacija:"selectedImageAlt = "Izabrana slika pečata"@@ -1993,6 +1998,7 @@ insertText = "Umetni tekst"line = "Linija"lineArrow = "Strelica"moreActions = "Više radnji"+multiClickShapeHint = "Dvaput kliknite ili pritisnite Enter da završite"noBackground = "Bez pozadine"note = "Beleška"notesStamps = "Beleške i pečati"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Omogući sepija filter"engineLoadError = "Nije uspelo inicijalizovanje PDF viewer engine-a"engineSlowWarning = "Inicijalizacija PDF engine-a traje duže nego što je očekivano. Proverite WebAssembly i Worker podešavanja pregledača ili ponovo učitajte stranicu."firstPage = "Prva stranica"+fitPage = "Prilagodi stranici"+fitWidth = "Prilagodi širini"lastPage = "Poslednja stranica"loadingEngine = "Učitavanje PDF Engine-a..."moreOptions = "Više"diff --git a/frontend/public/locales/sv-SE/translation.toml b/frontend/public/locales/sv-SE/translation.tomlindex 74b974565b..730d18c10e 100644--- a/frontend/public/locales/sv-SE/translation.toml+++ b/frontend/public/locales/sv-SE/translation.toml@@ -370,6 +370,11 @@ pageVars = "Sidinformation"position = "Position"positionAndFormatting = "Position och formatering"preview = "Förhandsgranskning:"+qrCode = "QR-kod"+qrCodeSize = "QR-kodens storlek"+qrContent = "QR-kodens innehåll"+qrContentDescription = "Text eller länk att koda. Dynamiska variabler såsom @filename och @page_number stöds."+qrContentTooLong = "För långt för att få plats i en QR-kod. Förkorta innehållet."quickPosition = "Välj en position på sidan för att placera stämpeln."rotation = "Rotering"selectedImageAlt = "Vald stämpelbild"@@ -1993,6 +1998,7 @@ insertText = "Infoga text"line = "Linje"lineArrow = "Pil"moreActions = "Fler åtgärder"+multiClickShapeHint = "Dubbelklicka eller tryck på Enter för att avsluta"noBackground = "Ingen bakgrund"note = "Anteckning"notesStamps = "Anteckningar och stämplar"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Aktivera sepiafilter"engineLoadError = "Det gick inte att initiera PDF-visningsmotorn"engineSlowWarning = "Initieringen av PDF-motorn tar längre tid än förväntat. Kontrollera webbläsarens WebAssembly- och Worker-inställningar, eller ladda om sidan."firstPage = "Första sidan"+fitPage = "Anpassa till sidan"+fitWidth = "Anpassa till bredden"lastPage = "Sista sidan"loadingEngine = "Läser in PDF-motor..."moreOptions = "Mer"diff --git a/frontend/public/locales/th-TH/translation.toml b/frontend/public/locales/th-TH/translation.tomlindex 490ae5ac17..1b50d63f49 100644--- a/frontend/public/locales/th-TH/translation.toml+++ b/frontend/public/locales/th-TH/translation.toml@@ -370,6 +370,11 @@ pageVars = "ข้อมูลหน้า"position = "ตำแหน่ง"positionAndFormatting = "ตำแหน่งและการจัดรูปแบบ"preview = "ตัวอย่าง:"+qrCode = "QR Code"+qrCodeSize = "ขนาด QR Code"+qrContent = "เนื้อหา QR Code"+qrContentDescription = "ข้อความหรือลิงก์ที่จะเข้ารหัส รองรับตัวแปรแบบไดนามิก เช่น @filename และ @page_number"+qrContentTooLong = "ยาวเกินไปสำหรับ QR Code โปรดย่อเนื้อหา"quickPosition = "เลือกตำแหน่งบนหน้าสำหรับวางตราประทับ"rotation = "การหมุน"selectedImageAlt = "รูปภาพตราประทับที่เลือก"@@ -1993,6 +1998,7 @@ insertText = "แทรกข้อความ"line = "เส้น"lineArrow = "ลูกศร"moreActions = "การดำเนินการเพิ่มเติม"+multiClickShapeHint = "ดับเบิลคลิกหรือกด Enter เพื่อเสร็จสิ้น"noBackground = "ไม่มีพื้นหลัง"note = "โน้ต"notesStamps = "โน้ตและตราประทับ"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "เปิดใช้งานตัวกรองเซengineLoadError = "ไม่สามารถเริ่มต้นเอนจินตัวดู PDF ได้"engineSlowWarning = "การเริ่มต้นเอนจิน PDF ใช้เวลานานกว่าที่คาดไว้ โปรดตรวจสอบการตั้งค่า WebAssembly และ Worker ของเบราว์เซอร์ของคุณ หรือโหลดหน้าใหม่"firstPage = "หน้าแรก"+fitPage = "พอดีกับหน้า"+fitWidth = "พอดีกับความกว้าง"lastPage = "หน้าสุดท้าย"loadingEngine = "กำลังโหลด PDF Engine..."moreOptions = "เพิ่มเติม"diff --git a/frontend/public/locales/tr-TR/translation.toml b/frontend/public/locales/tr-TR/translation.tomlindex 3199c6e303..423897011e 100644--- a/frontend/public/locales/tr-TR/translation.toml+++ b/frontend/public/locales/tr-TR/translation.toml@@ -370,6 +370,11 @@ pageVars = "Sayfa Bilgileri"position = "Konum"positionAndFormatting = "Konum ve Biçimlendirme"preview = "Önizleme:"+qrCode = "QR Kod"+qrCodeSize = "QR Kod Boyutu"+qrContent = "QR Kod İçeriği"+qrContentDescription = "Kodlanacak metin veya bağlantı. @filename ve @page_number gibi dinamik değişkenler desteklenir."+qrContentTooLong = "QR koda sığmayacak kadar uzun. İçeriği kısaltın."quickPosition = "Damgayı yerleştirmek için sayfada bir konum seçin."rotation = "Döndürme"selectedImageAlt = "Seçilen damga görseli"@@ -1993,6 +1998,7 @@ insertText = "Metin Ekle"line = "Çizgi"lineArrow = "Ok"moreActions = "Diğer işlemler"+multiClickShapeHint = "Bitirmek için çift tıklayın veya Enter tuşuna basın"noBackground = "Arka plan yok"note = "Not"notesStamps = "Notlar ve Damgalar"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Sepya Filtresini Etkinleştir"engineLoadError = "PDF görüntüleyici motoru başlatılamadı"engineSlowWarning = "PDF motorunun başlatılması beklenenden uzun sürüyor. Lütfen tarayıcınızın WebAssembly ve Worker ayarlarını kontrol edin veya sayfayı yeniden yükleyin."firstPage = "İlk Sayfa"+fitPage = "Sayfaya sığdır"+fitWidth = "Genişliğe sığdır"lastPage = "Son Sayfa"loadingEngine = "PDF Engine yükleniyor..."moreOptions = "Daha fazla"diff --git a/frontend/public/locales/uk-UA/translation.toml b/frontend/public/locales/uk-UA/translation.tomlindex ea7274193c..423fce9ba6 100644--- a/frontend/public/locales/uk-UA/translation.toml+++ b/frontend/public/locales/uk-UA/translation.toml@@ -370,6 +370,11 @@ pageVars = "Інформація про сторінку"position = "Позиція"positionAndFormatting = "Позиція та форматування"preview = "Попередній перегляд:"+qrCode = "QR-код"+qrCodeSize = "Розмір QR-коду"+qrContent = "Вміст QR-коду"+qrContentDescription = "Текст або посилання для кодування. Підтримуються динамічні змінні, такі як @filename та @page_number."+qrContentTooLong = "Занадто довге, щоб уміститися в QR-код. Скоротіть вміст."quickPosition = "Виберіть позицію на сторінці для розміщення штампа."rotation = "Обертання"selectedImageAlt = "Вибране зображення штампа"@@ -1993,6 +1998,7 @@ insertText = "Вставити текст"line = "Лінія"lineArrow = "Стрілка"moreActions = "Додаткові дії"+multiClickShapeHint = "Двічі клацніть або натисніть Enter, щоб завершити"noBackground = "Без фону"note = "Нотатка"notesStamps = "Нотатки та штампи"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Увімкнути фільтр сепії"engineLoadError = "Не вдалося ініціалізувати рушій переглядача PDF"engineSlowWarning = "Ініціалізація рушія PDF триває довше, ніж очікувалося. Перевірте налаштування WebAssembly і Worker у вашому браузері або перезавантажте сторінку."firstPage = "Перша сторінка"+fitPage = "Підігнати до сторінки"+fitWidth = "Підігнати за шириною"lastPage = "Остання сторінка"loadingEngine = "Завантаження рушія PDF..."moreOptions = "Більше"diff --git a/frontend/public/locales/vi-VN/translation.toml b/frontend/public/locales/vi-VN/translation.tomlindex d100d077c9..75f96df623 100644--- a/frontend/public/locales/vi-VN/translation.toml+++ b/frontend/public/locales/vi-VN/translation.toml@@ -370,6 +370,11 @@ pageVars = "Thông tin trang"position = "Vị trí"positionAndFormatting = "Vị trí & định dạng"preview = "Xem trước:"+qrCode = "Mã QR"+qrCodeSize = "Kích thước mã QR"+qrContent = "Nội dung mã QR"+qrContentDescription = "Văn bản hoặc liên kết để mã hóa. Hỗ trợ các biến động như @filename và @page_number."+qrContentTooLong = "Quá dài để vừa trong mã QR. Hãy rút ngắn nội dung."quickPosition = "Chọn một vị trí trên trang để đặt con dấu."rotation = "Xoay"selectedImageAlt = "Hình ảnh con dấu đã chọn"@@ -1993,6 +1998,7 @@ insertText = "Chèn văn bản"line = "Đường thẳng"lineArrow = "Mũi tên"moreActions = "Thao tác khác"+multiClickShapeHint = "Nhấp đúp hoặc nhấn Enter để hoàn tất"noBackground = "Không nền"note = "Ghi chú"notesStamps = "Ghi chú & Dấu"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "Bật bộ lọc sepia"engineLoadError = "Không thể khởi tạo công cụ xem PDF"engineSlowWarning = "Việc khởi tạo công cụ PDF đang mất nhiều thời gian hơn dự kiến. Vui lòng kiểm tra cài đặt WebAssembly và Worker của trình duyệt, hoặc tải lại trang."firstPage = "Trang đầu"+fitPage = "Vừa với trang"+fitWidth = "Vừa theo chiều rộng"lastPage = "Trang cuối"loadingEngine = "Đang tải PDF Engine..."moreOptions = "Thêm"diff --git a/frontend/public/locales/zh-BO/translation.toml b/frontend/public/locales/zh-BO/translation.tomlindex 3e3fc2784c..79bded2f73 100644--- a/frontend/public/locales/zh-BO/translation.toml+++ b/frontend/public/locales/zh-BO/translation.toml@@ -370,6 +370,11 @@ pageVars = "页面信息"position = "གནས་ས།"positionAndFormatting = "位置与格式"preview = "预览:"+qrCode = "二维码"+qrCodeSize = "二维码大小"+qrContent = "二维码内容"+qrContentDescription = "要编码的文本或链接。支持 @filename 和 @page_number 等动态变量。"+qrContentTooLong = "内容过长,无法适配二维码。请缩短内容。"quickPosition = "选择页面上的位置以放置印章。"rotation = "འཁོར་སྐྱོད།"selectedImageAlt = "已选印章图像"@@ -1993,6 +1998,7 @@ insertText = "插入文本"line = "直线"lineArrow = "箭头"moreActions = "更多操作"+multiClickShapeHint = "双击或按 Enter 完成"noBackground = "无背景"note = "便签"notesStamps = "便签与图章"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "启用棕褐色滤镜"engineLoadError = "无法初始化 PDF 查看器引擎"engineSlowWarning = "PDF 引擎初始化耗时超过预期。请检查你的浏览器 WebAssembly 和 Worker 设置,或重新加载页面。"firstPage = "第一页"+fitPage = "适合页面"+fitWidth = "适合宽度"lastPage = "最后一页"loadingEngine = "正在加载 PDF 引擎..."moreOptions = "更多"diff --git a/frontend/public/locales/zh-CN/translation.toml b/frontend/public/locales/zh-CN/translation.tomlindex 3f495a5eea..086003e77b 100644--- a/frontend/public/locales/zh-CN/translation.toml+++ b/frontend/public/locales/zh-CN/translation.toml@@ -370,6 +370,11 @@ pageVars = "页面信息"position = "定位"positionAndFormatting = "位置与格式"preview = "预览:"+qrCode = "二维码"+qrCodeSize = "二维码大小"+qrContent = "二维码内容"+qrContentDescription = "要编码的文本或链接。支持 @filename 和 @page_number 等动态变量。"+qrContentTooLong = "内容过长,无法放入二维码。请缩短内容。"quickPosition = "选择页面上的一个位置以放置图章。"rotation = "旋转角度"selectedImageAlt = "选定的印章图像"@@ -1993,6 +1998,7 @@ insertText = "插入文本"line = "直线"lineArrow = "箭头"moreActions = "更多操作"+multiClickShapeHint = "双击或按 Enter 键完成"noBackground = "无背景"note = "便笺"notesStamps = "便笺与图章"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "启用褐色滤镜"engineLoadError = "无法初始化 PDF 查看器引擎"engineSlowWarning = "PDF 引擎初始化时间比预期更长。请检查你的浏览器 WebAssembly 和 Worker 设置,或重新加载页面。"firstPage = "第一页"+fitPage = "适合页面"+fitWidth = "适合宽度"lastPage = "最后一页"loadingEngine = "正在加载 PDF 引擎..."moreOptions = "更多"diff --git a/frontend/public/locales/zh-TW/translation.toml b/frontend/public/locales/zh-TW/translation.tomlindex c98add16cd..576920c9ce 100644--- a/frontend/public/locales/zh-TW/translation.toml+++ b/frontend/public/locales/zh-TW/translation.toml@@ -370,6 +370,11 @@ pageVars = "頁面資訊"position = "位置"positionAndFormatting = "位置與格式"preview = "預覽:"+qrCode = "QR 碼"+qrCodeSize = "QR 碼大小"+qrContent = "QR 碼內容"+qrContentDescription = "要編碼的文字或連結。支援 @filename 與 @page_number 等動態變數。"+qrContentTooLong = "內容過長,無法放入 QR 碼。請縮短內容。"quickPosition = "選擇頁面上的位置以放置印章。"rotation = "旋轉"selectedImageAlt = "已選取的圖章影像"@@ -1993,6 +1998,7 @@ insertText = "插入文字"line = "線條"lineArrow = "箭頭"moreActions = "更多操作"+multiClickShapeHint = "按兩下或按 Enter 以完成"noBackground = "無背景"note = "註釋"notesStamps = "註釋與圖章"@@ -13698,6 +13704,8 @@ enableSepiaFilter = "啟用復古濾鏡"engineLoadError = "無法初始化 PDF 檢視器引擎"engineSlowWarning = "PDF 引擎初始化所需時間比預期長。請檢查瀏覽器的 WebAssembly 與 Worker 設定,或重新載入頁面。"firstPage = "第一頁"+fitPage = "適合整頁"+fitWidth = "適合頁寬"lastPage = "最後一頁"loadingEngine = "正在載入 PDF 引擎..."moreOptions = "更多"diff --git a/frontend/src-tauri/tauri.conf.json b/frontend/src-tauri/tauri.conf.jsonindex 4f8ffa2cf9..4a6e890fa6 100644--- a/frontend/src-tauri/tauri.conf.json+++ b/frontend/src-tauri/tauri.conf.json@@ -2,7 +2,7 @@"$schema": "../../node_modules/@tauri-apps/cli/config.schema.json","productName": "Stirling PDF","mainBinaryName": "Stirling-PDF",- "version": "3.2.1",+ "version": "3.2.2","identifier": "stirling.pdf.dev","build": {"frontendDist": "../dist",diff --git a/frontend/src/editor/core/tests/helpers/api-stubs.ts b/frontend/src/editor/core/tests/helpers/api-stubs.tsindex 150bbbc99b..6f71dfa08f 100644--- a/frontend/src/editor/core/tests/helpers/api-stubs.ts+++ b/frontend/src/editor/core/tests/helpers/api-stubs.ts@@ -297,13 +297,6 @@ export async function mockAppApis(}),);- // Folder access reads this on every visit to the System page; unstubbed it- // 401s in a retry loop and the refresh failures sign the session out.- await page.route(- "**/api/v1/admin/settings/policies/implied-folder-roots",- (route: Route) => route.fulfill({ json: { impliedRoots: [] } }),- );-// Same trap on the merged Legal and Advanced pages, which each pull in a// card that fetches on mount.await page.route("**/api/v1/admin/login-agreement/**", (route: Route) =>diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsx b/frontend/src/editor/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsxindex b048866a17..85d9992e54 100644--- a/frontend/src/editor/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsx+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/server/FolderAccessCard.tsx@@ -1,21 +1,11 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback } from "react";import { Icon } from "@editor/ui/Icon";import { InfoTooltip } from "@editor/ui/InfoTooltip";import { useTranslation } from "react-i18next";-import {- Code,- Divider,- Group,- Paper,- Stack,- Text,- TextInput,-} from "@mantine/core";+import { Code, Group, Paper, Stack, Text, TextInput } from "@mantine/core";import { Button } from "@editor/ui/Button";import PendingBadge from "@editor/components/shared/config/PendingBadge";import { useLoginRequired } from "@editor/hooks/useLoginRequired";-import apiClient from "@editor/services/apiClient";-import type { ImpliedFolderRoot } from "@editor/components/shared/config/configSections/server/serverSettings";import type { FolderAccessCardProps } from "@editor/components/shared/config/configSections/server/serverCardProps";/** The directories folder sources and outputs may touch. A security boundary. */@@ -30,37 +20,8 @@ export function FolderAccessCard({const { t } = useTranslation();const { getDisabledStyles } = useLoginRequired();- const [impliedRoots, setImpliedRoots] = useState<ImpliedFolderRoot[]>([]);-- useEffect(() => {- if (!loginEnabled) return;- apiClient- .get<ImpliedFolderRoot[]>(- "/api/v1/admin/settings/policies/implied-folder-roots",- )- .then((res) => setImpliedRoots(res.data ?? []))- .catch(() => setImpliedRoots([]));- }, [loginEnabled]);-const roots = settings.allowedFolderRoots ?? [];- const reasonLabel = (reason: string) => {- switch (reason) {- case "serverStorage":- return t(- "admin.settings.folderAccess.implied.serverStorage",- "Server file storage",- );- case "watchedFolder":- return t(- "admin.settings.folderAccess.implied.watchedFolder",- "Pipeline watched folder",- );- default:- return reason;- }- };-const setRoots = useCallback((next: string[]) => {setSettings({ ...settings, allowedFolderRoots: next });@@ -108,7 +69,7 @@ export function FolderAccessCard({<Text size="xs" c="dimmed">{t("admin.settings.folderAccess.securityNote",- "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory is always off-limits, and folder access is always disabled in hosted (SaaS) mode.",+ "Leave this empty to disable folder sources and outputs entirely. Stirling's own configuration directory, server file storage and the pipeline watched folders are always off-limits, and folder access is always disabled in hosted (SaaS) mode.",)}</Text>@@ -166,45 +127,6 @@ export function FolderAccessCard({{t("admin.settings.folderAccess.roots.add", "Add")}</Button></Group>-- {impliedRoots.length > 0 && (- <>- <Divider />- <Group gap="xs" align="center">- <Text fw={500} size="sm">- {t(- "admin.settings.folderAccess.implied.title",- "Always allowed",- )}- </Text>- <InfoTooltip- label={t(- "admin.settings.folderAccess.implied.description",- "These Stirling-managed directories are always permitted and can't be changed here.",- )}- />- </Group>- <Stack gap="xs">- {impliedRoots.map((root) => (- <Group- key={root.path}- justify="space-between"- wrap="nowrap"- gap="xs"- align="center"- >- <Code style={{ wordBreak: "break-all" }}>{root.path}</Code>- <Group gap={6} wrap="nowrap" style={{ flexShrink: 0 }}>- <Text size="xs" c="dimmed">- {reasonLabel(root.reason)}- </Text>- <Icon name="lock" size="1rem" />- </Group>- </Group>- ))}- </Stack>- </>- )}</Stack></Paper>);diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/server/serverSettings.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/server/serverSettings.tsindex 77242587fe..7269b1129a 100644--- a/frontend/src/editor/proprietary/components/shared/config/configSections/server/serverSettings.ts+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/server/serverSettings.ts@@ -89,11 +89,6 @@ export interface FolderAccessSettingsData {allowedFolderRoots?: string[];}-export interface ImpliedFolderRoot {- path: string;- reason: string;-}-export interface McpAuthData {mode?: string;issuerUri?: string;diff --git a/scripts/counter_translation_v3.py b/scripts/counter_translation_v3.pyindex fa8d0e9b03..2cb2f3c834 100644--- a/scripts/counter_translation_v3.py+++ b/scripts/counter_translation_v3.py@@ -335,7 +335,7 @@ def main() -> None:# Project layout assumptionscwd = os.getcwd()- locales_dir = os.path.join(cwd, "frontend", "editor", "public", "locales")+ locales_dir = os.path.join(cwd, "frontend", "public", "locales")reference_file = os.path.join(locales_dir, "en-US", "translation.toml")scripts_directory = os.path.join(cwd, "scripts")translation_state_file = os.path.join(scripts_directory, "ignore_translation.toml")diff --git a/scripts/translations/bulk_auto_translate.py b/scripts/translations/bulk_auto_translate.pyindex 6ec67030ee..89e08fa6c8 100644--- a/scripts/translations/bulk_auto_translate.py+++ b/scripts/translations/bulk_auto_translate.py@@ -21,6 +21,7 @@ import threadingimport timeimport tomllibfrom concurrent.futures import ThreadPoolExecutor, as_completed+from datetime import datetimefrom pathlib import Pathfrom stale_translations import find_stale, git@@ -95,6 +96,31 @@ def get_language_completion(locales_dir: Path, language: str) -> float | None:return None+def find_error_line(output: str) -> str:+ lines = [line.strip() for line in output.splitlines() if line.strip()]+ if not lines:+ return "Unknown error"+ error_line = next((line for line in lines if "Error" in line), lines[-1])+ return error_line[:300]+++def write_log(log_file: Path, cmd: list[str], stdout: str | bytes | None, stderr: str | bytes | None) -> str:+ api_key = cmd[cmd.index("--api-key") + 1]++ def as_text(stream: str | bytes | None) -> str:+ if isinstance(stream, bytes):+ stream = stream.decode("utf-8", errors="replace")+ return (stream or "").replace(api_key, "***")++ output = as_text(stdout) + as_text(stderr)+ shown_cmd = " ".join("***" if part == api_key else part for part in cmd)+ log_file.write_text(+ f"$ {shown_cmd}\n\n--- stdout ---\n{as_text(stdout)}\n--- stderr ---\n{as_text(stderr)}",+ encoding="utf-8",+ )+ return output++def translate_language(language: str,api_key: str,@@ -103,6 +129,7 @@ def translate_language(skip_verification: bool,include_existing: bool,model: str,+ log_dir: Path,keys_file: Path | None = None,only_keys: bool = False,) -> tuple[str, bool, str]:@@ -137,6 +164,8 @@ def translate_language(if only_keys:cmd.append("--only-keys")+ log_file = log_dir / f"{language}.log"+try:result = subprocess.run(cmd,@@ -144,6 +173,7 @@ def translate_language(text=True,timeout=timeout * 5, # Overall timeout = 5x per-batch timeout)+ output = write_log(log_file, cmd, result.stdout, result.stderr)if result.returncode == 0:# Check if nothing to translate@@ -153,14 +183,13 @@ def translate_language(safe_print(f"[{language}] ✓ Success")return (language, True, "Success")else:- # Show the actual error (last line of output), not the header- output = result.stderr.strip() or result.stdout.strip() or "Unknown error"- error_msg = output.splitlines()[-1][:200]- safe_print(f"[{language}] ✗ Failed: {error_msg}")+ error_msg = find_error_line(output)+ safe_print(f"[{language}] ✗ Failed: {error_msg} (log: {log_file})")return (language, False, error_msg)- except subprocess.TimeoutExpired:- safe_print(f"[{language}] ✗ Timeout exceeded")+ except subprocess.TimeoutExpired as e:+ write_log(log_file, cmd, e.stdout, e.stderr)+ safe_print(f"[{language}] ✗ Timeout exceeded (log: {log_file})")return (language, False, "Timeout exceeded")except Exception as e:safe_print(f"[{language}] ✗ Error: {str(e)}")@@ -256,6 +285,12 @@ Note: Requires OPENAI_API_KEY environment variable or --api-key argument.action="store_true",help="Also retranslate existing keys that match English (default: only translate missing keys)",)+ parser.add_argument(+ "--log-dir",+ default="translation_logs",+ help="Directory for each language's full pipeline output, one timestamped folder per run "+ "(default: translation_logs)",+ )parser.add_argument("--dry-run",action="store_true",@@ -348,6 +383,11 @@ Note: Requires OPENAI_API_KEY environment variable or --api-key argument.start_time = time.time()+ log_root = Path(args.log_dir)+ log_root.mkdir(parents=True, exist_ok=True)+ log_dir = Path(tempfile.mkdtemp(prefix=datetime.now().strftime("%Y%m%d_%H%M%S_"), dir=log_root))+ print(f"Logging each language's output to {log_dir}/\n")+# Stale key lists are handed to auto_translate.py as fileskeys_dir = Path(tempfile.mkdtemp(prefix="stale_keys_"))keys_files: dict[str, Path] = {}@@ -370,6 +410,7 @@ Note: Requires OPENAI_API_KEY environment variable or --api-key argument.args.skip_verification,args.include_existing,args.model,+ log_dir,keys_files.get(lang),args.mode == "changed",): lang@@ -415,6 +456,7 @@ Note: Requires OPENAI_API_KEY environment variable or --api-key argument.print(f"\n❌ Failed ({len(results['failed'])}):")for lang, msg in sorted(results["failed"]):print(f" - {lang}: {msg}")+ print(f" log: {log_dir / f'{lang}.log'}")sys.exit(1)print("\n✅ Bulk translation completed successfully!")diff --git a/scripts/translations/translation_merger.py b/scripts/translations/translation_merger.pyindex 10b4a99d14..62a89777c2 100644--- a/scripts/translations/translation_merger.py+++ b/scripts/translations/translation_merger.py@@ -22,7 +22,7 @@ import tomli_wclass TranslationMerger:def __init__(self,- locales_dir: str = os.path.join(os.getcwd(), "frontend", "editor", "public", "locales"),+ locales_dir: str = os.path.join(os.getcwd(), "frontend", "public", "locales"),ignore_file: str = os.path.join(os.getcwd(), "scripts", "ignore_translation.toml"),):self.locales_dir = Path(locales_dir)@@ -351,7 +351,7 @@ def main():)parser.add_argument("--locales-dir",- default=os.path.join(os.getcwd(), "frontend", "editor", "public", "locales"),+ default=os.path.join(os.getcwd(), "frontend", "public", "locales"),help="Path to locales directory",)parser.add_argument(