Compare commits

..
Author SHA1 Message Date
Anthony Stirling 5aec8b32e2 chore: miscellaneous improvements and dependency updates
Collection of various improvements and fixes:

Build & Dependencies:
- Update build.gradle configuration
- Update frontend dependencies (package.json/package-lock.json)
- Update Tauri configuration (tauri.conf.json)

Frontend improvements:
- PDF validation signature report enhancements
- Form fill improvements (FormFieldOverlay, PdfLibFormProvider)
- Image to PDF utilities
- PDF link utilities and signature flattening
- Account service improvements
- PDF export service enhancements
- Testing utilities updates
- Theme updates (mantineTheme)
- Footer info hook
- PDF lib links hook

Tool operation updates:
- Adjust contrast operation
- Remove annotations operation

Desktop services:
- API client improvements
- Tauri HTTP client enhancements

Auth/Config:
- UseSession improvements
- Admin security section config UI
- Server experience simulations

Onboarding:
- Orchestrator refinements

These changes include bug fixes, code quality improvements, and
feature enhancements that don't fit into specific functional categories.
2026-02-16 10:46:58 +00:00
60 changed files with 375 additions and 721 deletions
@@ -398,9 +398,7 @@ public class ApplicationProperties {
private boolean enableKeystore = true;
private boolean enableKeyRotation = false;
private boolean enableKeyCleanup = true;
private int keyRetentionDays = 30;
private int tokenExpiryMinutes = 1440;
private int allowedClockSkewSeconds = 60;
private int keyRetentionDays = 7;
}
@Data
@@ -9,7 +9,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@@ -26,9 +25,6 @@ import lombok.extern.slf4j.Slf4j;
public class MobileScannerService {
private static final long SESSION_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
private static final Pattern FILENAME_SANITIZE_PATTERN = Pattern.compile("[^a-zA-Z0-9._-]");
private static final Pattern SESSION_ID_VALIDATION_PATTERN = Pattern.compile("[a-zA-Z0-9-]+");
private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");
private final Map<String, SessionData> activeSessions = new ConcurrentHashMap<>();
private final Path tempDirectory;
@@ -125,8 +121,7 @@ public class MobileScannerService {
// Handle duplicate filenames
int counter = 1;
while (Files.exists(filePath)) {
String nameWithoutExt =
FILE_EXTENSION_PATTERN.matcher(safeFilename).replaceFirst("");
String nameWithoutExt = safeFilename.replaceFirst("[.][^.]+$", "");
String ext =
safeFilename.contains(".")
? safeFilename.substring(safeFilename.lastIndexOf("."))
@@ -276,14 +271,14 @@ public class MobileScannerService {
throw new IllegalArgumentException("Session ID cannot be empty");
}
// Basic validation: alphanumeric and hyphens only
if (!SESSION_ID_VALIDATION_PATTERN.matcher(sessionId).matches()) {
if (!sessionId.matches("[a-zA-Z0-9-]+")) {
throw new IllegalArgumentException("Invalid session ID format");
}
}
private String sanitizeFilename(String filename) {
// Remove path traversal attempts and dangerous characters
String sanitized = FILENAME_SANITIZE_PATTERN.matcher(filename).replaceAll("_");
String sanitized = filename.replaceAll("[^a-zA-Z0-9._-]", "_");
// Ensure we have a non-empty, safe filename
if (sanitized.isBlank()) {
sanitized = "upload-" + System.currentTimeMillis();
@@ -47,7 +47,6 @@ public class SvgSanitizer {
private static final Pattern DATA_SCRIPT_PATTERN =
Pattern.compile(
"^\\s*data\\s*:[^,]*(?:script|javascript|vbscript)", Pattern.CASE_INSENSITIVE);
private static final Pattern NULL_BYTE_PATTERN = Pattern.compile("\u0000");
private final SsrfProtectionService ssrfProtectionService;
private final ApplicationProperties applicationProperties;
@@ -211,7 +210,7 @@ public class SvgSanitizer {
String result = url.trim();
result = NULL_BYTE_PATTERN.matcher(result).replaceAll("");
result = result.replaceAll("\u0000", "");
for (int i = 0; i < 3; i++) {
try {
@@ -9,7 +9,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -39,10 +38,6 @@ import stirling.software.common.model.ApplicationProperties;
})
public class SPDFApplication {
private static final Pattern PORT_SUFFIX_PATTERN = Pattern.compile(".+:\\d+$");
private static final Pattern URL_SCHEME_PATTERN =
Pattern.compile("^[a-zA-Z][a-zA-Z0-9+.-]*://.*");
private static final Pattern TRAILING_SLASH_PATTERN = Pattern.compile("/+$");
private static String serverPortStatic;
private static String baseUrlStatic;
private static String contextPathStatic;
@@ -249,8 +244,8 @@ public class SPDFApplication {
String trimmedBase =
(backendUrl == null || backendUrl.isBlank())
? "http://localhost"
: TRAILING_SLASH_PATTERN.matcher(backendUrl.trim()).replaceAll("");
boolean hasScheme = URL_SCHEME_PATTERN.matcher(trimmedBase).matches();
: backendUrl.trim().replaceAll("/+$", "");
boolean hasScheme = trimmedBase.matches("^[a-zA-Z][a-zA-Z0-9+.-]*://.*");
String baseForParsing = hasScheme ? trimmedBase : "http://" + trimmedBase;
Integer parsedPort = parsePort(port);
@@ -303,7 +298,7 @@ public class SPDFApplication {
if (port == null) {
return trimmedBase;
}
if (PORT_SUFFIX_PATTERN.matcher(trimmedBase).matches()) {
if (trimmedBase.matches(".+:\\d+$")) {
return trimmedBase;
}
return trimmedBase + ":" + port;
@@ -8,7 +8,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -52,7 +51,6 @@ import stirling.software.common.util.WebResponseUtils;
@RequiredArgsConstructor
public class MergeController {
private static final Pattern QUOTE_WRAP_PATTERN = Pattern.compile("^\"|\"$");
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
@@ -175,7 +173,7 @@ public class MergeController {
String[] parts = inside.split(",");
String[] result = new String[parts.length];
for (int i = 0; i < parts.length; i++) {
result[i] = QUOTE_WRAP_PATTERN.matcher(parts[i].trim()).replaceAll("");
result[i] = parts[i].trim().replaceAll("^\"|\"$", "");
}
return result;
}
@@ -2,7 +2,6 @@ package stirling.software.SPDF.controller.api.converters;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
@@ -37,7 +36,6 @@ import stirling.software.common.util.WebResponseUtils;
@RequiredArgsConstructor
public class ConvertPdfJsonController {
private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");
private final PdfJsonConversionService pdfJsonConversionService;
@Autowired(required = false)
@@ -61,9 +59,7 @@ public class ConvertPdfJsonController {
String originalName = inputFile.getOriginalFilename();
String baseName =
(originalName != null && !originalName.isBlank())
? FILE_EXTENSION_PATTERN
.matcher(Filenames.toSimpleFileName(originalName))
.replaceFirst("")
? Filenames.toSimpleFileName(originalName).replaceFirst("[.][^.]+$", "")
: "document";
String docName = baseName + ".json";
return WebResponseUtils.bytesToWebResponse(jsonBytes, docName, MediaType.APPLICATION_JSON);
@@ -86,9 +82,7 @@ public class ConvertPdfJsonController {
String originalName = jsonFile.getOriginalFilename();
String baseName =
(originalName != null && !originalName.isBlank())
? FILE_EXTENSION_PATTERN
.matcher(Filenames.toSimpleFileName(originalName))
.replaceFirst("")
? Filenames.toSimpleFileName(originalName).replaceFirst("[.][^.]+$", "")
: "document";
String docName = baseName.endsWith(".pdf") ? baseName : baseName + ".pdf";
return WebResponseUtils.bytesToWebResponse(pdfBytes, docName);
@@ -121,9 +115,7 @@ public class ConvertPdfJsonController {
String originalName = inputFile.getOriginalFilename();
String baseName =
(originalName != null && !originalName.isBlank())
? FILE_EXTENSION_PATTERN
.matcher(Filenames.toSimpleFileName(originalName))
.replaceFirst("")
? Filenames.toSimpleFileName(originalName).replaceFirst("[.][^.]+$", "")
: "document";
String docName = baseName + "_metadata.json";
@@ -160,9 +152,7 @@ public class ConvertPdfJsonController {
String baseName =
(filename != null && !filename.isBlank())
? FILE_EXTENSION_PATTERN
.matcher(Filenames.toSimpleFileName(filename))
.replaceFirst("")
? Filenames.toSimpleFileName(filename).replaceFirst("[.][^.]+$", "")
: Optional.ofNullable(document.getMetadata())
.map(PdfJsonMetadata::getTitle)
.filter(title -> title != null && !title.isBlank())
@@ -57,7 +57,6 @@ import stirling.software.common.util.WebResponseUtils;
@RequiredArgsConstructor
public class StampController {
private static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n");
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
@@ -267,7 +266,7 @@ public class StampController {
.getEscapedNewlinePattern()
.matcher(processedStampText)
.replaceAll("\n");
String[] lines = NEWLINE_PATTERN.split(normalizedText);
String[] lines = normalizedText.split("\\r?\\n");
PDRectangle pageSize = page.getMediaBox();
@@ -21,7 +21,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.springframework.core.io.Resource;
@@ -45,7 +44,6 @@ import stirling.software.common.util.FileMonitor;
public class PipelineDirectoryProcessor {
private static final int MAX_DIRECTORY_DEPTH = 50; // Prevent excessive recursion
private static final Pattern WATCHED_FOLDERS_PATTERN = Pattern.compile("\\\\?watchedFolders");
private final ObjectMapper objectMapper;
private final ApiDocService apiDocService;
@@ -435,12 +433,10 @@ public class PipelineDirectoryProcessor {
private Path determineOutputPath(PipelineConfig config, Path dir) {
String outputDir =
WATCHED_FOLDERS_PATTERN
.matcher(
config.getOutputDir()
.replace("{outputFolder}", finishedFoldersDir)
.replace("{folderName}", dir.toString()))
.replaceAll("");
config.getOutputDir()
.replace("{outputFolder}", finishedFoldersDir)
.replace("{folderName}", dir.toString())
.replaceAll("\\\\?watchedFolders", "");
return Paths.get(outputDir).isAbsolute() ? Paths.get(outputDir) : Paths.get(".", outputDir);
}
@@ -6,7 +6,6 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
@@ -29,8 +28,6 @@ public class ReactRoutingController {
private static final org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(ReactRoutingController.class);
private static final Pattern BASE_HREF_PATTERN =
Pattern.compile("<base href=\\\"[^\\\"]*\\\"\\s*/?>");
@Value("${server.servlet.context-path:/}")
private String contextPath;
@@ -97,9 +94,9 @@ public class ReactRoutingController {
html = html.replace("%BASE_URL%", baseUrl);
// Also rewrite any existing <base> tag (Vite may have baked one in)
html =
BASE_HREF_PATTERN
.matcher(html)
.replaceFirst("<base href=\\\"" + baseUrl + "\\\" />");
html.replaceFirst(
"<base href=\\\"[^\\\"]*\\\"\\s*/?>",
"<base href=\\\"" + baseUrl + "\\\" />");
// Inject context path as a global variable for API calls
String contextPathScript =
@@ -38,7 +38,6 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
@@ -134,9 +133,6 @@ import stirling.software.common.util.TempFileManager;
@RequiredArgsConstructor
public class PdfJsonConversionService {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern WHITESPACE_DASH_UNDERSCORE_PATTERN = Pattern.compile("[\\s\\-_]");
private static final Pattern FONT_SUBSET_PREFIX_PATTERN = Pattern.compile("^[A-Z]{6}\\+");
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final ObjectMapper objectMapper;
private final EndpointConfiguration endpointConfiguration;
@@ -535,10 +531,7 @@ public class PdfJsonConversionService {
: "Unknown";
// Clean up subset prefix (e.g., "ABCDEF+TimesNewRoman"
// -> "TimesNewRoman")
String cleanName =
FONT_SUBSET_PREFIX_PATTERN
.matcher(name)
.replaceAll("");
String cleanName = name.replaceAll("^[A-Z]{6}\\+", "");
return String.format("%s (%s)", cleanName, subtype);
})
.collect(java.util.stream.Collectors.toList());
@@ -1449,9 +1442,9 @@ public class PdfJsonConversionService {
if (!fallbackFontService.canEncodeFully(font, text)) {
String fontName =
fontModel != null && fontModel.getBaseName() != null
? FONT_SUBSET_PREFIX_PATTERN
.matcher(fontModel.getBaseName())
.replaceAll("") // Remove subset prefix
? fontModel
.getBaseName()
.replaceAll("^[A-Z]{6}\\+", "") // Remove subset prefix
: (font != null ? font.getName() : "unknown");
String fontKey = fontName + ":" + element.getFontId() + ":" + pageNumber;
if (!warnedFonts.contains(fontKey)) {
@@ -1909,10 +1902,7 @@ public class PdfJsonConversionService {
if (plusIndex >= 0 && plusIndex < normalized.length() - 1) {
normalized = normalized.substring(plusIndex + 1);
}
normalized =
WHITESPACE_DASH_UNDERSCORE_PATTERN
.matcher(normalized.toLowerCase(Locale.ROOT))
.replaceAll("");
normalized = normalized.toLowerCase(Locale.ROOT).replaceAll("[\\s\\-_]", "");
// Exact match after normalization
try {
@@ -3266,7 +3256,7 @@ public class PdfJsonConversionService {
if (value == null) {
return "";
}
String trimmed = WHITESPACE_PATTERN.matcher(value).replaceAll(" ").trim();
String trimmed = value.replaceAll("\s+", " ").trim();
if (trimmed.length() <= 32) {
return trimmed;
}
@@ -7,7 +7,6 @@ import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
@@ -311,11 +310,6 @@ public class PdfJsonFallbackFontService {
"classpath:/static/fonts/DejaVuSansMono-BoldOblique.ttf",
"DejaVuSansMono-BoldOblique",
"ttf")));
private static final Pattern BOLD_FONT_WEIGHT_PATTERN =
Pattern.compile(".*[_-]?[6-9]00(wght)?.*");
private static final Pattern FONT_NAME_DELIMITER_PATTERN = Pattern.compile("[-_,+]");
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern PATTERN = Pattern.compile("^[A-Z]{6}\\+");
private final ResourceLoader resourceLoader;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
@@ -424,18 +418,16 @@ public class PdfJsonFallbackFontService {
// Normalize font name: remove subset prefix (e.g. "PXAAAC+"), convert to lowercase,
// remove spaces
String normalized =
WHITESPACE_PATTERN
.matcher(
PATTERN.matcher(originalFontName)
.replaceAll("") // Remove subset prefix
.toLowerCase())
.replaceAll(""); // Remove spaces (e.g. "Times New Roman" ->
originalFontName
.replaceAll("^[A-Z]{6}\\+", "") // Remove subset prefix
.toLowerCase()
.replaceAll("\\s+", ""); // Remove spaces (e.g. "Times New Roman" ->
// "timesnewroman")
// Extract base name without weight/style suffixes
// Split on common delimiters: hyphen, underscore, comma, plus
// Handles: "Arimo_700wght" -> "arimo", "Arial-Bold" -> "arial", "Arial,Bold" -> "arial"
String baseName = FONT_NAME_DELIMITER_PATTERN.split(normalized)[0];
String baseName = normalized.split("[-_,+]")[0];
String aliasedFontId = FONT_NAME_ALIASES.get(baseName);
if (aliasedFontId != null) {
@@ -478,7 +470,7 @@ public class PdfJsonFallbackFontService {
// Check for numeric weight indicators (600-900 = bold)
// Handles: "Arimo_700wght", "Arial-700", "Font-w700"
if (BOLD_FONT_WEIGHT_PATTERN.matcher(normalizedFontName).matches()) {
if (normalizedFontName.matches(".*[_-]?[6-9]00(wght)?.*")) {
return true;
}
@@ -522,7 +514,7 @@ public class PdfJsonFallbackFontService {
// Supported: Liberation (Sans/Serif/Mono), Noto Sans, DejaVu (Sans/Serif/Mono)
boolean isSupported =
baseFontId.startsWith("fallback-liberation-")
|| "fallback-noto-sans".equals(baseFontId)
|| baseFontId.equals("fallback-noto-sans")
|| baseFontId.startsWith("fallback-dejavu-");
if (!isSupported) {
@@ -531,8 +523,8 @@ public class PdfJsonFallbackFontService {
// DejaVu Sans and Mono use "oblique" instead of "italic"
boolean useOblique =
"fallback-dejavu-sans".equals(baseFontId)
|| "fallback-dejavu-mono".equals(baseFontId);
baseFontId.equals("fallback-dejavu-sans")
|| baseFontId.equals("fallback-dejavu-mono");
if (isBold && isItalic) {
return baseFontId + (useOblique ? "-boldoblique" : "-bolditalic");
@@ -9,7 +9,6 @@ import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.springframework.stereotype.Service;
@@ -28,7 +27,6 @@ import stirling.software.common.configuration.InstallationPathConfig;
@Slf4j
public class SharedSignatureService {
private static final Pattern FILENAME_VALIDATION_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]+$");
private final String SIGNATURE_BASE_PATH;
private final String ALL_USERS_FOLDER = "ALL_USERS";
private final ObjectMapper objectMapper;
@@ -107,7 +105,7 @@ public class SharedSignatureService {
throw new IllegalArgumentException("Invalid filename");
}
// Only allow alphanumeric, hyphen, underscore, and dot (for extensions)
if (!FILENAME_VALIDATION_PATTERN.matcher(fileName).matches()) {
if (!fileName.matches("^[a-zA-Z0-9_.-]+$")) {
throw new IllegalArgumentException("Filename contains invalid characters");
}
}
@@ -115,7 +113,7 @@ public class SharedSignatureService {
private String validateAndNormalizeExtension(String extension) {
String normalized = extension.toLowerCase().trim();
// Whitelist only safe image extensions
if ("png".equals(normalized) || "jpg".equals(normalized) || "jpeg".equals(normalized)) {
if (normalized.equals("png") || normalized.equals("jpg") || normalized.equals("jpeg")) {
return normalized;
}
throw new IllegalArgumentException("Unsupported image extension: " + extension);
@@ -64,9 +64,7 @@ security:
persistence: true # Set to 'true' to enable JWT key store
enableKeyRotation: true # Set to 'true' to enable key pair rotation
enableKeyCleanup: true # Set to 'true' to enable key pair cleanup
keyRetentionDays: 30 # Number of days to retain old keys. The default is 30 days.
tokenExpiryMinutes: 1440 # JWT access token lifetime in minutes (1 day).
allowedClockSkewSeconds: 60 # Allowed JWT validation clock skew in seconds to tolerate small client/server time drift.
keyRetentionDays: 7 # Number of days to retain old keys. The default is 7 days.
validation: # PDF signature validation settings
trust:
serverAsAnchor: true # Trust server certificate as anchor for PDF signatures (if configured and self-signed or CA)
@@ -18,7 +18,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.jupiter.api.AfterEach;
@@ -47,7 +46,6 @@ import stirling.software.common.util.WebResponseUtils;
public class ConvertWebsiteToPdfTest {
private static final Pattern PDF_FILENAME_PATTERN = Pattern.compile("[A-Za-z0-9_]+\\.pdf");
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private RuntimePathConfig runtimePathConfig;
@@ -144,7 +142,7 @@ public class ConvertWebsiteToPdfTest {
assertTrue(out.endsWith(".pdf"));
// Only A–Z, a–z, 0–9, underscore and dot allowed
assertTrue(PDF_FILENAME_PATTERN.matcher(out).matches());
assertTrue(out.matches("[A-Za-z0-9_]+\\.pdf"));
// no truncation here (source not that long)
assertTrue(out.length() <= 54);
}
@@ -161,7 +159,7 @@ public class ConvertWebsiteToPdfTest {
String out = (String) m.invoke(sut, longUrl);
assertTrue(out.endsWith(".pdf"));
assertTrue(PDF_FILENAME_PATTERN.matcher(out).matches());
assertTrue(out.matches("[A-Za-z0-9_]+\\.pdf"));
// safeName limited to 50 -> total max 54 including '.pdf'
assertTrue(out.length() <= 54, "Filename should be truncated to 50 + '.pdf'");
}
@@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -27,18 +26,6 @@ import stirling.software.common.util.TempFileManager;
@ExtendWith(MockitoExtension.class)
class StampControllerTest {
private static final Pattern UUID_HEX_PATTERN = Pattern.compile("[0-9a-f]{8}");
private static final Pattern DATE_LITERAL_REGEX =
Pattern.compile("@date is \\d{4}-\\d{2}-\\d{2}");
private static final Pattern DATE_TIME_MIN_PATTERN =
Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}");
private static final Pattern DATE_SLASH_PATTERN = Pattern.compile("\\d{2}/\\d{2}/\\d{4}");
private static final Pattern DAY_LABEL_PATTERN = Pattern.compile("Day: \\d{2}");
private static final Pattern MONTH_LABEL_PATTERN = Pattern.compile("Month: \\d{2}");
private static final Pattern DATE_TIME_FULL_PATTERN =
Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
private static final Pattern TIME_LABEL_PATTERN = Pattern.compile("Time: \\d{2}:\\d{2}:\\d{2}");
private static final Pattern DATE_LABEL_PATTERN = Pattern.compile("Date: \\d{4}-\\d{2}-\\d{2}");
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@@ -186,7 +173,7 @@ class StampControllerTest {
void testDateReplacement() throws Exception {
String result = invokeProcessStampText("Date: @date", 1, 1, "test.pdf", null);
assertTrue(
DATE_LABEL_PATTERN.matcher(result).matches(),
result.matches("Date: \\d{4}-\\d{2}-\\d{2}"),
"Date should match YYYY-MM-DD format");
}
@@ -195,7 +182,7 @@ class StampControllerTest {
void testTimeReplacement() throws Exception {
String result = invokeProcessStampText("Time: @time", 1, 1, "test.pdf", null);
assertTrue(
TIME_LABEL_PATTERN.matcher(result).matches(),
result.matches("Time: \\d{2}:\\d{2}:\\d{2}"),
"Time should match HH:mm:ss format");
}
@@ -205,7 +192,7 @@ class StampControllerTest {
String result = invokeProcessStampText("@datetime", 1, 1, "test.pdf", null);
// DateTime format: YYYY-MM-DD HH:mm:ss
assertTrue(
DATE_TIME_FULL_PATTERN.matcher(result).matches(),
result.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"),
"DateTime should match YYYY-MM-DD HH:mm:ss format");
}
@@ -221,15 +208,14 @@ class StampControllerTest {
@DisplayName("Should replace @month with zero-padded month")
void testMonthReplacement() throws Exception {
String result = invokeProcessStampText("Month: @month", 1, 1, "test.pdf", null);
assertTrue(
MONTH_LABEL_PATTERN.matcher(result).matches(), "Month should be zero-padded");
assertTrue(result.matches("Month: \\d{2}"), "Month should be zero-padded");
}
@Test
@DisplayName("Should replace @day with zero-padded day")
void testDayReplacement() throws Exception {
String result = invokeProcessStampText("Day: @day", 1, 1, "test.pdf", null);
assertTrue(DAY_LABEL_PATTERN.matcher(result).matches(), "Day should be zero-padded");
assertTrue(result.matches("Day: \\d{2}"), "Day should be zero-padded");
}
}
@@ -242,7 +228,7 @@ class StampControllerTest {
void testCustomDateFormatSlash() throws Exception {
String result = invokeProcessStampText("@date{dd/MM/yyyy}", 1, 1, "test.pdf", null);
assertTrue(
DATE_SLASH_PATTERN.matcher(result).matches(),
result.matches("\\d{2}/\\d{2}/\\d{4}"),
"Should match dd/MM/yyyy format: " + result);
}
@@ -252,7 +238,7 @@ class StampControllerTest {
String result =
invokeProcessStampText("@date{yyyy-MM-dd HH:mm}", 1, 1, "test.pdf", null);
assertTrue(
DATE_TIME_MIN_PATTERN.matcher(result).matches(),
result.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}"),
"Should match yyyy-MM-dd HH:mm format: " + result);
}
@@ -359,7 +345,7 @@ class StampControllerTest {
// @@date should become @date, and @date should be replaced with actual date
assertTrue(result.startsWith("@date is "), "Should start with literal @date");
assertTrue(
DATE_LITERAL_REGEX.matcher(result).matches(),
result.matches("@date is \\d{4}-\\d{2}-\\d{2}"),
"Should have date after: " + result);
}
@@ -477,9 +463,7 @@ class StampControllerTest {
@DisplayName("UUID should contain only hex characters")
void testUuidFormat() throws Exception {
String result = invokeProcessStampText("@uuid", 1, 1, "test.pdf", null);
assertTrue(
UUID_HEX_PATTERN.matcher(result).matches(),
"UUID should be 8 hex characters: " + result);
assertTrue(result.matches("[0-9a-f]{8}"), "UUID should be 8 hex characters: " + result);
}
}
@@ -34,7 +34,6 @@ import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.api.user.MfaCodeRequest;
import stirling.software.proprietary.security.model.api.user.UsernameAndPassMfa;
import stirling.software.proprietary.security.model.exception.AuthenticationFailureException;
import stirling.software.proprietary.security.service.CustomUserDetailsService;
import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService;
@@ -181,12 +180,7 @@ public class AuthController {
return ResponseEntity.ok(
Map.of(
"user", buildUserResponse(user),
"session",
Map.of(
"access_token",
token,
"expires_in",
getTokenExpirySeconds())));
"session", Map.of("access_token", token, "expires_in", 3600)));
} catch (UsernameNotFoundException e) {
String username = request.getUsername();
@@ -278,7 +272,8 @@ public class AuthController {
.body(Map.of("error", "No token found"));
}
String username = jwtService.extractUsernameAllowExpired(token);
jwtService.validateToken(token);
String username = jwtService.extractUsername(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
User user = (User) userDetails;
@@ -294,17 +289,8 @@ public class AuthController {
return ResponseEntity.ok(
Map.of(
"user", buildUserResponse(user),
"session",
Map.of(
"access_token",
newToken,
"expires_in",
getTokenExpirySeconds())));
"session", Map.of("access_token", newToken, "expires_in", 3600)));
} catch (AuthenticationFailureException e) {
log.error("Token refresh error", e);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "Token refresh failed"));
} catch (Exception e) {
log.error("Token refresh error", e);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
@@ -546,12 +532,6 @@ public class AuthController {
return userMap;
}
private long getTokenExpirySeconds() {
int configuredMinutes = securityProperties.getJwt().getTokenExpiryMinutes();
int expiryMinutes = configuredMinutes > 0 ? configuredMinutes : 720;
return expiryMinutes * 60L;
}
private ResponseEntity<?> ensureWebAuth(User user) {
if (!AuthenticationType.WEB.name().equalsIgnoreCase(user.getAuthenticationType())) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
@@ -9,7 +9,6 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.regex.Pattern;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -37,7 +36,6 @@ import stirling.software.common.configuration.RuntimePathConfig;
@RequiredArgsConstructor
public class UIDataTessdataController {
private static final Pattern INVALID_LANG_CHARS_PATTERN = Pattern.compile("[^A-Za-z0-9_+\\-]");
private final RuntimePathConfig runtimePathConfig;
private static volatile List<String> cachedRemoteTessdata = null;
private static volatile long cachedRemoteTessdataExpiry = 0L;
@@ -90,7 +88,7 @@ public class UIDataTessdataController {
failed.add(language);
continue;
}
String safeLang = INVALID_LANG_CHARS_PATTERN.matcher(language).replaceAll("");
String safeLang = language.replaceAll("[^A-Za-z0-9_+\\-]", "");
if (!safeLang.equals(language)) {
failed.add(language);
continue;
@@ -30,7 +30,6 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.security.model.JwtVerificationKey;
import stirling.software.proprietary.security.model.exception.AuthenticationFailureException;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
@@ -40,21 +39,17 @@ import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrin
public class JwtService implements JwtServiceInterface {
private static final String ISSUER = "https://stirling.com";
private static final long ONE_MINUTE_MILLIS = 60_000L;
private static final int DEFAULT_EXPIRY_MINUTES = 720;
private static final long EXPIRATION = 43200000;
private final KeyPersistenceServiceInterface keyPersistenceService;
private final boolean v2Enabled;
private final ApplicationProperties.Security securityProperties;
@Autowired
public JwtService(
@Qualifier("v2Enabled") boolean v2Enabled,
KeyPersistenceServiceInterface keyPersistenceService,
ApplicationProperties applicationProperties) {
KeyPersistenceServiceInterface keyPersistenceService) {
this.v2Enabled = v2Enabled;
this.keyPersistenceService = keyPersistenceService;
this.securityProperties = applicationProperties.getSecurity();
}
@Override
@@ -91,8 +86,7 @@ public class JwtService implements JwtServiceInterface {
.subject(username)
.issuer(ISSUER)
.issuedAt(new Date())
.expiration(
new Date(System.currentTimeMillis() + getExpirationMillis()))
.expiration(new Date(System.currentTimeMillis() + EXPIRATION))
.signWith(keyPair.getPrivate(), Jwts.SIG.RS256);
String keyId = activeKey.getKeyId();
@@ -120,23 +114,12 @@ public class JwtService implements JwtServiceInterface {
return extractClaim(token, Claims::getSubject);
}
@Override
public String extractUsernameAllowExpired(String token) {
return extractClaim(token, Claims::getSubject, true);
}
@Override
public Map<String, Object> extractClaims(String token) {
Claims claims = extractAllClaims(token);
return new HashMap<>(claims);
}
@Override
public Map<String, Object> extractClaimsAllowExpired(String token) {
Claims claims = extractAllClaims(token, true);
return new HashMap<>(claims);
}
@Override
public boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
@@ -147,21 +130,11 @@ public class JwtService implements JwtServiceInterface {
}
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token, false);
return claimsResolver.apply(claims);
}
private <T> T extractClaim(
String token, Function<Claims, T> claimsResolver, boolean allowExpired) {
final Claims claims = extractAllClaims(token, allowExpired);
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return extractAllClaims(token, false);
}
private Claims extractAllClaims(String token, boolean allowExpired) {
try {
String keyId = extractKeyId(token);
KeyPair keyPair;
@@ -208,7 +181,6 @@ public class JwtService implements JwtServiceInterface {
return Jwts.parser()
.verifyWith(keyPair.getPublic())
.clockSkewSeconds(getAllowedClockSkewSeconds())
.build()
.parseSignedClaims(token)
.getPayload();
@@ -219,9 +191,6 @@ public class JwtService implements JwtServiceInterface {
log.warn("Invalid token: {}", e.getMessage());
throw new AuthenticationFailureException("Invalid token", e);
} catch (ExpiredJwtException e) {
if (allowExpired) {
return e.getClaims();
}
log.warn("The token has expired: {}", e.getMessage());
throw new AuthenticationFailureException("The token has expired", e);
} catch (UnsupportedJwtException e) {
@@ -241,7 +210,6 @@ public class JwtService implements JwtServiceInterface {
keyPersistenceService.decodePublicKey(activeKey.getVerifyingKey());
return Jwts.parser()
.verifyWith(publicKey)
.clockSkewSeconds(getAllowedClockSkewSeconds())
.build()
.parseSignedClaims(token)
.getPayload();
@@ -262,7 +230,6 @@ public class JwtService implements JwtServiceInterface {
verificationKey.getVerifyingKey());
return Jwts.parser()
.verifyWith(publicKey)
.clockSkewSeconds(getAllowedClockSkewSeconds())
.build()
.parseSignedClaims(token)
.getPayload();
@@ -309,7 +276,6 @@ public class JwtService implements JwtServiceInterface {
(String)
Jwts.parser()
.verifyWith(signingKey)
.clockSkewSeconds(getAllowedClockSkewSeconds())
.build()
.parse(token)
.getHeader()
@@ -320,15 +286,4 @@ public class JwtService implements JwtServiceInterface {
return null;
}
}
private long getExpirationMillis() {
int configuredMinutes = securityProperties.getJwt().getTokenExpiryMinutes();
int expiryMinutes = configuredMinutes > 0 ? configuredMinutes : DEFAULT_EXPIRY_MINUTES;
return expiryMinutes * ONE_MINUTE_MILLIS;
}
private long getAllowedClockSkewSeconds() {
int configuredSeconds = securityProperties.getJwt().getAllowedClockSkewSeconds();
return configuredSeconds >= 0 ? configuredSeconds : 60L;
}
}
@@ -41,15 +41,6 @@ public interface JwtServiceInterface {
*/
String extractUsername(String token);
/**
* Extract username from JWT token while allowing expired tokens. Signature and token structure
* must still be valid.
*
* @param token the JWT token
* @return username extracted from token
*/
String extractUsernameAllowExpired(String token);
/**
* Extract all claims from JWT token
*
@@ -58,15 +49,6 @@ public interface JwtServiceInterface {
*/
Map<String, Object> extractClaims(String token);
/**
* Extract all claims from JWT token while allowing expired tokens. Signature and token
* structure must still be valid.
*
* @param token the JWT token
* @return map of claims
*/
Map<String, Object> extractClaimsAllowExpired(String token);
/**
* Check if token is expired
*
@@ -6,7 +6,6 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -34,7 +33,6 @@ public class TotpService {
private static final String HMAC_ALGORITHM = "HmacSHA1";
private static final String DEFAULT_ISSUER = "Stirling PDF";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final Pattern TOTP_CODE_PATTERN = Pattern.compile("\\d{6}");
private final ApplicationProperties applicationProperties;
@@ -73,7 +71,7 @@ public class TotpService {
}
String normalizedCode = code.replace(" ", "");
if (!TOTP_CODE_PATTERN.matcher(normalizedCode).matches()) {
if (!normalizedCode.matches("\\d{6}")) {
return null;
}
@@ -10,7 +10,6 @@ import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.springframework.stereotype.Service;
@@ -33,7 +32,6 @@ import stirling.software.proprietary.model.api.signature.SavedSignatureResponse;
@Slf4j
public class SignatureService implements PersonalSignatureServiceInterface {
private static final Pattern FILENAME_VALIDATION_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]+$");
private final String SIGNATURE_BASE_PATH;
private final String ALL_USERS_FOLDER = "ALL_USERS";
private final ObjectMapper objectMapper = new ObjectMapper();
@@ -368,14 +366,14 @@ public class SignatureService implements PersonalSignatureServiceInterface {
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
throw new IllegalArgumentException("Invalid filename");
}
if (!FILENAME_VALIDATION_PATTERN.matcher(fileName).matches()) {
if (!fileName.matches("^[a-zA-Z0-9_.-]+$")) {
throw new IllegalArgumentException("Filename contains invalid characters");
}
}
private String validateAndNormalizeExtension(String extension) {
String normalized = extension.toLowerCase().trim();
if ("png".equals(normalized) || "jpg".equals(normalized) || "jpeg".equals(normalized)) {
if (normalized.equals("png") || normalized.equals("jpg") || normalized.equals("jpeg")) {
return normalized;
}
throw new IllegalArgumentException("Unsupported image extension: " + extension);
@@ -58,7 +58,6 @@ class AuthControllerLoginTest {
void setUp() {
securityProperties = new ApplicationProperties.Security();
securityProperties.setLoginMethod("all");
securityProperties.getJwt().setTokenExpiryMinutes(60);
AuthController controller =
new AuthController(
@@ -176,7 +175,7 @@ class AuthControllerLoginTest {
void refreshReturnsNewTokenWhenValid() throws Exception {
User user = buildUser();
when(jwtService.extractToken(any())).thenReturn("old");
when(jwtService.extractUsernameAllowExpired("old")).thenReturn("user@example.com");
when(jwtService.extractUsername("old")).thenReturn("user@example.com");
when(userDetailsService.loadUserByUsername("user@example.com")).thenReturn(user);
when(jwtService.generateToken(eq("user@example.com"), any(Map.class)))
.thenReturn("new-token");
@@ -31,7 +31,6 @@ import org.springframework.security.core.Authentication;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.security.model.JwtVerificationKey;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.exception.AuthenticationFailureException;
@@ -65,8 +64,7 @@ class JwtServiceTest {
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded());
testVerificationKey = new JwtVerificationKey("test-key-id", encodedPublicKey);
ApplicationProperties applicationProperties = new ApplicationProperties();
jwtService = new JwtService(true, keystoreService, applicationProperties);
jwtService = new JwtService(true, keystoreService);
}
@Test
@@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
@@ -17,8 +16,6 @@ import stirling.software.proprietary.security.util.Base32Codec;
class TotpServiceTest {
private static final Pattern PATTERN = Pattern.compile("[A-Z2-7]+");
private TotpService buildService(String appName) {
ApplicationProperties properties = new ApplicationProperties();
ApplicationProperties.Ui ui = new ApplicationProperties.Ui();
@@ -35,7 +32,7 @@ class TotpServiceTest {
assertNotNull(secret);
assertEquals(32, secret.length());
assertTrue(PATTERN.matcher(secret).matches());
assertTrue(secret.matches("[A-Z2-7]+"));
}
@Test
@@ -208,7 +208,7 @@ export function useOnboardingOrchestrator(
try {
const [accountData, loginPageData] = await Promise.all([
accountService.getAccountData(),
accountService.getAccountData({ suppressErrorToast: true }),
accountService.getLoginPageData(),
]);
@@ -8,7 +8,6 @@ import type {
AnnotationEvent,
AnnotationPatch,
} from '@app/components/viewer/viewerTypes';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
type NoteIcon = NonNullable<AnnotationToolOptions['icon']>;
@@ -291,7 +290,6 @@ const TOOL_DEFAULT_BUILDERS: Record<AnnotationToolId, ToolDefaultsBuilder> = {
export const AnnotationAPIBridge = forwardRef<AnnotationAPI>(function AnnotationAPIBridge(_props, ref) {
// Use the provided annotation API just like SignatureAPIBridge/HistoryAPIBridge
const { provides: annotationApi } = useAnnotationCapability();
const documentReady = useDocumentReady();
const buildAnnotationDefaults = useCallback(
(toolId: AnnotationToolId, options?: AnnotationToolOptions) =>
@@ -325,7 +323,6 @@ export const AnnotationAPIBridge = forwardRef<AnnotationAPI>(function Annotation
activateAnnotationTool: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => {
configureAnnotationTool(toolId, options);
},
isReady: () => !!annotationApi && documentReady,
setAnnotationStyle: (toolId: AnnotationToolId, options?: AnnotationToolOptions) => {
const defaults = buildAnnotationDefaults(toolId, options);
const api = annotationApi as AnnotationApiSurface | undefined;
@@ -3,11 +3,7 @@ import { useAttachmentCapability } from '@embedpdf/plugin-attachment/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { AttachmentState, AttachmentAPIWrapper } from '@app/contexts/viewer/viewerBridges';
import { PdfAttachmentObject } from '@embedpdf/models';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF attachment plugin to the shared ViewerContext.
*/
export function AttachmentAPIBridge() {
const { provides: attachmentCapability } = useAttachmentCapability();
const { registerBridge } = useViewer();
@@ -16,19 +12,10 @@ export function AttachmentAPIBridge() {
isLoading: false,
error: null,
});
const documentReady = useDocumentReady();
const fetchAttachments = useCallback(
async () => {
if (!attachmentCapability || !documentReady) {
// Set error state instead of throwing for better user experience
setState(prev => ({
...prev,
error: 'Document not ready or attachment capability not available',
isLoading: false
}));
return [];
}
if (!attachmentCapability) return [];
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
@@ -55,12 +42,11 @@ export function AttachmentAPIBridge() {
throw error;
}
},
[attachmentCapability, documentReady]
[attachmentCapability]
);
const api = useMemo<AttachmentAPIWrapper | null>(() => {
// Only provide API when both capability AND document are ready
if (!attachmentCapability || !documentReady) return null;
if (!attachmentCapability) return null;
return {
getAttachments: fetchAttachments,
@@ -98,23 +84,15 @@ export function AttachmentAPIBridge() {
});
},
};
}, [attachmentCapability, documentReady, fetchAttachments]);
}, [attachmentCapability, fetchAttachments]);
useEffect(() => {
if (!api) {
// If API becomes null (e.g. document transitions), ensure we unregister stale bridge
registerBridge('attachment', null);
return;
}
if (!api) return;
registerBridge('attachment', {
state,
api,
});
return () => {
registerBridge('attachment', null);
};
}, [api, state, registerBridge]);
return null;
@@ -2,11 +2,7 @@ import { useEffect, useMemo, useState, useCallback } from 'react';
import { useBookmarkCapability, BookmarkCapability } from '@embedpdf/plugin-bookmark/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { BookmarkState, BookmarkAPIWrapper } from '@app/contexts/viewer/viewerBridges';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF bookmark plugin to the shared ViewerContext.
*/
export function BookmarkAPIBridge() {
const { provides: bookmarkCapability } = useBookmarkCapability();
const { registerBridge } = useViewer();
@@ -15,19 +11,9 @@ export function BookmarkAPIBridge() {
isLoading: false,
error: null,
});
const documentReady = useDocumentReady();
const fetchBookmarks = useCallback(
async (capability: BookmarkCapability) => {
if (!documentReady) {
setState(prev => ({
...prev,
error: 'Document not ready or bookmark capability not available',
isLoading: false,
}));
return [];
}
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
const task = capability.getBookmarks();
@@ -48,12 +34,11 @@ export function BookmarkAPIBridge() {
throw error;
}
},
[documentReady]
[]
);
const api = useMemo<BookmarkAPIWrapper | null>(() => {
// Only provide API when both capability AND document are ready
if (!bookmarkCapability || !documentReady) return null;
if (!bookmarkCapability) return null;
return {
fetchBookmarks: () => fetchBookmarks(bookmarkCapability),
@@ -72,22 +57,15 @@ export function BookmarkAPIBridge() {
});
},
};
}, [bookmarkCapability, documentReady, fetchBookmarks]);
}, [bookmarkCapability, fetchBookmarks]);
useEffect(() => {
if (!api) {
registerBridge('bookmark', null);
return;
}
if (!api) return;
registerBridge('bookmark', {
state,
api,
});
return () => {
registerBridge('bookmark', null);
};
}, [api, state, registerBridge]);
return null;
@@ -1,6 +1,5 @@
import { useEffect, useMemo } from 'react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
import {
PdfPermissionFlag,
DocumentPermissionsState,
@@ -26,7 +25,6 @@ export function DocumentPermissionsAPIBridge({
permissions = PdfPermissionFlag.AllowAll,
}: DocumentPermissionsAPIBridgeProps) {
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
const state = useMemo<DocumentPermissionsState>(() => ({
isEncrypted,
@@ -44,7 +42,7 @@ export function DocumentPermissionsAPIBridge({
const api = useMemo<DocumentPermissionsAPIWrapper>(() => ({
hasPermission: (flag: PdfPermissionFlag) => hasPermissionFlag(permissions, flag),
hasAllPermissions: (flags: PdfPermissionFlag[]) =>
hasAllPermissions: (flags: PdfPermissionFlag[]) =>
flags.every(flag => hasPermissionFlag(permissions, flag)),
getEffectivePermission: (flag: PdfPermissionFlag) => {
if (isOwnerUnlocked) return true;
@@ -53,17 +51,11 @@ export function DocumentPermissionsAPIBridge({
}), [permissions, isOwnerUnlocked]);
useEffect(() => {
if (documentReady) {
registerBridge('permissions', {
state,
api,
});
}
return () => {
registerBridge('permissions', null);
};
}, [registerBridge, state, api, documentReady]);
registerBridge('permissions', {
state,
api,
});
}, [registerBridge, state, api]);
return null;
}
@@ -1,7 +1,6 @@
import { useEffect } from 'react';
import { useExportCapability } from '@embedpdf/plugin-export/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Component that runs inside EmbedPDF context and provides export functionality
@@ -9,10 +8,9 @@ import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady'
export function ExportAPIBridge() {
const { provides: exportApi } = useExportCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
useEffect(() => {
if (exportApi && documentReady) {
if (exportApi) {
// Register this bridge with ViewerContext
registerBridge('export', {
state: {
@@ -21,11 +19,7 @@ export function ExportAPIBridge() {
api: exportApi
});
}
return () => {
registerBridge('export', null);
};
}, [exportApi, documentReady, registerBridge]);
}, [exportApi, registerBridge]);
return null;
}
}
@@ -2,25 +2,19 @@ import { useImperativeHandle, forwardRef, useEffect, useRef } from 'react';
import { useHistoryCapability } from '@embedpdf/plugin-history/react';
import { useAnnotationCapability } from '@embedpdf/plugin-annotation/react';
import { useSignature } from '@app/contexts/SignatureContext';
import { uuidV4, PdfAnnotationSubtype } from '@embedpdf/models';
import { PdfAnnotationSubtype, uuidV4 } from '@embedpdf/models';
import type { HistoryAPI } from '@app/components/viewer/viewerTypes';
import { ANNOTATION_RECREATION_DELAY_MS, ANNOTATION_VERIFICATION_DELAY_MS } from '@app/constants/app';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF history (undo/redo) plugin to the shared ViewerContext.
*/
export const HistoryAPIBridge = forwardRef<HistoryAPI>(function HistoryAPIBridge(_, ref) {
const { provides: historyApi } = useHistoryCapability();
const { provides: annotationApi } = useAnnotationCapability();
const { getImageData, storeImageData } = useSignature();
const documentReady = useDocumentReady();
const restoringIds = useRef<Set<string>>(new Set());
// Monitor annotation events to detect when annotations are restored
useEffect(() => {
if (!annotationApi || !documentReady) return;
if (!annotationApi) return;
const handleAnnotationEvent = (event: any) => {
const annotation = event.annotation;
@@ -152,8 +146,6 @@ export const HistoryAPIBridge = forwardRef<HistoryAPI>(function HistoryAPIBridge
return historyApi ? historyApi.canRedo() : false;
},
isReady: () => !!historyApi && documentReady,
purgeByMetadata: <T,>(predicate: (metadata: T | undefined) => boolean, topic?: string) => {
if (historyApi?.purgeByMetadata) {
return historyApi.purgeByMetadata(predicate, topic);
@@ -3,8 +3,7 @@ import { useDocumentState } from '@embedpdf/core/react';
import { useScroll } from '@embedpdf/plugin-scroll/react';
import { useAnnotationCapability } from '@embedpdf/plugin-annotation/react';
import { PdfAnnotationSubtype } from '@embedpdf/models';
import { usePdfLibLinks } from '@app/hooks/usePdfLibLinks';
import type { PdfLibLink } from '@app/utils/pdfLinkUtils';
import { usePdfLibLinks, type PdfLibLink } from '@app/hooks/usePdfLibLinks';
// ---------------------------------------------------------------------------
// Inline SVG icons (thin-stroke, modern)
@@ -125,7 +125,7 @@ export function LocalEmbedPDF({ file, url, fileName, enableAnnotations = false,
}),
createPluginRegistration(ScrollPluginPackage),
createPluginRegistration(RenderPluginPackage, {
withForms: true,
withForms: !enableFormFill, // Disable native form rendering when our interactive overlay is active
withAnnotations: showBakedAnnotations && !enableAnnotations, // Show baked annotations only when: visibility is ON and annotation layer is OFF
}),
@@ -204,7 +204,7 @@ export function LocalEmbedPDF({ file, url, fileName, enableAnnotations = false,
// Register print plugin for printing PDFs
createPluginRegistration(PrintPluginPackage),
];
}, [pdfUrl, enableAnnotations, showBakedAnnotations, fileName, file, url]);
}, [pdfUrl, enableAnnotations, enableFormFill, showBakedAnnotations, fileName, file, url]);
// Initialize the engine with the React hook - use local WASM for offline support
const { engine, isLoading, error } = usePdfiumEngine({
@@ -2,33 +2,28 @@ import { useEffect, useRef } from 'react';
import { usePan } from '@embedpdf/plugin-pan/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF pan (hand tool) plugin to the shared ViewerContext.
*/
export function PanAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and the document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <PanAPIBridgeInner documentId={activeDocumentId} />;
}
function PanAPIBridgeInner({ documentId }: { documentId: string }) {
const { provides: pan, isPanning } = usePan(documentId);
const { registerBridge, triggerImmediatePanUpdate } = useViewer();
// Keep pan ref updated to avoid re-running effect when object reference changes
const panRef = useRef(pan);
useEffect(() => {
panRef.current = pan;
}, [pan]);
// Track previous isPanning value to detect changes
const prevIsPanningRef = useRef<boolean>(isPanning);
@@ -62,16 +57,13 @@ function PanAPIBridgeInner({ documentId }: { documentId: string }) {
},
}
});
// Trigger immediate pan update if the value changed
if (prevIsPanningRef.current !== isPanning) {
prevIsPanningRef.current = isPanning;
triggerImmediatePanUpdate(isPanning);
}
}
return () => {
registerBridge('pan', null);
};
}, [isPanning, registerBridge, triggerImmediatePanUpdate]);
return null;
@@ -1,18 +1,16 @@
import { useEffect } from 'react';
import { usePrintCapability } from '@embedpdf/plugin-print/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF print plugin to the shared ViewerContext.
* Component that runs inside EmbedPDF context and exposes print API to ViewerContext
*/
export function PrintAPIBridge() {
const { provides: print } = usePrintCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
useEffect(() => {
if (print && documentReady) {
if (print) {
// Register this bridge with ViewerContext
registerBridge('print', {
state: {},
@@ -21,11 +19,7 @@ export function PrintAPIBridge() {
}
});
}
return () => {
registerBridge('print', null);
};
}, [print, documentReady, registerBridge]);
}, [print, registerBridge]);
return null;
}
@@ -4,18 +4,17 @@ import { PdfAnnotationSubtype } from '@embedpdf/models';
import { useRedaction } from '@app/contexts/RedactionContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useAnnotationCapability } from '@embedpdf/plugin-annotation/react';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* RedactionAPIBridge - Uses embedPDF v2.5.0
* Bridges between the EmbedPDF redaction plugin and the Stirling-PDF RedactionContext.
* Uses the unified redaction mode (toggleRedact/enableRedact/endRedact).
*/
export function RedactionAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
@@ -70,7 +69,9 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {
}, [annotationProvides, manualRedactColor]);
// Expose the EmbedPDF API through our context's ref
// Uses v2.5.0 unified redaction mode
useImperativeHandle(redactionApiRef, () => ({
// Unified redaction methods (v2.5.0)
toggleRedact: () => {
redactionProvides?.toggleRedact();
},
@@ -2,20 +2,15 @@ import { useEffect, useRef } from 'react';
import { useRotate } from '@embedpdf/plugin-rotate/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF rotation plugin to the shared ViewerContext.
*/
export function RotateAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <RotateAPIBridgeInner documentId={activeDocumentId} />;
}
@@ -47,11 +42,7 @@ function RotateAPIBridgeInner({ documentId }: { documentId: string }) {
}
});
}
return () => {
registerBridge('rotation', null);
};
}, [rotation, registerBridge]);
return null;
}
}
@@ -2,20 +2,15 @@ import { useEffect, useRef } from 'react';
import { useScroll } from '@embedpdf/plugin-scroll/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF scroll plugin to the shared ViewerContext.
*/
export function ScrollAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <ScrollAPIBridgeInner documentId={activeDocumentId} />;
}
@@ -40,7 +35,7 @@ function ScrollAPIBridgeInner({ documentId }: { documentId: string }) {
currentPage,
totalPages,
};
// Trigger immediate update for responsive UI
triggerImmediateScrollUpdate(newState.currentPage, newState.totalPages);
@@ -49,10 +44,6 @@ function ScrollAPIBridgeInner({ documentId }: { documentId: string }) {
api: currentScroll
});
}
return () => {
registerBridge('scroll', null);
};
}, [currentPage, totalPages, registerBridge, triggerImmediateScrollUpdate]);
return null;
@@ -2,7 +2,6 @@ import { useEffect, useState, useRef } from 'react';
import { useSearch } from '@embedpdf/plugin-search/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
interface SearchResult {
pageIndex: number;
@@ -12,35 +11,30 @@ interface SearchResult {
}>;
}
/**
* SearchAPIBridge - Updated for embedPDF v2.6.0
* Connects the PDF search plugin to the shared ViewerContext.
*/
export function SearchAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <SearchAPIBridgeInner documentId={activeDocumentId} />;
}
function SearchAPIBridgeInner({ documentId }: { documentId: string }) {
const { provides: search } = useSearch(documentId);
const { registerBridge, scrollActions } = useViewer();
// Keep search ref updated to avoid re-running effects when object reference changes
const searchRef = useRef(search);
const isSearchingRef = useRef(false);
const lastScrolledIndexRef = useRef<number | null>(null);
useEffect(() => {
searchRef.current = search;
}, [search]);
const [localState, setLocalState] = useState({
results: null as SearchResult[] | null,
activeIndex: 0
@@ -48,14 +42,14 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {
// Subscribe to search result changes from EmbedPDF
const subscriptionRef = useRef<(() => void) | null>(null);
useEffect(() => {
// Cleanup previous subscription
if (subscriptionRef.current) {
subscriptionRef.current();
subscriptionRef.current = null;
}
if (!search) return;
subscriptionRef.current = search.onSearchResultStateChange?.((state: any) => {
@@ -93,11 +87,11 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {
lastScrolledIndexRef.current = null;
return;
}
// Only scroll if the active index actually changed
const activeResultIndex = localActiveIndex - 1; // Convert back to 0-based
if (activeResultIndex >= 0 &&
activeResultIndex < localResults.length &&
if (activeResultIndex >= 0 &&
activeResultIndex < localResults.length &&
lastScrolledIndexRef.current !== activeResultIndex) {
const activeResult = localResults[activeResultIndex];
if (activeResult) {
@@ -120,13 +114,13 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {
if (isSearchingRef.current) {
return null;
}
if (!currentSearch?.startSearch || !currentSearch?.searchAllPages) {
return null;
}
isSearchingRef.current = true;
try {
currentSearch.startSearch();
const results = await currentSearch.searchAllPages(query);
@@ -177,10 +171,6 @@ function SearchAPIBridgeInner({ documentId }: { documentId: string }) {
}
});
}
return () => {
registerBridge('search', null);
};
}, [localResults, localActiveIndex, registerBridge]);
return null;
@@ -1,22 +1,17 @@
import { useEffect, useRef } from 'react';
import { useSelectionCapability } from '@embedpdf/plugin-selection/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF selection plugin to the shared ViewerContext.
*/
export function SelectionAPIBridge() {
const { provides: selection } = useSelectionCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
const hasSelectionRef = useRef(false);
const selectedTextRef = useRef('');
useEffect(() => {
if (!selection || !documentReady) return;
if (!selection) return;
const buildApi = () => ({
copyToClipboard: () => selection.copyToClipboard(),
@@ -73,9 +68,8 @@ export function SelectionAPIBridge() {
unsubCopy?.();
document.removeEventListener('copy', handleCopy);
document.removeEventListener('keydown', handleKeyDown);
registerBridge('selection', null);
};
}, [selection, documentReady, registerBridge]);
}, [selection]);
return null;
}
@@ -5,11 +5,6 @@ import { useSignature } from '@app/contexts/SignatureContext';
import type { SignatureAPI } from '@app/components/viewer/viewerTypes';
import type { SignParameters } from '@app/hooks/tools/sign/useSignParameters';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF signature (stamp/ink) tools to the shared ViewerContext and SignatureContext.
*/
// Minimum allowed width/height (in pixels) for a signature image or text stamp.
// This prevents rendering issues and ensures signatures are always visible and usable.
@@ -137,7 +132,6 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
const { provides: annotationApi } = useAnnotationCapability();
const { signatureConfig, storeImageData, isPlacementMode, placementPreviewSize, setSignaturesApplied } = useSignature();
const { getZoomState, registerImmediateZoomUpdate } = useViewer();
const documentReady = useDocumentReady();
const [currentZoom, setCurrentZoom] = useState(() => getZoomState()?.currentZoom ?? 1);
const lastStampImageRef = useRef<string | null>(null);
@@ -217,7 +211,7 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
// Enable keyboard deletion of selected annotations
useEffect(() => {
// Always enable delete key when we have annotation API and are in sign mode
if (!annotationApi || (isPlacementMode === undefined) || !documentReady) return;
if (!annotationApi || (isPlacementMode === undefined)) return;
const handleKeyDown = (event: KeyboardEvent) => {
// Skip delete/backspace while a text input/textarea is focused (e.g., editing textbox)
@@ -397,7 +391,7 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
}), [annotationApi, signatureConfig, placementPreviewSize, applyStampDefaults]);
useEffect(() => {
if (!annotationApi?.onAnnotationEvent || !documentReady) {
if (!annotationApi?.onAnnotationEvent) {
return;
}
@@ -436,10 +430,10 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
return () => {
unsubscribe?.();
};
}, [annotationApi, storeImageData, setSignaturesApplied, documentReady]);
}, [annotationApi, storeImageData, setSignaturesApplied]);
useEffect(() => {
if (!isPlacementMode || !documentReady) {
if (!isPlacementMode) {
return;
}
@@ -453,7 +447,66 @@ export const SignatureAPIBridge = forwardRef<SignatureAPI>(function SignatureAPI
return () => {
cancelled = true;
};
}, [isPlacementMode, configureStampDefaults, placementPreviewSize, signatureConfig, documentReady]);
}, [isPlacementMode, configureStampDefaults, placementPreviewSize, signatureConfig]);
useEffect(() => {
if (!annotationApi?.onAnnotationEvent) {
return;
}
const unsubscribe = annotationApi.onAnnotationEvent(event => {
if (event.type !== 'create' && event.type !== 'update') {
return;
}
const annotation: any = event.annotation;
const annotationId: string | undefined = annotation?.id;
if (!annotationId) {
return;
}
// Mark signatures as not applied when a new signature is placed
if (event.type === 'create') {
setSignaturesApplied(false);
}
const directData =
extractDataUrl(annotation.imageSrc) ||
extractDataUrl(annotation.imageData) ||
extractDataUrl(annotation.appearance) ||
extractDataUrl(annotation.stampData) ||
extractDataUrl(annotation.contents) ||
extractDataUrl(annotation.data) ||
extractDataUrl(annotation.customData) ||
extractDataUrl(annotation.asset);
const dataToStore = directData || lastStampImageRef.current;
if (dataToStore) {
storeImageData(annotationId, dataToStore);
}
});
return () => {
unsubscribe?.();
};
}, [annotationApi, storeImageData, setSignaturesApplied]);
useEffect(() => {
if (!isPlacementMode) {
return;
}
let cancelled = false;
configureStampDefaults().catch((error) => {
if (!cancelled) {
console.error('Error updating signature defaults:', error);
}
});
return () => {
cancelled = true;
};
}, [isPlacementMode, configureStampDefaults, placementPreviewSize, signatureConfig]);
return null; // This is a bridge component with no UI
@@ -2,21 +2,15 @@ import { useEffect, useRef } from 'react';
import { useSpread, SpreadMode } from '@embedpdf/plugin-spread/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useActiveDocumentId } from '@app/components/viewer/useActiveDocumentId';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* SpreadAPIBridge - Updated for embedPDF v2.6.0
* Connects the PDF spread mode (single/dual page) plugin to the shared ViewerContext.
*/
export function SpreadAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <SpreadAPIBridgeInner documentId={activeDocumentId} />;
}
@@ -58,10 +52,6 @@ function SpreadAPIBridgeInner({ documentId }: { documentId: string }) {
});
triggerImmediateSpreadUpdate(spreadMode);
return () => {
registerBridge('spread', null);
};
}, [spreadMode, registerBridge, triggerImmediateSpreadUpdate]);
return null;
@@ -1,29 +1,23 @@
import { useEffect } from 'react';
import { useThumbnailCapability } from '@embedpdf/plugin-thumbnail/react';
import { useViewer } from '@app/contexts/ViewerContext';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* ThumbnailAPIBridge - Updated for embedPDF v2.6.0
* Provides thumbnail generation functionality.
* ThumbnailAPIBridge provides thumbnail generation functionality.
* Exposes thumbnail API to UI components without managing state.
*/
export function ThumbnailAPIBridge() {
const { provides: thumbnail } = useThumbnailCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
useEffect(() => {
if (thumbnail && documentReady) {
if (thumbnail) {
registerBridge('thumbnail', {
state: null, // No state - just provides API
api: thumbnail
});
}
return () => {
registerBridge('thumbnail', null);
};
}, [thumbnail, documentReady, registerBridge]);
}, [thumbnail]);
return null;
}
@@ -11,20 +11,15 @@ import {
useFitWidthResize,
} from '@app/utils/viewerZoom';
import { getFirstPageAspectRatioFromStub } from '@app/utils/pageMetadata';
import { useDocumentReady } from '@app/components/viewer/hooks/useDocumentReady';
/**
* Connects the PDF zoom plugin to the shared ViewerContext.
*/
export function ZoomAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
// Don't render the inner component until we have a valid document ID
if (!activeDocumentId) {
return null;
}
return <ZoomAPIBridgeInner documentId={activeDocumentId} />;
}
@@ -65,7 +60,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
// Extract primitive values from zoomState for dependency arrays
const zoomLevel = zoomState?.zoomLevel;
const currentZoomLevel = zoomState?.currentZoomLevel;
// Extract metadata aspect ratio as a primitive to avoid object reference issues
const metadataAspectRatio = getFirstPageAspectRatioFromStub(firstFileStub);
@@ -205,14 +200,14 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
// Subscribe to zoom changes - use ref to avoid re-subscribing when zoom reference changes
const zoomSubscriptionRef = useRef<(() => void) | null>(null);
useEffect(() => {
// Cleanup previous subscription if any
if (zoomSubscriptionRef.current) {
zoomSubscriptionRef.current();
zoomSubscriptionRef.current = null;
}
if (!zoom) {
return;
}
@@ -260,4 +255,4 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}, [zoomStateCurrentZoomLevel, registerBridge, triggerImmediateZoomUpdate]);
return null;
}
}
@@ -1,67 +0,0 @@
import { useState, useEffect } from 'react';
import { useDocumentManagerCapability } from '@embedpdf/plugin-document-manager/react';
/**
* useDocumentReady - Custom hook to track whether a PDF document is fully loaded
* and ready for interaction.
*
* Subscribes to both onDocumentOpened (sets true) and onDocumentClosed (resets
* to false) so the flag correctly tracks the document lifecycle across
* open → close → reopen transitions.
*
* The initial check is synchronous (getActiveDocument is sync) — no debounce
* needed.
*/
export function useDocumentReady() {
const { provides: documentManagerCapability } = useDocumentManagerCapability();
const [documentReady, setDocumentReady] = useState(false);
useEffect(() => {
if (!documentManagerCapability) {
setDocumentReady(false);
return;
}
let mounted = true;
const unsubOpen = documentManagerCapability.onDocumentOpened?.((event: any) => {
if (mounted && (event?.documentId || event?.id)) {
setDocumentReady(true);
}
});
const unsubClose = documentManagerCapability.onDocumentClosed?.(() => {
if (!mounted) return;
try {
const remaining = documentManagerCapability.getActiveDocument?.();
if (!remaining?.id && mounted) {
setDocumentReady(false);
}
} catch {
if (mounted) setDocumentReady(false);
}
});
try {
const activeDoc = documentManagerCapability.getActiveDocument?.();
if (mounted) {
setDocumentReady(!!activeDoc?.id);
}
} catch {
if (mounted) setDocumentReady(false);
}
return () => {
mounted = false;
if (typeof unsubOpen === 'function') {
unsubOpen();
}
if (typeof unsubClose === 'function') {
unsubClose();
}
};
}, [documentManagerCapability]);
return documentReady;
}
+2 -2
View File
@@ -151,7 +151,7 @@ interface ViewerContextType {
// Bridge registration - internal use by bridges
registerBridge: <K extends BridgeKey>(
type: K,
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]> | null
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]>
) => void;
// Save changes function - registered by EmbedPdfViewer
@@ -242,7 +242,7 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
const registerBridge = useCallback(
<K extends BridgeKey>(
type: K,
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]> | null
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]>
) => {
setBridgeRef(bridgeRefs.current, type, ref);
},
@@ -227,7 +227,7 @@ export const createBridgeRegistry = (): ViewerBridgeRegistry => ({
export function registerBridge<K extends BridgeKey>(
registry: ViewerBridgeRegistry,
type: K,
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]> | null
ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]>
): void {
registry[type] = ref as ViewerBridgeRegistry[K];
}
+17 -10
View File
@@ -10,7 +10,7 @@ import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useLogoPath } from "@app/hooks/useLogoPath";
import { useLogoAssets } from '@app/hooks/useLogoAssets';
import { useFileContext } from "@app/contexts/file/fileHooks";
import { useNavigationActions } from "@app/contexts/NavigationContext";
import { useNavigationState, useNavigationActions } from "@app/contexts/NavigationContext";
import { useViewer } from "@app/contexts/ViewerContext";
import AppsIcon from '@mui/icons-material/AppsRounded';
@@ -55,22 +55,27 @@ export default function HomePage() {
const [configModalOpen, setConfigModalOpen] = useState(false);
const { activeFiles } = useFileContext();
const navigationState = useNavigationState();
const { actions } = useNavigationActions();
const { setActiveFileIndex } = useViewer();
const prevFileCountRef = useRef(0);
const prevFileCountRef = useRef(activeFiles.length);
// Startup/open transition behavior:
// - opening exactly 1 file from empty -> viewer
// - opening 2+ files from empty -> fileEditor
// Auto-switch to viewer when going from 0 to 1 file
// Skip this if PDF Text Editor is active - it handles its own empty state
useEffect(() => {
const prevCount = prevFileCountRef.current;
const currentCount = activeFiles.length;
if (prevCount === 0 && currentCount === 1) {
actions.setWorkbench('viewer');
setActiveFileIndex(0);
} else if (prevCount === 0 && currentCount > 1) {
actions.setWorkbench('fileEditor');
if (
navigationState.workbench !== 'fileEditor' &&
prevCount === 0 &&
currentCount === 1
) {
// PDF Text Editor handles its own empty state with a dropzone
if (selectedToolKey !== 'pdfTextEditor') {
actions.setWorkbench('viewer');
setActiveFileIndex(0);
}
}
prevFileCountRef.current = currentCount;
@@ -78,6 +83,8 @@ export default function HomePage() {
activeFiles.length,
actions,
setActiveFileIndex,
selectedToolKey,
navigationState.workbench,
]);
const brandAltText = t("home.mobile.brandAlt", "Stirling PDF logo");
+5 -2
View File
@@ -35,8 +35,11 @@ export const accountService = {
/**
* Get current user account data
*/
async getAccountData(): Promise<AccountData> {
const response = await apiClient.get<AccountData>('/api/v1/proprietary/ui-data/account');
async getAccountData(options?: { suppressErrorToast?: boolean; skipAuthRedirect?: boolean }): Promise<AccountData> {
const response = await apiClient.get<AccountData>('/api/v1/proprietary/ui-data/account', {
suppressErrorToast: options?.suppressErrorToast,
skipAuthRedirect: options?.skipAuthRedirect,
});
return response.data;
},
+4 -5
View File
@@ -356,11 +356,10 @@ export const mantineTheme = createTheme({
},
control: {
color: 'var(--text-secondary)',
'&[data-active]': {
backgroundColor: 'var(--bg-surface)',
color: 'var(--text-primary)',
boxShadow: 'var(--shadow-sm)',
},
},
indicator: {
backgroundColor: 'var(--bg-surface)',
boxShadow: 'var(--shadow-sm)',
},
},
},
@@ -1,36 +0,0 @@
import { STIRLING_SAAS_URL } from '@app/constants/connection';
import { connectionModeService } from '@app/services/connectionModeService';
import { authService } from '@app/services/authService';
import type { PlatformSessionUser } from '@proprietary/extensions/platformSessionBridge';
export async function isDesktopSaaSAuthMode(): Promise<boolean> {
try {
const mode = await connectionModeService.getCurrentMode();
return mode === 'saas';
} catch {
return false;
}
}
export async function getPlatformSessionUser(): Promise<PlatformSessionUser | null> {
try {
const userInfo = await authService.getUserInfo();
if (!userInfo) {
return null;
}
return {
username: userInfo.username,
email: userInfo.email,
};
} catch {
return null;
}
}
export async function refreshPlatformSession(): Promise<boolean> {
try {
return await authService.refreshSupabaseToken(STIRLING_SAAS_URL);
} catch {
return false;
}
}
@@ -25,6 +25,12 @@ setupApiInterceptors(apiClient as unknown as AxiosInstance);
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
// Let the auth-refresh interceptor handle first-pass 401s silently.
// If refresh/retry fails, the request is marked `_retry` and will fall through
// to normal global handling below.
if (error?.response?.status === 401 && error?.config?._retry !== true) {
return Promise.reject(error);
}
await handleHttpError(error); // Handle error (shows toast unless suppressed)
return Promise.reject(error);
}
@@ -104,16 +104,9 @@ export function setupApiInterceptors(client: AxiosInstance): void {
},
async (error) => {
const originalRequest = error.config as ExtendedRequestConfig;
const requestUrl = String(originalRequest?.url || '');
const isAuthProbeRequest = requestUrl.includes('/api/v1/auth/me');
// Handle 401 Unauthorized - try to refresh token
if (error.response?.status === 401 && !originalRequest._retry) {
// `/auth/me` is used as a probe by session bootstrap; refreshing here can
// create recursion (refresh -> save token -> jwt-available -> /auth/me).
if (isAuthProbeRequest) {
return Promise.reject(error);
}
if (typeof window !== 'undefined') {
console.warn('[apiClientSetup] 401 on path:', window.location.pathname, 'url:', originalRequest.url);
}
+1 -11
View File
@@ -542,17 +542,7 @@ export class AuthService {
}
);
const token =
response.data?.session?.access_token ??
response.data?.access_token ??
response.data?.token;
if (!token) {
console.error('[Desktop AuthService] Refresh response missing token payload');
this.setAuthStatus('unauthenticated', null);
await this.logout();
return false;
}
const { token } = response.data;
// Save token to all storage locations
await this.saveTokenEverywhere(token);
@@ -118,6 +118,16 @@ class TauriHttpClient {
return error;
}
private isResponseLike(value: unknown): value is TauriHttpResponse {
if (!value || typeof value !== 'object') return false;
const candidate = value as Partial<TauriHttpResponse>;
return (
typeof candidate.status === 'number' &&
'data' in candidate &&
candidate.config !== undefined
);
}
private buildUrl(config: TauriHttpRequestConfig): string {
let url = config.url || '';
@@ -316,6 +326,46 @@ class TauriHttpClient {
throw error;
}
// Some layers may throw a response-like object directly.
// Handle it by status instead of incorrectly wrapping as ERR_NETWORK.
if (this.isResponseLike(error)) {
if (error.status >= 200 && error.status < 300) {
return error as TauriHttpResponse<T>;
}
const errorCode =
error.status === 401
? 'ERR_UNAUTHORIZED'
: error.status === 403
? 'ERR_FORBIDDEN'
: error.status === 404
? 'ERR_NOT_FOUND'
: error.status >= 500
? 'ERR_SERVER_ERROR'
: 'ERR_BAD_REQUEST';
const errorMessage = `Request failed with status code ${error.status}`;
const httpError = this.createError(
errorMessage,
finalConfig,
errorCode,
error as TauriHttpResponse,
error
);
let finalError: unknown = httpError;
for (const handler of this.interceptors.response.handlers) {
if (handler.rejected) {
try {
finalError = await Promise.resolve(handler.rejected(finalError));
} catch (e) {
finalError = e;
}
}
}
throw finalError;
}
// Create detailed error messages for network/other failures
let errorMessage = 'Network Error';
let errorCode = 'ERR_NETWORK';
+14 -9
View File
@@ -108,12 +108,20 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const mountId = Math.random().toString(36).substring(7);
console.log(`[Auth:${mountId}] 🔵 AuthProvider mounted`);
const initializeAuth = async () => {
const initializeAuth = async (showLoading = false) => {
try {
if (showLoading) {
setLoading(true);
}
console.debug(`[Auth:${mountId}] Initializing auth...`);
console.debug(`[Auth:${mountId}] Path: ${window.location.pathname} Search: ${window.location.search}`);
// Clear any platform-specific cached auth on login page init.
if (typeof window !== 'undefined' && window.location.pathname.startsWith('/login')) {
// Clear platform auth cache on login init only when no local JWT exists yet.
// This avoids wiping freshly-saved desktop tokens during jwt-available re-init.
if (
typeof window !== 'undefined' &&
window.location.pathname.startsWith('/login') &&
!localStorage.getItem('stirling_jwt')
) {
await clearPlatformAuthOnLoginInit();
}
@@ -147,18 +155,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
};
initializeAuth();
initializeAuth(true);
// Listen for jwt-available event (triggered by desktop auth or other sources)
const handleJwtAvailable = () => {
console.log(`[Auth:${mountId}] ════════════════════════════════════`);
console.log(`[Auth:${mountId}] 🔄 JWT available event received`);
console.log(`[Auth:${mountId}] Current state: loading=${loading}, hasSession=${!!session}`);
console.log(`[Auth:${mountId}] Setting loading=true to stabilize auth state`);
setLoading(true); // Prevent unstable renders during auth state transition
setError(null);
console.log(`[Auth:${mountId}] Refreshing session...`);
void initializeAuth();
console.log(`[Auth:${mountId}] Refreshing session in background...`);
void initializeAuth(false);
};
window.addEventListener('jwt-available', handleJwtAvailable);
@@ -52,7 +52,6 @@ describe('SpringAuthClient', () => {
expect(apiClient.get).toHaveBeenCalledWith('/api/v1/auth/me', {
headers: { Authorization: `Bearer ${mockToken}` },
suppressErrorToast: true,
skipAuthRedirect: true,
});
expect(result.data.session).toBeTruthy();
expect(result.data.session?.user).toEqual(mockUser);
@@ -13,11 +13,6 @@ import { BASE_PATH } from '@app/constants/app';
import { type OAuthProvider } from '@app/auth/oauthTypes';
import { resetOAuthState } from '@app/auth/oauthStorage';
import { clearPlatformAuthAfterSignOut } from '@app/extensions/authSessionCleanup';
import {
getPlatformSessionUser,
isDesktopSaaSAuthMode,
refreshPlatformSession,
} from '@app/extensions/platformSessionBridge';
import { startOAuthNavigation } from '@app/extensions/oauthNavigation';
// Helper to extract error message from axios error
@@ -111,26 +106,6 @@ class SpringAuthClient {
this.startSessionMonitoring();
}
private getTokenExpiry(token: string): { expiresIn: number; expiresAt: number } {
try {
const parts = token.split('.');
if (parts.length < 2) {
throw new Error('Token payload missing');
}
const payload = JSON.parse(atob(parts[1]));
const expSeconds = typeof payload?.exp === 'number' ? payload.exp : 0;
const expiresAt = expSeconds > 0 ? expSeconds * 1000 : Date.now() + 3600 * 1000;
const expiresIn = Math.max(0, Math.floor((expiresAt - Date.now()) / 1000));
return { expiresIn, expiresAt };
} catch {
// Fallback for non-JWT or malformed tokens.
const expiresAt = Date.now() + 3600 * 1000;
return { expiresIn: 3600, expiresAt };
}
}
/**
* Helper to get CSRF token from cookie
*/
@@ -152,40 +127,13 @@ class SpringAuthClient {
async getSession(): Promise<{ data: { session: Session | null }; error: AuthError | null }> {
try {
// Get JWT from localStorage
let token = localStorage.getItem('stirling_jwt');
const token = localStorage.getItem('stirling_jwt');
if (!token) {
// console.debug('[SpringAuth] getSession: No JWT in localStorage');
return { data: { session: null }, error: null };
}
if (await isDesktopSaaSAuthMode()) {
let tokenExpiry = this.getTokenExpiry(token);
if (tokenExpiry.expiresIn <= 0) {
const refreshed = await refreshPlatformSession();
if (refreshed) {
token = localStorage.getItem('stirling_jwt') || token;
tokenExpiry = this.getTokenExpiry(token);
}
}
const platformUser = await getPlatformSessionUser();
const session: Session = {
user: {
id: platformUser?.email || platformUser?.username || 'desktop-saas-user',
email: platformUser?.email || '',
username: platformUser?.username || platformUser?.email || 'User',
role: 'USER',
},
access_token: token,
expires_in: tokenExpiry.expiresIn,
expires_at: tokenExpiry.expiresAt,
};
return { data: { session }, error: null };
}
// Verify with backend
// Note: We pass the token explicitly here, overriding the interceptor's default
// console.debug('[SpringAuth] getSession: Verifying JWT with /api/v1/auth/me');
@@ -194,8 +142,6 @@ class SpringAuthClient {
'Authorization': `Bearer ${token}`,
},
suppressErrorToast: true, // Suppress global error handler (we handle errors locally)
// Session bootstrap should not trigger global 401 refresh/redirect loops.
skipAuthRedirect: true,
});
// console.debug('[SpringAuth] /me response status:', response.status);
@@ -203,12 +149,11 @@ class SpringAuthClient {
// console.debug('[SpringAuth] /me response data:', data);
// Create session object
const tokenExpiry = this.getTokenExpiry(token);
const session: Session = {
user: data.user,
access_token: token,
expires_in: tokenExpiry.expiresIn,
expires_at: tokenExpiry.expiresAt,
expires_in: 3600,
expires_at: Date.now() + 3600 * 1000,
};
// console.debug('[SpringAuth] getSession: Session retrieved successfully');
@@ -437,28 +382,6 @@ class SpringAuthClient {
*/
async refreshSession(): Promise<{ data: { session: Session | null }; error: AuthError | null }> {
try {
if (await isDesktopSaaSAuthMode()) {
const refreshed = await refreshPlatformSession();
if (!refreshed) {
localStorage.removeItem('stirling_jwt');
return {
data: { session: null },
error: { message: 'Token refresh failed - please log in again' },
};
}
const { data, error } = await this.getSession();
if (error || !data.session) {
return {
data: { session: null },
error: error || { message: 'Token refresh failed - please log in again' },
};
}
this.notifyListeners('TOKEN_REFRESHED', data.session);
return { data, error: null };
}
const response = await apiClient.post('/api/v1/auth/refresh', null, {
headers: {
'X-XSRF-TOKEN': this.getCsrfToken() || '',
@@ -22,6 +22,9 @@ interface SecuritySettingsData {
enableKeyRotation?: boolean;
enableKeyCleanup?: boolean;
keyRetentionDays?: number;
tokenExpiryMinutes?: number;
allowedClockSkewSeconds?: number;
refreshGraceMinutes?: number;
secureCookie?: boolean;
};
audit?: {
@@ -132,6 +135,9 @@ export default function AdminSecuritySection() {
'security.jwt.enableKeyRotation': securitySettings.jwt?.enableKeyRotation,
'security.jwt.enableKeyCleanup': securitySettings.jwt?.enableKeyCleanup,
'security.jwt.keyRetentionDays': securitySettings.jwt?.keyRetentionDays,
'security.jwt.tokenExpiryMinutes': securitySettings.jwt?.tokenExpiryMinutes,
'security.jwt.allowedClockSkewSeconds': securitySettings.jwt?.allowedClockSkewSeconds,
'security.jwt.refreshGraceMinutes': securitySettings.jwt?.refreshGraceMinutes,
'security.jwt.secureCookie': securitySettings.jwt?.secureCookie,
// Premium audit settings
'premium.enterpriseFeatures.audit.enabled': audit?.enabled,
@@ -400,6 +406,60 @@ export default function AdminSecuritySection() {
/>
</div>
<div>
<NumberInput
name="jwt_tokenExpiryMinutes"
label={
<Group component="span" gap="xs">
<span>{t('admin.settings.security.jwt.tokenExpiryMinutes.label', 'Token Expiry (minutes)')}</span>
<PendingBadge show={isFieldPending('jwt.tokenExpiryMinutes')} />
</Group>
}
description={t('admin.settings.security.jwt.tokenExpiryMinutes.description', 'Access token lifetime in minutes')}
value={settings?.jwt?.tokenExpiryMinutes ?? 1440}
onChange={(value) => setSettings({ ...settings, jwt: { ...settings?.jwt, tokenExpiryMinutes: Number(value) } })}
min={1}
max={10080}
disabled={!loginEnabled}
/>
</div>
<div>
<NumberInput
name="jwt_allowedClockSkewSeconds"
label={
<Group component="span" gap="xs">
<span>{t('admin.settings.security.jwt.allowedClockSkewSeconds.label', 'Allowed Clock Skew (seconds)')}</span>
<PendingBadge show={isFieldPending('jwt.allowedClockSkewSeconds')} />
</Group>
}
description={t('admin.settings.security.jwt.allowedClockSkewSeconds.description', 'Tolerance for client/server clock drift during token validation')}
value={settings?.jwt?.allowedClockSkewSeconds ?? 60}
onChange={(value) => setSettings({ ...settings, jwt: { ...settings?.jwt, allowedClockSkewSeconds: Number(value) } })}
min={0}
max={300}
disabled={!loginEnabled}
/>
</div>
<div>
<NumberInput
name="jwt_refreshGraceMinutes"
label={
<Group component="span" gap="xs">
<span>{t('admin.settings.security.jwt.refreshGraceMinutes.label', 'Refresh Grace (minutes)')}</span>
<PendingBadge show={isFieldPending('jwt.refreshGraceMinutes')} />
</Group>
}
description={t('admin.settings.security.jwt.refreshGraceMinutes.description', 'Allow refresh with an expired access token only within this grace period')}
value={settings?.jwt?.refreshGraceMinutes ?? 15}
onChange={(value) => setSettings({ ...settings, jwt: { ...settings?.jwt, refreshGraceMinutes: Number(value) } })}
min={0}
max={1440}
disabled={!loginEnabled}
/>
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<Text fw={500} size="sm">{t('admin.settings.security.jwt.secureCookie.label', 'Secure Cookie')}</Text>
@@ -1,25 +0,0 @@
export interface PlatformSessionUser {
username: string;
email?: string;
}
/**
* Proprietary/web default: no desktop SaaS auth bridge.
*/
export async function isDesktopSaaSAuthMode(): Promise<boolean> {
return false;
}
/**
* Proprietary/web default: no platform user store.
*/
export async function getPlatformSessionUser(): Promise<PlatformSessionUser | null> {
return null;
}
/**
* Proprietary/web default: no platform refresh path.
*/
export async function refreshPlatformSession(): Promise<boolean> {
return false;
}