Compare commits

..
Author SHA1 Message Date
ConnorYohandGitHub 170f317f11 Merge branch 'main' into worktree-guest-signing-support 2026-03-30 11:04:28 +01:00
Connor Yoh 5f553ece11 feat(signing): add external/guest user signing support
Allow document owners to invite external users (no Stirling-PDF account)
to sign documents via a one-time share link.

Backend:
- GuestCertificateService: generates ephemeral PKCS12 keystores keyed by
  email, with rfc822Name SAN for industry-traceable digital signatures;
  uses emailProtection EKU, cryptographically random serial numbers, and
  HMAC-SHA256 derived passwords
- SigningFinalizationService: handles GUEST_CERT case in buildKeystore()
  and getKeystorePassword()
- WorkflowParticipantController: defaults certType to GUEST_CERT for
  unregistered participants, captures hashed-IP audit trail on submission,
  skips password encryption for GUEST_CERT paths
- WorkflowSessionService: sends signing invitation email to guest
  participants on session creation; redacts email PII in logs
- EmailService: adds sendSigningInvitationEmail() with HTML-escaped
  user-supplied values and javascript: URL guard to prevent XSS

Frontend:
- GuestSignPage: new token-gated route /sign/:token outside AppProviders;
  full page-state machine (loading/ready/expired/signed/declined/error)
- GuestCertificateChooser: auto-generated cert vs upload P12 chooser
- SelectParticipantsStep: refactored to support registered + external
  (email) participants via tabbed UI with validation
- AddParticipantsFlow: same external email tab added for mid-session adds
- CreateSessionFlow/SignPopout: thread new Participant[] shape through
  to split userIds and emails on submit
- App.tsx: /sign/:token route with minimal GuestSigningProviders (no auth)
- i18n: [guestSigning] keys added to en-GB/translation.toml

Tests:
- GuestCertificateServiceTest: keystore generation, SAN, deterministic passwords
- WorkflowParticipantControllerTest: GUEST_CERT defaulting, audit trail,
  token guards, encrypt() not called for guest cert
- EmailServiceTest: invitation email, HTML injection safety, JS URL guard
- GuestSignPage.test.tsx: 9 vitest unit tests (all page states + submit)
- SelectParticipantsStep.test.tsx: 15 vitest unit tests
- GuestSigningE2E.spec.ts: 19 Playwright E2E tests (route-mocked, no backend)
- playwright.config.ts: fix testDir to src/core/tests, use port 5174
2026-03-27 17:51:43 +00:00
116 changed files with 5215 additions and 4491 deletions
+2 -4
View File
@@ -236,12 +236,10 @@ jobs:
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
run: cd frontend && npm ci
- name: Generate icons
run: cd frontend && node scripts/generate-icons.js
- name: Install Playwright (chromium only)
run: cd frontend && npx playwright install chromium --with-deps
- name: Run E2E tests (chromium)
run: cd frontend && npx playwright test --project=chromium
run: cd frontend && npx playwright test src/core/tests/certValidation --project=chromium
- name: Upload Playwright report
if: always()
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
@@ -513,7 +511,7 @@ jobs:
echo "base_image=stirling-pdf-base:pr-test" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64" >> $GITHUB_OUTPUT
else
echo "base_image=stirlingtools/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "base_image=ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf-base:latest" >> $GITHUB_OUTPUT
echo "platforms=linux/amd64,linux/arm64/v8" >> $GITHUB_OUTPUT
fi
+1 -4
View File
@@ -35,14 +35,11 @@ jobs:
- name: Install frontend dependencies
run: cd frontend && npm ci
- name: Generate icons
run: cd frontend && node scripts/generate-icons.js
- name: Install all Playwright browsers
run: cd frontend && npx playwright install --with-deps
- name: Run E2E tests (all browsers)
run: cd frontend && npx playwright test
run: cd frontend && npx playwright test src/core/tests/certValidation
- name: Upload Playwright report
if: always()
@@ -112,6 +112,8 @@ public class FileMonitor {
All files observed changes in the last iteration will be considered as staging files.
If those files are not modified in current iteration, they will be considered as ready for processing.
*/
stagingFiles = new HashSet<>(newlyDiscoveredFiles);
readyForProcessingFiles.clear();
if (path2KeyMapping.isEmpty()) {
log.warn("Not monitoring any directories; attempting to re-register root paths.");
@@ -127,17 +129,8 @@ public class FileMonitor {
}
}
// Skip expensive collection work when there is nothing to track
WatchKey firstKey = watchService.poll();
if (firstKey == null && newlyDiscoveredFiles.isEmpty() && readyForProcessingFiles.isEmpty()) {
return;
}
stagingFiles = new HashSet<>(newlyDiscoveredFiles);
readyForProcessingFiles.clear();
WatchKey key = firstKey;
while (key != null) {
WatchKey key;
while ((key = watchService.poll()) != null) {
final Path watchingDir = (Path) key.watchable();
key.pollEvents()
.forEach(
@@ -174,7 +167,6 @@ public class FileMonitor {
if (!isKeyValid) { // key is invalid when the directory itself is no longer exists
path2KeyMapping.remove((Path) key.watchable());
}
key = watchService.poll();
}
readyForProcessingFiles.addAll(stagingFiles);
}
@@ -1,22 +1,19 @@
package stirling.software.SPDF.controller.api.misc;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -24,7 +21,6 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
import com.google.zxing.*;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
import io.github.pixee.security.Filenames;
@@ -39,6 +35,7 @@ import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ApplicationContextProvider;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
@@ -51,219 +48,61 @@ import stirling.software.common.util.WebResponseUtils;
public class AutoSplitPdfController {
private static final Set<String> VALID_QR_CONTENTS =
Set.of(
"https://github.com/Stirling-Tools/Stirling-PDF",
"https://github.com/Frooodle/Stirling-PDF",
"https://stirlingpdf.com");
private static final int MAX_IMAGES_FOR_DIRECT_EXTRACTION = 3;
// 150 DPI is sufficient for QR code detection — higher wastes memory and CPU
private static final int QR_DETECTION_DPI = 150;
// Max total pixels before we downscale to avoid OOM on getRGB() allocation
private static final long MAX_IMAGE_PIXELS = 100_000_000L; // ~10000x10000
// Number of evenly-spaced pixel samples used for the blank image check
private static final int BLANK_CHECK_SAMPLES = 20;
private static final Map<DecodeHintType, Object> DECODE_HINTS;
static {
DECODE_HINTS = new EnumMap<>(DecodeHintType.class);
DECODE_HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
DECODE_HINTS.put(DecodeHintType.ALSO_INVERTED, Boolean.TRUE);
DECODE_HINTS.put(DecodeHintType.POSSIBLE_FORMATS, List.of(BarcodeFormat.QR_CODE));
}
new HashSet<>(
Set.of(
"https://github.com/Stirling-Tools/Stirling-PDF",
"https://github.com/Frooodle/Stirling-PDF",
"https://stirlingpdf.com"));
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private final ApplicationProperties applicationProperties;
/**
* Downscale an image if it exceeds the maximum pixel count. Scales uniformly based on the
* pixel-count ratio so both portrait and landscape images are handled correctly.
*/
private static BufferedImage downscaleIfNeeded(BufferedImage image) {
long totalPixels = (long) image.getWidth() * image.getHeight();
if (totalPixels <= MAX_IMAGE_PIXELS) {
return image;
}
double scale = Math.sqrt((double) MAX_IMAGE_PIXELS / totalPixels);
int newWidth = Math.max(1, (int) (image.getWidth() * scale));
int newHeight = Math.max(1, (int) (image.getHeight() * scale));
log.debug(
"Downscaling image from {}x{} to {}x{} for QR detection",
image.getWidth(),
image.getHeight(),
newWidth,
newHeight);
BufferedImage scaled = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
return scaled;
}
/**
* Quick check whether an image appears to be blank (single solid colour). Samples pixels at
* evenly-spaced positions — if all samples match the first pixel the image is almost certainly
* blank (e.g. a masked image that returned solid white).
*/
private static boolean isBlankImage(int[] pixels) {
if (pixels.length == 0) return true;
int first = pixels[0];
int step = Math.max(1, pixels.length / BLANK_CHECK_SAMPLES);
for (int i = step; i < pixels.length; i += step) {
if (pixels[i] != first) {
return false;
}
}
return true;
}
/**
* Try to decode a QR code from pre-extracted RGB pixel data using multiple binarization
* strategies. Returns the decoded text or null.
*
* <p>Strategy 1: HybridBinarizer — good for variable brightness (digital PDFs).
*
* <p>Strategy 2: GlobalHistogramBinarizer — better for scanned/noisy images with uniform
* lighting, and for QR codes with embedded logos that confuse the hybrid approach.
*/
private static String tryDecodeQR(int[] pixels, int width, int height) {
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
MultiFormatReader reader = new MultiFormatReader();
// Strategy 1: HybridBinarizer — good for variable brightness (digital PDFs)
try {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap, DECODE_HINTS);
log.debug("QR detected via HybridBinarizer: '{}'", result.getText());
return result.getText();
} catch (NotFoundException e) {
// continue
}
// Strategy 2: GlobalHistogramBinarizer — better for scanned/noisy images
try {
BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Result result = reader.decode(bitmap, DECODE_HINTS);
log.debug("QR detected via GlobalHistogramBinarizer: '{}'", result.getText());
return result.getText();
} catch (NotFoundException e) {
return null;
}
}
/**
* Attempt to decode a QR code from a BufferedImage. Handles downscaling for oversized images
* and skips blank images early.
*/
private static String decodeQRCode(BufferedImage bufferedImage) {
bufferedImage = downscaleIfNeeded(bufferedImage);
LuminanceSource source;
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
int[] pixels = new int[width * height];
bufferedImage.getRGB(0, 0, width, height, pixels, 0, width);
// Skip blank images early (e.g. masked images that decode to solid white)
if (isBlankImage(pixels)) {
log.debug("Skipping blank {}x{} image", width, height);
return null;
}
return tryDecodeQR(pixels, width, height);
}
/** Count the number of images embedded in a page's resources. */
private static int countPageImages(PDPage page) {
if (page.getResources() == null || page.getResources().getXObjectNames() == null) {
return 0;
}
int count = 0;
for (COSName name : page.getResources().getXObjectNames()) {
if (page.getResources().isImageXObject(name)) {
count++;
if (bufferedImage.getRaster().getDataBuffer() instanceof DataBufferByte dataBufferByte) {
byte[] pixels = dataBufferByte.getData();
source =
new PlanarYUVLuminanceSource(
pixels,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
0,
0,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
false);
} else if (bufferedImage.getRaster().getDataBuffer()
instanceof DataBufferInt dataBufferInt) {
int[] pixels = dataBufferInt.getData();
byte[] newPixels = new byte[pixels.length];
for (int i = 0; i < pixels.length; i++) {
newPixels[i] = (byte) (pixels[i] & 0xff);
}
source =
new PlanarYUVLuminanceSource(
newPixels,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
0,
0,
bufferedImage.getWidth(),
bufferedImage.getHeight(),
false);
} else {
throw new IllegalArgumentException(
"BufferedImage must have 8-bit gray scale, 24-bit RGB, 32-bit ARGB (packed"
+ " int), byte gray, or 3-byte/4-byte RGB image data");
}
return count;
}
/**
* Extract images directly from a page's resources and check each for a QR code. Returns the QR
* code text if found, null otherwise.
*/
private static String checkPageImagesDirect(PDPage page) throws IOException {
if (page.getResources() == null || page.getResources().getXObjectNames() == null) {
return null;
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
Result result = new MultiFormatReader().decode(bitmap);
return result.getText();
} catch (NotFoundException e) {
return null; // there is no QR code in the image
}
for (COSName name : page.getResources().getXObjectNames()) {
if (!page.getResources().isImageXObject(name)) {
continue;
}
PDImageXObject imageObject = (PDImageXObject) page.getResources().getXObject(name);
BufferedImage image;
try {
image = imageObject.getImage();
} catch (OutOfMemoryError e) {
log.warn(
"Skipping oversized embedded image '{}' ({}x{}) - out of memory",
name.getName(),
imageObject.getWidth(),
imageObject.getHeight());
continue;
}
String result = decodeQRCode(image);
if (result != null) {
return result;
}
}
return null;
}
/**
* Render the full page to an image and scan it for a QR code. Tries a low DPI first (fast, low
* memory) and only retries at the system's maxDPI if detection fails. The first rendered image
* is released before the retry to allow GC to reclaim it.
*/
private String checkPageByRendering(PDFRenderer pdfRenderer, int pageNum) throws IOException {
log.debug("Rendering page {} at {} DPI for QR detection", pageNum + 1, QR_DETECTION_DPI);
BufferedImage bim =
ExceptionUtils.handleOomRendering(
pageNum + 1,
QR_DETECTION_DPI,
() -> pdfRenderer.renderImageWithDPI(pageNum, QR_DETECTION_DPI));
String result = decodeQRCode(bim);
bim = null; // allow GC before potential high-DPI retry
if (result == null) {
int maxDpi = getSystemMaxDpi();
if (maxDpi > QR_DETECTION_DPI) {
log.debug(
"Retrying page {} at {} DPI (low-DPI detection failed)",
pageNum + 1,
maxDpi);
BufferedImage highRes =
ExceptionUtils.handleOomRendering(
pageNum + 1,
maxDpi,
() -> pdfRenderer.renderImageWithDPI(pageNum, maxDpi));
result = decodeQRCode(highRes);
}
}
return result;
}
private int getSystemMaxDpi() {
if (applicationProperties != null && applicationProperties.getSystem() != null) {
return applicationProperties.getSystem().getMaxDPI();
}
return QR_DETECTION_DPI;
}
@AutoJobPostMapping(value = "/auto-split-pdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@@ -272,56 +111,42 @@ public class AutoSplitPdfController {
summary = "Auto split PDF pages into separate documents",
description =
"This endpoint accepts a PDF file, scans each page for a specific QR code, and"
+ " splits the document at the QR code boundaries. The output is a zip"
+ " file containing each separate PDF document. Input:PDF Output:ZIP-PDF"
+ " splits the document at the QR code boundaries. The output is a zip file"
+ " containing each separate PDF document. Input:PDF Output:ZIP-PDF"
+ " Type:SISO")
public ResponseEntity<byte[]> autoSplitPdf(@ModelAttribute AutoSplitPdfRequest request)
throws IOException {
MultipartFile file = request.getFileInput();
boolean duplexMode = Boolean.TRUE.equals(request.getDuplexMode());
log.info(
"Auto-split starting: filename='{}', size={} bytes, duplexMode={}",
file.getOriginalFilename(),
file.getSize(),
duplexMode);
List<PDDocument> splitDocuments = new ArrayList<>();
try (TempFile outputTempFile = new TempFile(tempFileManager, ".zip");
PDDocument document = pdfDocumentFactory.load(file.getInputStream())) {
int totalPages = document.getNumberOfPages();
log.info("PDF loaded, totalPages={}", totalPages);
PDFRenderer pdfRenderer = new PDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (int page = 0; page < totalPages; ++page) {
PDPage pdPage = document.getPage(page);
int imageCount = countPageImages(pdPage);
for (int page = 0; page < document.getNumberOfPages(); ++page) {
BufferedImage bim;
String qrResult;
if (imageCount > 0 && imageCount <= MAX_IMAGES_FOR_DIRECT_EXTRACTION) {
// Try extracting images directly from the PDF (faster, avoids rendering)
qrResult = checkPageImagesDirect(pdPage);
if (qrResult == null) {
// Fall back to rendering — the image may use masking/compositing
// that getImage() doesn't resolve, or the QR may be vector-drawn
qrResult = checkPageByRendering(pdfRenderer, page);
}
} else {
// Too many images or no images — render the full page
qrResult = checkPageByRendering(pdfRenderer, page);
// Use global maximum DPI setting, fallback to 300 if not set
int renderDpi = 150; // Default fallback
ApplicationProperties properties =
ApplicationContextProvider.getBean(ApplicationProperties.class);
if (properties != null && properties.getSystem() != null) {
renderDpi = properties.getSystem().getMaxDPI();
}
final int dpi = renderDpi;
final int pageNum = page;
boolean isValidQrCode = qrResult != null && VALID_QR_CONTENTS.contains(qrResult);
if (isValidQrCode) {
log.info(
"Page {}/{} contains QR divider ('{}')",
page + 1,
totalPages,
qrResult);
}
bim =
ExceptionUtils.handleOomRendering(
pageNum + 1,
dpi,
() -> pdfRenderer.renderImageWithDPI(pageNum, dpi));
String result = decodeQRCode(bim);
boolean isValidQrCode = VALID_QR_CONTENTS.contains(result);
log.debug("detected qr code {}, code is vale={}", result, isValidQrCode);
if (isValidQrCode && page != 0) {
splitDocuments.add(new PDDocument());
}
@@ -334,25 +159,32 @@ public class AutoSplitPdfController {
splitDocuments.add(firstDocument);
}
// If duplexMode is true and current page is a divider, then skip next page
if (duplexMode && isValidQrCode) {
page++; // skip back of divider page
page++;
}
}
// Remove split documents that have no pages
splitDocuments.removeIf(pdDocument -> pdDocument.getNumberOfPages() == 0);
log.info("Split complete, {} output documents", splitDocuments.size());
String filename =
GeneralUtils.removeExtension(
Filenames.toSimpleFileName(file.getOriginalFilename()));
// Stream split documents directly into zip — avoids holding all PDFs in memory
try (OutputStream fileOut = Files.newOutputStream(outputTempFile.getPath());
ZipOutputStream zipOut = new ZipOutputStream(fileOut)) {
try (ZipOutputStream zipOut =
new ZipOutputStream(Files.newOutputStream(outputTempFile.getPath()))) {
for (int i = 0; i < splitDocuments.size(); i++) {
String fileName = filename + "_" + (i + 1) + ".pdf";
zipOut.putNextEntry(new ZipEntry(fileName));
splitDocuments.get(i).save(zipOut);
PDDocument splitDocument = splitDocuments.get(i);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
splitDocument.save(baos);
byte[] pdf = baos.toByteArray();
ZipEntry pdfEntry = new ZipEntry(fileName);
zipOut.putNextEntry(pdfEntry);
zipOut.write(pdf);
zipOut.closeEntry();
}
}
@@ -365,6 +197,7 @@ public class AutoSplitPdfController {
log.error("Error in auto split", e);
throw e;
} finally {
// Clean up split documents
for (PDDocument splitDoc : splitDocuments) {
try {
splitDoc.close();
@@ -47,7 +47,6 @@ import stirling.software.proprietary.security.model.dto.AdminUserSummary;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.MfaService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -72,7 +71,6 @@ public class ProprietaryUIDataController {
private final UserLicenseSettingsService licenseSettingsService;
private final PersistentAuditEventRepository auditRepository;
private final MfaService mfaService;
private final LoginAttemptService loginAttemptService;
public ProprietaryUIDataController(
ApplicationProperties applicationProperties,
@@ -86,8 +84,7 @@ public class ProprietaryUIDataController {
@Qualifier("runningEE") boolean runningEE,
UserLicenseSettingsService licenseSettingsService,
PersistentAuditEventRepository auditRepository,
MfaService mfaService,
LoginAttemptService loginAttemptService) {
MfaService mfaService) {
this.applicationProperties = applicationProperties;
this.auditConfig = auditConfig;
this.sessionPersistentRegistry = sessionPersistentRegistry;
@@ -100,7 +97,6 @@ public class ProprietaryUIDataController {
this.licenseSettingsService = licenseSettingsService;
this.auditRepository = auditRepository;
this.mfaService = mfaService;
this.loginAttemptService = loginAttemptService;
}
/**
@@ -391,7 +387,6 @@ public class ProprietaryUIDataController {
data.setPremiumEnabled(premiumEnabled);
data.setMailEnabled(applicationProperties.getMail().isEnabled());
data.setUserSettings(userSettings);
data.setLockedUsers(loginAttemptService.getAllBlockedUsers());
return ResponseEntity.ok(data);
}
@@ -610,7 +605,6 @@ public class ProprietaryUIDataController {
private boolean premiumEnabled;
private boolean mailEnabled;
private Map<String, Map<String, String>> userSettings;
private List<String> lockedUsers;
}
@Data
@@ -159,13 +159,10 @@ public class SecurityConfiguration {
firewall.setAllowedHeaderValues(
headerValue -> headerValue != null && allowedChars.matcher(headerValue).matches());
// Allow non-ASCII characters and newlines in parameter values.
Pattern allowedParamChars =
Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]\\r\\n]*");
// Apply the same rules to parameter values for consistency.
firewall.setAllowedParameterValues(
parameterValue ->
parameterValue != null
&& allowedParamChars.matcher(parameterValue).matches());
parameterValue != null && allowedChars.matcher(parameterValue).matches());
return firewall;
}
@@ -48,7 +48,6 @@ import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.SaveUserRequest;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
@@ -68,7 +67,6 @@ public class UserController {
private final UserRepository userRepository;
private final Optional<EmailService> emailService;
private final UserLicenseSettingsService licenseSettingsService;
private final LoginAttemptService loginAttemptService;
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/register")
@@ -777,14 +775,6 @@ public class UserController {
Map.of("message", "User " + (enabled ? "enabled" : "disabled") + " successfully"));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/unlockUser/{username}")
@Audited(type = AuditEventType.SETTINGS_CHANGED, level = AuditLevel.BASIC)
public ResponseEntity<?> unlockUser(@PathVariable("username") String username) {
loginAttemptService.resetAttempts(username);
return ResponseEntity.ok(Map.of("message", "User account unlocked successfully"));
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/deleteUser/{username}")
@Audited(type = AuditEventType.USER_PROFILE_UPDATE, level = AuditLevel.BASIC)
@@ -6,6 +6,7 @@ import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
@@ -260,6 +261,111 @@ public class EmailService {
sendPlainEmail(to, subject, body, true);
}
/**
* Sends a document signing invitation to an external/guest user.
*
* @param to the recipient email address
* @param ownerName the display name of the session owner
* @param documentName the name of the document to be signed
* @param signingUrl the full URL of the guest signing page
* @param expiresAt human-readable expiry date/time string
* @param message optional personal message from the owner (may be null)
* @throws MessagingException if sending fails
*/
@Async
public void sendSigningInvitationEmail(
String to,
String ownerName,
String documentName,
String signingUrl,
String expiresAt,
String message)
throws MessagingException {
// Escape all user-supplied values before embedding in HTML
String safeOwner = HtmlUtils.htmlEscape(ownerName != null ? ownerName : "");
String safeDoc = HtmlUtils.htmlEscape(documentName != null ? documentName : "");
// Only allow http/https URLs in the signing link to prevent javascript: injection
String safeUrl =
(signingUrl != null
&& (signingUrl.startsWith("https://")
|| signingUrl.startsWith("http://")))
? signingUrl
: "#";
String safeUrlText = HtmlUtils.htmlEscape(safeUrl);
String subject = "Please sign: " + (documentName != null ? documentName : "");
String messageSection =
(message != null && !message.isBlank())
? """
<div style="background-color: #f8f9fa; border-left: 4px solid #6c757d; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; font-style: italic; color: #555;">"%s"</p>
</div>
"""
.formatted(HtmlUtils.htmlEscape(message))
: "";
String expirySection =
(expiresAt != null && !expiresAt.isBlank())
? """
<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; color: #856404; font-size: 14px;"><strong>&#9888; Important:</strong> This signing link will expire on %s.</p>
</div>
"""
.formatted(HtmlUtils.htmlEscape(expiresAt))
: "";
String body =
"""
<html><body style="margin: 0; padding: 0;">
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
<!-- Logo -->
<div style="text-align: center; padding: 20px; background-color: #222;">
<img src="https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/main/docs/stirling-transparent.svg" alt="Stirling PDF" style="max-height: 60px;">
</div>
<!-- Content -->
<div style="padding: 30px; color: #333;">
<h2 style="color: #222; margin-top: 0;">You have been asked to sign a document</h2>
<p>Hi there,</p>
<p><strong>%s</strong> has requested your signature on:</p>
<!-- Document Name Box -->
<div style="background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; font-size: 16px;"><strong>&#128196; %s</strong></p>
</div>
%s
<!-- CTA Button -->
<div style="text-align: center; margin: 30px 0;">
<a href="%s" style="display: inline-block; background-color: #007bff; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 5px; font-weight: bold;">Review and Sign Document</a>
</div>
<p style="font-size: 14px; color: #666;">Or copy and paste this link in your browser:</p>
<div style="background-color: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 4px; word-break: break-all; font-size: 13px; color: #555;">
%s
</div>
%s
<p style="font-size: 13px; color: #888;">No account is required. Click the button above to review the document and apply your signature.</p>
<p>If you did not expect this request, you can safely ignore this email.</p>
<p style="margin-bottom: 0;">&#8212; The Stirling PDF Team</p>
</div>
<!-- Footer -->
<div style="text-align: center; padding: 15px; font-size: 12px; color: #777; background-color: #f0f0f0;">
&copy; 2025 Stirling PDF. All rights reserved.
</div>
</div>
</div>
</body></html>
"""
.formatted(
safeOwner,
safeDoc,
messageSection,
safeUrl,
safeUrlText,
expirySection);
sendPlainEmail(to, subject, body, true);
}
@Async
public void sendPasswordChangedNotification(
String to, String username, String newPassword, String loginUrl)
@@ -1,11 +1,8 @@
package stirling.software.proprietary.security.service;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
@@ -82,28 +79,6 @@ public class LoginAttemptService {
return attemptCounter.getAttemptCount() >= MAX_ATTEMPT;
}
public void resetAttempts(String key) {
if (key == null || key.trim().isEmpty()) {
return;
}
String normalizedKey = key.toLowerCase(Locale.ROOT);
attemptsCache.remove(normalizedKey);
}
public boolean isBlockingEnabled() {
return isBlockedEnabled;
}
public List<String> getAllBlockedUsers() {
if (!isBlockedEnabled) {
return List.of();
}
return attemptsCache.entrySet().stream()
.filter(entry -> entry.getValue().getAttemptCount() >= MAX_ATTEMPT)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
public int getRemainingAttempts(String key) {
if (!isBlockedEnabled || key == null || key.trim().isEmpty()) {
// Arbitrarily high number if tracking is disabled
@@ -2,8 +2,11 @@ package stirling.software.proprietary.workflow.controller;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@@ -24,6 +27,7 @@ import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
@@ -134,7 +138,7 @@ public class WorkflowParticipantController {
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ParticipantResponse> submitSignature(
@ModelAttribute SignatureSubmissionRequest request) {
@ModelAttribute SignatureSubmissionRequest request, HttpServletRequest httpRequest) {
workflowSessionService.ensureSigningEnabled();
@@ -169,7 +173,8 @@ public class WorkflowParticipantController {
try {
// Build metadata map with certificate and wet signature data
Map<String, Object> metadata = buildSubmissionMetadata(request);
Map<String, Object> metadata =
buildSubmissionMetadata(request, participant, httpRequest);
participant.setParticipantMetadata(metadata);
// Update status to SIGNED
@@ -369,15 +374,27 @@ public class WorkflowParticipantController {
}
/**
* Builds metadata map from signature submission request. Includes certificate submission and
* wet signature data.
* Builds metadata map from signature submission request. Includes certificate submission, wet
* signature data, and an audit trail entry for compliance traceability.
*/
private Map<String, Object> buildSubmissionMetadata(SignatureSubmissionRequest request)
private Map<String, Object> buildSubmissionMetadata(
SignatureSubmissionRequest request,
WorkflowParticipant participant,
HttpServletRequest httpRequest)
throws IOException {
Map<String, Object> metadata = new HashMap<>();
// Validate certificate before storing — throws 400 if invalid, expired, or wrong password
if (request.getCertType() != null && !"SERVER".equalsIgnoreCase(request.getCertType())) {
// Default to GUEST_CERT for external (non-registered) participants that did not
// supply their own certificate.
String effectiveCertType = request.getCertType();
if (effectiveCertType == null && participant.getUser() == null) {
effectiveCertType = "GUEST_CERT";
}
// Validate uploaded certificate before storing — skip for GUEST_CERT (no upload)
if (effectiveCertType != null
&& !"SERVER".equalsIgnoreCase(effectiveCertType)
&& !"GUEST_CERT".equalsIgnoreCase(effectiveCertType)) {
byte[] keystoreBytes = null;
if (request.getP12File() != null && !request.getP12File().isEmpty()) {
keystoreBytes = request.getP12File().getBytes();
@@ -386,16 +403,20 @@ public class WorkflowParticipantController {
}
if (keystoreBytes != null) {
certificateSubmissionValidator.validateAndExtractInfo(
keystoreBytes, request.getCertType(), request.getPassword());
keystoreBytes, effectiveCertType, request.getPassword());
}
}
// Add certificate submission if provided
if (request.getCertType() != null) {
// Add certificate submission if provided (or defaulted)
if (effectiveCertType != null) {
Map<String, Object> certSubmission = new HashMap<>();
certSubmission.put("certType", request.getCertType());
certSubmission.put(
"password", metadataEncryptionService.encrypt(request.getPassword()));
certSubmission.put("certType", effectiveCertType);
// GUEST_CERT passwords are derived at finalization time; no password to store
String encryptedPassword =
"GUEST_CERT".equalsIgnoreCase(effectiveCertType)
? null
: metadataEncryptionService.encrypt(request.getPassword());
certSubmission.put("password", encryptedPassword);
certSubmission.put("showSignature", request.getShowSignature());
certSubmission.put("pageNumber", request.getPageNumber());
certSubmission.put("location", request.getLocation());
@@ -437,6 +458,31 @@ public class WorkflowParticipantController {
metadata.put("wetSignatures", wetSigs);
}
// Audit trail for compliance traceability (IP is hashed, not stored raw)
Map<String, Object> auditTrail = new HashMap<>();
auditTrail.put("ipHash", hashIp(httpRequest.getRemoteAddr()));
String userAgent = httpRequest.getHeader("User-Agent");
auditTrail.put(
"userAgent",
userAgent != null && userAgent.length() > 500
? userAgent.substring(0, 500)
: userAgent);
auditTrail.put("submittedAt", Instant.now().toString());
auditTrail.put("email", participant.getEmail());
metadata.put("auditTrail", auditTrail);
return metadata;
}
/** Returns a SHA-256 Base64-encoded digest of an IP address for privacy-safe audit logging. */
private String hashIp(String ip) {
if (ip == null) return null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(ip.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
} catch (Exception e) {
return null;
}
}
}
@@ -0,0 +1,187 @@
package stirling.software.proprietary.workflow.service;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
/**
* Generates ephemeral (in-memory) PKCS12 keystores for guest/external signers. The generated
* certificate includes the signer's email address as a Subject Alternative Name (rfc822Name),
* providing industry-standard traceability. Guest keystores are never persisted to the database.
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class GuestCertificateService {
private static final String KEYSTORE_ALIAS = "stirling-pdf-guest-cert";
private static final int VALIDITY_DAYS = 365;
private final ApplicationProperties applicationProperties;
static {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
/**
* Generates a new in-memory PKCS12 keystore for a guest signer identified by email. The X.509
* certificate includes: - CN = sanitized email (no special chars) - O = Stirling-PDF Guest -
* SAN rfc822Name = raw email (industry-standard signer identity field)
*
* @param email the guest signer's email address
* @return an in-memory PKCS12 KeyStore ready for use in PDF signing
*/
public KeyStore generateGuestKeyStore(String email) throws Exception {
log.debug(
"Generating guest certificate for external signer (domain: {})",
email.contains("@") ? email.substring(email.indexOf('@')) : "<no-domain>");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(2048, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Sanitize email for use in DN (remove chars that break X.500 parsing)
String safeCn = email.replaceAll("[,=+<>#;\"\\\\]", "_");
X500Name subject = new X500Name("CN=" + safeCn + ", O=Stirling-PDF Guest, C=US");
BigInteger serialNumber = new BigInteger(64, new SecureRandom());
Date notBefore = new Date();
Date notAfter =
new Date(notBefore.getTime() + ((long) VALIDITY_DAYS * 24 * 60 * 60 * 1000));
JcaX509v3CertificateBuilder certBuilder =
new JcaX509v3CertificateBuilder(
subject, serialNumber, notBefore, notAfter, subject, keyPair.getPublic());
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
// End-entity certificate, not a CA
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
// Key usage for PDF digital signatures
certBuilder.addExtension(
Extension.keyUsage,
true,
new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation));
// Extended key usage: emailProtection is the correct OID for email-identified signers
certBuilder.addExtension(
Extension.extendedKeyUsage,
false,
new ExtendedKeyUsage(KeyPurposeId.id_kp_emailProtection));
// Subject Key Identifier
certBuilder.addExtension(
Extension.subjectKeyIdentifier,
false,
extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
// Authority Key Identifier (self-signed)
certBuilder.addExtension(
Extension.authorityKeyIdentifier,
false,
extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
// Subject Alternative Name: rfc822Name = email (industry-standard signer identity)
GeneralName emailSan = new GeneralName(GeneralName.rfc822Name, email);
GeneralNames subjectAltName = new GeneralNames(emailSan);
certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
// Sign the certificate
ContentSigner signer =
new JcaContentSignerBuilder("SHA256WithRSA")
.setProvider("BC")
.build(keyPair.getPrivate());
X509CertificateHolder certHolder = certBuilder.build(signer);
X509Certificate cert =
new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
// Build in-memory PKCS12 keystore
String password = generateGuestPassword(email);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
keyStore.setKeyEntry(
KEYSTORE_ALIAS,
keyPair.getPrivate(),
password.toCharArray(),
new Certificate[] {cert});
// Round-trip through serialization so the keystore is fully initialised
ByteArrayOutputStream baos = new ByteArrayOutputStream();
keyStore.store(baos, password.toCharArray());
KeyStore loaded = KeyStore.getInstance("PKCS12");
loaded.load(new java.io.ByteArrayInputStream(baos.toByteArray()), password.toCharArray());
log.debug("Guest certificate generated (CN={}, SAN=rfc822Name:[email])", safeCn);
return loaded;
}
/**
* Derives a deterministic password for a guest keystore. The password is a Base64-encoded
* HMAC-SHA256 of the email using the application's secret key, truncated to 32 characters. Two
* calls with the same email always return the same password.
*
* @param email the guest signer's email address
* @return a deterministic password string
*/
public String generateGuestPassword(String email) {
try {
String rawKey = applicationProperties.getAutomaticallyGenerated().getKey();
if (rawKey == null || rawKey.isBlank()) {
// Fallback: SHA-256 of email if no application key available
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(email.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash).substring(0, 32);
}
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec keySpec =
new SecretKeySpec(rawKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmac.init(keySpec);
byte[] macBytes = hmac.doFinal(email.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(macBytes);
// Truncate to 32 chars; use URL-safe replacement to avoid keystore password issues
return encoded.replace("/", "_").replace("+", "-").substring(0, 32);
} catch (Exception e) {
throw new IllegalStateException("Failed to derive guest keystore password", e);
}
}
}
@@ -72,6 +72,9 @@ public class SigningFinalizationService {
@Autowired(required = false)
private final UserServerCertificateService userServerCertificateService;
@Autowired(required = false)
private final GuestCertificateService guestCertificateService;
// ===== PUBLIC API =====
/**
@@ -891,6 +894,28 @@ public class SigningFinalizationService {
"Failed to generate or retrieve user certificate: " + e.getMessage());
}
case "GUEST_CERT":
if (guestCertificateService == null) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Guest certificate service is not available");
}
if (participant.getEmail() == null || participant.getEmail().isBlank()) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST,
"Guest certificate requires participant email address");
}
try {
return guestCertificateService.generateGuestKeyStore(participant.getEmail());
} catch (Exception e) {
log.error(
"Failed to generate guest certificate for {}: {}",
participant.getEmail(),
e.getMessage());
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR,
"Failed to generate guest certificate: " + e.getMessage());
}
default:
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Invalid certificate type: " + certType);
@@ -943,6 +968,12 @@ public class SigningFinalizationService {
}
}
if ("GUEST_CERT".equalsIgnoreCase(certType)
&& guestCertificateService != null
&& participant.getEmail() != null) {
return guestCertificateService.generateGuestPassword(participant.getEmail());
}
return submission.getPassword();
}
@@ -8,11 +8,13 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -63,6 +65,9 @@ public class WorkflowSessionService {
private final MetadataEncryptionService metadataEncryptionService;
private final CertificateSubmissionValidator certificateSubmissionValidator;
@Autowired(required = false)
private stirling.software.proprietary.security.service.EmailService emailService;
public void ensureSigningEnabled() {
if (!applicationProperties.getStorage().isEnabled()
|| !applicationProperties.getStorage().getSigning().isEnabled()) {
@@ -230,6 +235,62 @@ public class WorkflowSessionService {
session.addParticipant(participant);
participant = workflowParticipantRepository.save(participant);
// Send signing invitation email to external/guest participants
if (request.getEmail() != null
&& request.getUserId() == null
&& emailService != null
&& (request.isSendNotification())) {
try {
String signingUrl = buildSigningUrl(participant.getShareToken());
String ownerName =
session.getOwnerEmail() != null
? session.getOwnerEmail()
: "A Stirling PDF user";
String expiresAt =
participant.getExpiresAt() != null
? participant.getExpiresAt().toString()
: null;
emailService.sendSigningInvitationEmail(
participant.getEmail(),
ownerName,
session.getDocumentName(),
signingUrl,
expiresAt,
session.getMessage());
participant.setStatus(ParticipantStatus.NOTIFIED);
workflowParticipantRepository.save(participant);
log.info(
"Sent signing invitation to external participant (domain: {})",
emailDomain(participant.getEmail()));
} catch (Exception e) {
log.warn(
"Failed to send signing invitation email (domain: {}): {}",
emailDomain(participant.getEmail()),
e.getMessage());
}
}
}
}
/** Returns only the domain portion of an email for privacy-safe logging. */
private static String emailDomain(String email) {
if (email == null) return "<null>";
int at = email.indexOf('@');
return at >= 0 ? email.substring(at) : "<no-domain>";
}
/** Builds the guest signing URL for a share token using the current request context. */
private String buildSigningUrl(String shareToken) {
try {
return ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/sign/")
.path(shareToken)
.toUriString();
} catch (Exception e) {
// Fallback if called outside of a request context (e.g. in tests)
log.debug("Could not determine base URL from request context, using relative path");
return "/sign/" + shareToken;
}
}
@@ -29,7 +29,6 @@ import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.DatabaseService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.MfaService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
import stirling.software.proprietary.service.UserLicenseSettingsService;
@@ -48,7 +47,6 @@ class ProprietaryUIDataControllerTest {
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private PersistentAuditEventRepository auditRepository;
@Mock private MfaService mfaService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private AuditConfigurationProperties auditConfig;
@@ -81,8 +79,7 @@ class ProprietaryUIDataControllerTest {
false,
licenseSettingsService,
auditRepository,
mfaService,
loginAttemptService);
mfaService);
}
@Test
@@ -28,7 +28,6 @@ import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.api.user.UsernameAndPass;
import stirling.software.proprietary.security.repository.TeamRepository;
import stirling.software.proprietary.security.service.EmailService;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -48,7 +47,6 @@ class UserControllerTest {
@Mock private UserRepository userRepository;
@Mock private EmailService emailService;
@Mock private UserLicenseSettingsService licenseSettingsService;
@Mock private LoginAttemptService loginAttemptService;
private ApplicationProperties applicationProperties;
private MockMvc mockMvc;
@@ -67,8 +65,7 @@ class UserControllerTest {
teamRepository,
userRepository,
Optional.of(emailService),
licenseSettingsService,
loginAttemptService);
licenseSettingsService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@@ -141,13 +138,4 @@ class UserControllerTest {
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error").value("User not found."));
}
@Test
void unlockUserCallsResetAttemptsAndReturnsOk() throws Exception {
mockMvc.perform(post("/api/v1/user/admin/unlockUser/lockeduser"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("User account unlocked successfully"));
verify(loginAttemptService).resetAttempts("lockeduser");
}
}
@@ -164,4 +164,110 @@ public class EmailServiceTest {
assertEquals("Invalid Addresses", e.getMessage());
}
}
@Test
void sendSigningInvitationEmail_sendsEmailWithDocumentNameInSubject()
throws MessagingException {
when(applicationProperties.getMail()).thenReturn(mailProperties);
when(mailProperties.getFrom()).thenReturn("no-reply@stirling-software.com");
MimeMessage mimeMessage = mock(MimeMessage.class);
when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
emailService.sendSigningInvitationEmail(
"guest@example.com",
"Alice Owner",
"Contract 2025.pdf",
"https://example.com/sign/abc-token",
"2025-12-31",
"Please review and sign");
verify(mailSender).send(mimeMessage);
}
@Test
void sendSigningInvitationEmail_throwsForBlankRecipient() {
assertThrows(
MessagingException.class,
() ->
emailService.sendSigningInvitationEmail(
"",
"Owner",
"Doc.pdf",
"https://example.com/sign/tok",
null,
null));
}
// ── HTML injection / URL guard tests ──────────────────────────────────
@Test
void sendSigningInvitationEmail_doesNotThrowForHtmlInDocumentName() throws MessagingException {
when(applicationProperties.getMail()).thenReturn(mailProperties);
when(mailProperties.getFrom()).thenReturn("no-reply@stirling.com");
MimeMessage mimeMessage = mock(MimeMessage.class);
when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
// Document name with injected HTML — must not cause an exception
emailService.sendSigningInvitationEmail(
"guest@example.com",
"Alice",
"<script>alert('xss')</script>Contract.pdf",
"https://example.com/sign/tok",
null,
null);
verify(mailSender).send(mimeMessage);
}
@Test
void sendSigningInvitationEmail_doesNotThrowForHtmlInMessage() throws MessagingException {
when(applicationProperties.getMail()).thenReturn(mailProperties);
when(mailProperties.getFrom()).thenReturn("no-reply@stirling.com");
MimeMessage mimeMessage = mock(MimeMessage.class);
when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
// Personal message with HTML injection
emailService.sendSigningInvitationEmail(
"guest@example.com",
"Bob <b>Owner</b>",
"Contract.pdf",
"https://example.com/sign/tok",
"2026-12-31",
"<img src=x onerror=alert(1)> Please sign");
verify(mailSender).send(mimeMessage);
}
@Test
void sendSigningInvitationEmail_doesNotThrowForJavascriptUrl() throws MessagingException {
when(applicationProperties.getMail()).thenReturn(mailProperties);
when(mailProperties.getFrom()).thenReturn("no-reply@stirling.com");
MimeMessage mimeMessage = mock(MimeMessage.class);
when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
// javascript: URL — must be replaced with '#', not thrown into email
emailService.sendSigningInvitationEmail(
"guest@example.com",
"Owner",
"Contract.pdf",
"javascript:alert(document.cookie)",
null,
null);
verify(mailSender).send(mimeMessage);
}
@Test
void sendSigningInvitationEmail_acceptsNullOptionalParams() throws MessagingException {
when(applicationProperties.getMail()).thenReturn(mailProperties);
when(mailProperties.getFrom()).thenReturn("no-reply@stirling.com");
MimeMessage mimeMessage = mock(MimeMessage.class);
when(mailSender.createMimeMessage()).thenReturn(mimeMessage);
// expiresAt and message are optional — null values must not cause NPE
emailService.sendSigningInvitationEmail(
"guest@example.com", null, null, "https://example.com/sign/tok", null, null);
verify(mailSender).send(mimeMessage);
}
}
@@ -6,7 +6,6 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
@@ -237,145 +236,4 @@ class LoginAttemptServiceTest {
// If you later clamp to 0, update this assertion accordingly and add a new test.
assertEquals(expected, actual, "Current behavior returns negative values without clamping");
}
@Test
@DisplayName("resetAttempts(): removes entry from cache for given key")
void resetAttempts_shouldRemoveEntryFromCache() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
AttemptCounter counter = new AttemptCounter();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
ac.setInt(counter, 5);
attemptsCache.put("blockeduser", counter);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("resetAttempts", String.class);
method.invoke(svc, "BlockedUser"); // case-insensitive
assertFalse(
attemptsCache.containsKey("blockeduser"),
"resetAttempts should remove the user's entry from the cache");
}
@Test
@DisplayName("resetAttempts(): does nothing for null or blank key")
void resetAttempts_shouldDoNothingForNullOrBlankKey() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
attemptsCache.put("existing", new AttemptCounter());
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("resetAttempts", String.class);
method.invoke(svc, (Object) null);
method.invoke(svc, " ");
assertEquals(1, attemptsCache.size(), "Null or blank key should not modify the cache");
}
@Test
@DisplayName("isBlockingEnabled(): returns true when blocking is enabled")
void isBlockingEnabled_shouldReturnTrueWhenEnabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
var method = svc.getClass().getMethod("isBlockingEnabled");
boolean result = (Boolean) method.invoke(svc);
assertTrue(result, "isBlockingEnabled should return true when isBlockedEnabled is true");
}
@Test
@DisplayName("isBlockingEnabled(): returns false when blocking is disabled")
void isBlockingEnabled_shouldReturnFalseWhenDisabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", false);
var method = svc.getClass().getMethod("isBlockingEnabled");
boolean result = (Boolean) method.invoke(svc);
assertFalse(result, "isBlockingEnabled should return false when isBlockedEnabled is false");
}
@Test
@DisplayName("getAllBlockedUsers(): returns empty list when blocking is disabled")
void getAllBlockedUsers_shouldReturnEmptyWhenDisabled() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", false);
setPrivate(svc, "attemptsCache", new ConcurrentHashMap<String, AttemptCounter>());
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertTrue(
result.isEmpty(),
"getAllBlockedUsers should return empty list when blocking is disabled");
}
@Test
@DisplayName("getAllBlockedUsers(): returns only users at or above MAX_ATTEMPT")
void getAllBlockedUsers_shouldReturnOnlyBlockedUsers() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
setPrivate(svc, "MAX_ATTEMPT", 3);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
// User with exactly MAX_ATTEMPT attempts (blocked)
AttemptCounter blocked1 = new AttemptCounter();
ac.setInt(blocked1, 3);
attemptsCache.put("blocked1", blocked1);
// User with more than MAX_ATTEMPT attempts (blocked)
AttemptCounter blocked2 = new AttemptCounter();
ac.setInt(blocked2, 5);
attemptsCache.put("blocked2", blocked2);
// User with fewer than MAX_ATTEMPT attempts (not blocked)
AttemptCounter notBlocked = new AttemptCounter();
ac.setInt(notBlocked, 2);
attemptsCache.put("safe", notBlocked);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertEquals(2, result.size(), "Should return exactly 2 blocked users");
assertTrue(result.contains("blocked1"), "Should contain blocked1");
assertTrue(result.contains("blocked2"), "Should contain blocked2");
assertFalse(result.contains("safe"), "Should not contain safe user");
}
@Test
@DisplayName("getAllBlockedUsers(): returns empty list when no users are blocked")
void getAllBlockedUsers_shouldReturnEmptyWhenNoUsersBlocked() throws Exception {
Object svc = constructLoginAttemptService();
setPrivateBoolean(svc, "isBlockedEnabled", true);
setPrivate(svc, "MAX_ATTEMPT", 3);
var attemptsCache = new ConcurrentHashMap<String, AttemptCounter>();
Field ac = AttemptCounter.class.getDeclaredField("attemptCount");
ac.setAccessible(true);
AttemptCounter notBlocked = new AttemptCounter();
ac.setInt(notBlocked, 1);
attemptsCache.put("user1", notBlocked);
setPrivate(svc, "attemptsCache", attemptsCache);
var method = svc.getClass().getMethod("getAllBlockedUsers");
@SuppressWarnings("unchecked")
List<String> result = (List<String>) method.invoke(svc);
assertTrue(result.isEmpty(), "Should return empty list when no users exceed MAX_ATTEMPT");
}
}
@@ -0,0 +1,354 @@
package stirling.software.proprietary.workflow.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import stirling.software.proprietary.workflow.dto.ParticipantResponse;
import stirling.software.proprietary.workflow.dto.SignatureSubmissionRequest;
import stirling.software.proprietary.workflow.model.ParticipantStatus;
import stirling.software.proprietary.workflow.model.WorkflowParticipant;
import stirling.software.proprietary.workflow.model.WorkflowSession;
import stirling.software.proprietary.workflow.model.WorkflowStatus;
import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;
import stirling.software.proprietary.workflow.service.MetadataEncryptionService;
import stirling.software.proprietary.workflow.service.WorkflowSessionService;
import tools.jackson.databind.ObjectMapper;
@ExtendWith(MockitoExtension.class)
class WorkflowParticipantControllerTest {
@Mock private WorkflowSessionService workflowSessionService;
@Mock private WorkflowParticipantRepository participantRepository;
@Mock private MetadataEncryptionService metadataEncryptionService;
private ObjectMapper objectMapper;
private WorkflowParticipantController controller;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
controller =
new WorkflowParticipantController(
workflowSessionService,
participantRepository,
objectMapper,
metadataEncryptionService);
}
// ── Helpers ──────────────────────────────────────────────────────────────
private WorkflowParticipant guestParticipant(String token, String email) {
WorkflowSession session = new WorkflowSession();
session.setStatus(WorkflowStatus.IN_PROGRESS);
session.setFinalized(false);
WorkflowParticipant participant = new WorkflowParticipant();
participant.setId(1L);
participant.setShareToken(token);
participant.setEmail(email);
participant.setUser(null); // guest — no registered user
participant.setStatus(ParticipantStatus.VIEWED);
participant.setWorkflowSession(session);
return participant;
}
// ── GUEST_CERT defaulting ─────────────────────────────────────────────
@Test
void submitSignature_guestNoCertType_defaultsToGuestCert() throws Exception {
String token = "test-token-123";
WorkflowParticipant participant = guestParticipant(token, "guest@example.com");
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
// No encrypt() stub — GUEST_CERT skips encryption entirely (fix verified in separate test)
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
// certType intentionally not set — should default to GUEST_CERT
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
httpRequest.setRemoteAddr("192.168.1.1");
httpRequest.addHeader("User-Agent", "TestBrowser/1.0");
ResponseEntity<ParticipantResponse> response =
controller.submitSignature(request, httpRequest);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
// Capture the saved participant and verify certType in metadata
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
WorkflowParticipant saved = captor.getValue();
assertThat(saved.getStatus()).isEqualTo(ParticipantStatus.SIGNED);
Map<String, Object> metadata = saved.getParticipantMetadata();
assertThat(metadata).containsKey("certificateSubmission");
@SuppressWarnings("unchecked")
Map<String, Object> certSub = (Map<String, Object>) metadata.get("certificateSubmission");
assertThat(certSub.get("certType")).isEqualTo("GUEST_CERT");
}
@Test
void submitSignature_registeredUserNoCertType_doesNotDefaultToGuestCert() throws Exception {
String token = "registered-token";
WorkflowParticipant participant = guestParticipant(token, "user@example.com");
// Give participant a registered user
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("registered");
participant.setUser(user);
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
// certType intentionally not set
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
ResponseEntity<ParticipantResponse> response =
controller.submitSignature(request, httpRequest);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
WorkflowParticipant saved = captor.getValue();
Map<String, Object> metadata = saved.getParticipantMetadata();
// No certType defaulted — certificateSubmission should be absent
assertThat(metadata).doesNotContainKey("certificateSubmission");
}
// ── Audit trail ───────────────────────────────────────────────────────
@Test
void submitSignature_capturesAuditTrail() throws Exception {
String token = "audit-token";
WorkflowParticipant participant = guestParticipant(token, "audited@example.com");
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
httpRequest.setRemoteAddr("10.0.0.1");
httpRequest.addHeader("User-Agent", "AuditBrowser/2.0");
controller.submitSignature(request, httpRequest);
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
Map<String, Object> metadata = captor.getValue().getParticipantMetadata();
assertThat(metadata).containsKey("auditTrail");
@SuppressWarnings("unchecked")
Map<String, Object> audit = (Map<String, Object>) metadata.get("auditTrail");
assertThat(audit).containsKey("ipHash");
assertThat(audit).containsKey("userAgent");
assertThat(audit).containsKey("submittedAt");
assertThat(audit.get("email")).isEqualTo("audited@example.com");
// IP should be hashed, not stored raw
assertThat(audit.get("ipHash")).isNotEqualTo("10.0.0.1");
assertThat(audit.get("userAgent")).isEqualTo("AuditBrowser/2.0");
}
// ── GUEST_CERT password not stored ───────────────────────────────────
@Test
void submitSignature_guestCert_doesNotStoreEncryptedPassword() throws Exception {
String token = "no-pwd-token";
WorkflowParticipant participant = guestParticipant(token, "guest@example.com");
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
// certType not set → defaults to GUEST_CERT; no password submitted
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
controller.submitSignature(request, httpRequest);
// metadataEncryptionService.encrypt() must NOT be called for GUEST_CERT
verify(metadataEncryptionService, never()).encrypt(any());
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
@SuppressWarnings("unchecked")
Map<String, Object> certSub =
(Map<String, Object>)
captor.getValue().getParticipantMetadata().get("certificateSubmission");
assertThat(certSub.get("password")).isNull();
}
// ── Audit trail edge cases ────────────────────────────────────────────
@Test
void submitSignature_userAgentTruncatedAt500Chars() throws Exception {
String token = "ua-token";
WorkflowParticipant participant = guestParticipant(token, "ua@example.com");
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
httpRequest.addHeader("User-Agent", "A".repeat(600));
controller.submitSignature(request, httpRequest);
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
@SuppressWarnings("unchecked")
Map<String, Object> audit =
(Map<String, Object>) captor.getValue().getParticipantMetadata().get("auditTrail");
String storedUa = (String) audit.get("userAgent");
assertThat(storedUa).hasSize(500);
}
@Test
void submitSignature_nullIp_storesNullHash() throws Exception {
String token = "null-ip-token";
WorkflowParticipant participant = guestParticipant(token, "noip@example.com");
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
when(participantRepository.save(any())).thenReturn(participant);
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
MockHttpServletRequest httpRequest = new MockHttpServletRequest();
httpRequest.setRemoteAddr(null);
controller.submitSignature(request, httpRequest);
ArgumentCaptor<WorkflowParticipant> captor =
ArgumentCaptor.forClass(WorkflowParticipant.class);
verify(participantRepository).save(captor.capture());
@SuppressWarnings("unchecked")
Map<String, Object> audit =
(Map<String, Object>) captor.getValue().getParticipantMetadata().get("auditTrail");
assertThat(audit.get("ipHash")).isNull();
}
// ── Token guards ──────────────────────────────────────────────────────
@Test
void submitSignature_expiredToken_returnsForbidden() {
String token = "expired-token";
WorkflowParticipant participant = guestParticipant(token, "expired@example.com");
participant.setExpiresAt(java.time.LocalDateTime.now().minusDays(1)); // expired
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> controller.submitSignature(request, new MockHttpServletRequest()));
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
void submitSignature_alreadySigned_returnsBadRequest() {
String token = "signed-token";
WorkflowParticipant participant = guestParticipant(token, "done@example.com");
participant.setStatus(ParticipantStatus.SIGNED);
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> controller.submitSignature(request, new MockHttpServletRequest()));
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void submitSignature_alreadyDeclined_returnsBadRequest() {
String token = "declined-token";
WorkflowParticipant participant = guestParticipant(token, "declined@example.com");
participant.setStatus(ParticipantStatus.DECLINED);
when(participantRepository.findByShareToken(token)).thenReturn(Optional.of(participant));
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(token);
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> controller.submitSignature(request, new MockHttpServletRequest()));
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void submitSignature_unknownToken_returnsForbidden() {
when(participantRepository.findByShareToken("no-such-token")).thenReturn(Optional.empty());
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken("no-such-token");
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> controller.submitSignature(request, new MockHttpServletRequest()));
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
void submitSignature_blankToken_returnsBadRequest() {
SignatureSubmissionRequest request = new SignatureSubmissionRequest();
request.setParticipantToken(" ");
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> controller.submitSignature(request, new MockHttpServletRequest()));
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@@ -0,0 +1,138 @@
package stirling.software.proprietary.workflow.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
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.junit.jupiter.MockitoExtension;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.AutomaticallyGenerated;
@ExtendWith(MockitoExtension.class)
class GuestCertificateServiceTest {
@Mock private ApplicationProperties applicationProperties;
@Mock private AutomaticallyGenerated automaticallyGenerated;
private GuestCertificateService service;
@BeforeEach
void setUp() {
when(applicationProperties.getAutomaticallyGenerated()).thenReturn(automaticallyGenerated);
when(automaticallyGenerated.getKey()).thenReturn("test-secret-key-for-unit-tests");
service = new GuestCertificateService(applicationProperties);
}
@Test
void generateGuestKeyStore_createsValidPKCS12() throws Exception {
String email = "signer@example.com";
KeyStore keyStore = service.generateGuestKeyStore(email);
assertThat(keyStore).isNotNull();
assertThat(keyStore.getType()).isEqualToIgnoringCase("PKCS12");
assertThat(keyStore.aliases().hasMoreElements()).isTrue();
String alias = keyStore.aliases().nextElement();
assertThat(keyStore.isKeyEntry(alias)).isTrue();
assertThat(keyStore.getCertificate(alias)).isNotNull();
}
@Test
void generateGuestKeyStore_subjectContainsSanitizedEmail() throws Exception {
String email = "signer@example.com";
KeyStore keyStore = service.generateGuestKeyStore(email);
String alias = keyStore.aliases().nextElement();
X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
String subjectDn = cert.getSubjectX500Principal().getName();
assertThat(subjectDn).contains("signer@example.com");
assertThat(subjectDn).contains("Stirling-PDF Guest");
}
@Test
void generateGuestKeyStore_sanContainsEmailRfc822Name() throws Exception {
String email = "guest@test.org";
KeyStore keyStore = service.generateGuestKeyStore(email);
String alias = keyStore.aliases().nextElement();
X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
// Parse SAN extension via BouncyCastle
JcaX509CertificateHolder holder = new JcaX509CertificateHolder(cert);
org.bouncycastle.asn1.x509.GeneralNames sans =
org.bouncycastle.asn1.x509.GeneralNames.getInstance(
holder.getExtension(Extension.subjectAlternativeName).getParsedValue());
boolean foundEmail = false;
for (org.bouncycastle.asn1.x509.GeneralName gn : sans.getNames()) {
if (gn.getTagNo() == org.bouncycastle.asn1.x509.GeneralName.rfc822Name) {
String value = gn.getName().toString();
if (value.equals(email)) {
foundEmail = true;
}
}
}
assertThat(foundEmail)
.as("SAN should contain rfc822Name matching the signer's email")
.isTrue();
}
@Test
void generateGuestPassword_isDeterministic() {
String email = "signer@example.com";
String pw1 = service.generateGuestPassword(email);
String pw2 = service.generateGuestPassword(email);
assertThat(pw1).isEqualTo(pw2);
assertThat(pw1).hasSize(32);
}
@Test
void generateGuestPassword_differentEmails_differentPasswords() {
String pw1 = service.generateGuestPassword("alice@example.com");
String pw2 = service.generateGuestPassword("bob@example.com");
assertThat(pw1).isNotEqualTo(pw2);
}
@Test
void generateGuestPassword_fallbackWhenNoKey() {
// If no app key is configured, should fall back to SHA-256 of email
when(automaticallyGenerated.getKey()).thenReturn(null);
String pw = service.generateGuestPassword("fallback@example.com");
assertThat(pw).isNotNull();
assertThat(pw).hasSize(32);
}
@Test
void generateGuestKeyStore_certIsValidForSigning() throws Exception {
String email = "signer@example.com";
KeyStore keyStore = service.generateGuestKeyStore(email);
String alias = keyStore.aliases().nextElement();
X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
// Certificate must be currently valid
cert.checkValidity();
// Key usage must include digitalSignature (bit 0) and nonRepudiation (bit 1)
boolean[] keyUsage = cert.getKeyUsage();
assertThat(keyUsage).isNotNull();
assertThat(keyUsage[0]).as("digitalSignature key usage").isTrue();
assertThat(keyUsage[1]).as("nonRepudiation key usage").isTrue();
}
}
+5 -47
View File
@@ -338,43 +338,7 @@ RUN mkdir -p /magick-export/usr/bin \
cp -a /usr/local/etc/ImageMagick-7 /magick-export/usr/local/etc/
# Stage 4: Build FFmpeg from source
FROM ubuntu:noble AS ffmpeg-build
ARG TARGETPLATFORM
ARG FFMPEG_VERSION=8.1
COPY ffmpeg-${FFMPEG_VERSION}.tar.gz.asc /tmp/ffmpeg-sig/
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/tmp/ffmpeg-build,id=ffmpeg-build-${TARGETPLATFORM:-local} \
apt-get update && apt-get install -y --no-install-recommends \
build-essential curl ca-certificates pkg-config nasm \
libx264-dev libvpx-dev gnupg && \
rm -rf /var/lib/apt/lists/* && \
cd /tmp/ffmpeg-build && \
rm -rf ffmpeg-* && \
# Download tarball and verify against locally-pinned GPG signature
curl -fsSL --max-time 300 --retry 3 --retry-delay 5 \
-o "ffmpeg-${FFMPEG_VERSION}.tar.gz" \
"https://www.ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys FCF986EA15E6E293A5644F10B4322F04D67658D8 && \
gpg --verify /tmp/ffmpeg-sig/ffmpeg-${FFMPEG_VERSION}.tar.gz.asc "ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
tar xzf "ffmpeg-${FFMPEG_VERSION}.tar.gz" && \
cd "ffmpeg-${FFMPEG_VERSION}" && \
./configure \
--prefix=/usr/local \
--enable-gpl \
--enable-libx264 \
--enable-libvpx \
--disable-doc \
--disable-debug \
--disable-static \
--enable-shared && \
make -j"$(nproc)" && \
make install
# Stage 5: Build Python venv
# Stage 4: Build Python venv
FROM ubuntu:noble AS python-venv-build
ARG TARGETPLATFORM
ARG UNOSERVER_VERSION=3.6
@@ -421,8 +385,8 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
apt-get install -y --no-install-recommends \
# Core tools
ca-certificates tzdata tini bash fontconfig curl \
poppler-utils fontforge \
unpaper pngquant \
ffmpeg poppler-utils fontforge \
gosu unpaper pngquant \
# Fonts: full coverage for standard + fat variants
fonts-dejavu \
fonts-liberation2 \
@@ -632,13 +596,6 @@ COPY --link --from=pdf-tools-build /usr/local/bin/qpdf /usr/bin/qpdf
COPY --link --from=pdf-tools-build /magick-export/ /
COPY --link --from=gs-build /usr/local/bin/gs /usr/local/bin/gs
COPY --link --from=gs-build /usr/local/share/ghostscript /usr/local/share/ghostscript
COPY --link --from=ffmpeg-build /usr/local/bin/ff* /usr/local/bin/
COPY --link --from=ffmpeg-build /usr/local/lib/libav*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/local/lib/libsw*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/local/lib/libpostproc*.so* /usr/local/lib/
# ffmpeg runtime deps (libx264, libvpx) — copied from build stage instead of apt
COPY --link --from=ffmpeg-build /usr/lib/*/libx264*.so* /usr/local/lib/
COPY --link --from=ffmpeg-build /usr/lib/*/libvpx*.so* /usr/local/lib/
# Python venv pre-built (no pip install at runtime, no build tools needed)
COPY --link --from=python-venv-build /opt/venv /opt/venv
@@ -665,7 +622,8 @@ RUN set -eux; \
-d /home/stirlingpdfuser -s /bin/bash stirlingpdfuser 2>/dev/null \
|| useradd -m -g stirlingpdfgroup \
-d /home/stirlingpdfuser -s /bin/bash stirlingpdfuser; \
fi
fi; \
ln -sf /usr/sbin/gosu /usr/local/bin/su-exec
# Application directories
RUN set -eux; \
-11
View File
@@ -1,11 +0,0 @@
-----BEGIN PGP SIGNATURE-----
iQFMBAABCgA2FiEE/PmG6hXm4pOlZE8QtDIvBNZ2WNgFAmm4UOEYHGZmbXBlZy1k
ZXZlbEBmZm1wZWcub3JnAAoJELQyLwTWdljY6kAH/3UjGSnwGV8As/SgtXEYgSz8
66GQlrLDiF4QVVqmkSN5WQTcne/x7s7AJ+z2YkO17zg4DQYcJrPdwEsT1EiUnF/N
+kZW4E7umBZgcVYc9Kv7cj6riqDnedN+3QjuH4KhT82AZ8sHppTPdF3EsGV5YYhf
J+nT4rAHiHX84hcS6X9UL8qptrWRAQaYU+P0hWZ57P1RfIlFScylKYZ68Sf5EeB7
j0KIpu+FEzcDah1bemgUhHX0lM1VhjsDicv+swqAFT43Gc3YRcx42V5rCpP3UXD7
rZ1t5T0HojEU4pmaOdRMqLB3W4B8YptMPLqyQHmI4fBPxdStVeJ05ZhlDXwc1bA=
=4Mgh
-----END PGP SIGNATURE-----
+2 -2
View File
@@ -1,8 +1,8 @@
# Stirling-PDF - Full version (embedded frontend)
# Uses pre-built base image for fast builds
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
FROM gradle:9.3.1-jdk25 AS app-build
+2 -2
View File
@@ -2,8 +2,8 @@
# Extra fonts for air-gapped environments
# Uses pre-built base image for fast builds
ARG BASE_VERSION=1.0.2
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
ARG BASE_VERSION=1.0.0
ARG BASE_IMAGE=ghcr.io/stirling-tools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
FROM gradle:9.3.1-jdk25 AS app-build
+1 -1
View File
@@ -93,7 +93,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
bash \
curl \
shadow \
util-linux && \
su-exec && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /tmp/stirling-pdf/heap_dumps && \
mkdir -p /usr/share/fonts/opentype/noto && \
# User permissions
+270
View File
@@ -0,0 +1,270 @@
# Guest Signing — Test Plan
## Automated coverage summary
The following scenarios are already covered by automated tests and **do not need manual testing**:
| Area | Coverage | Test file |
|------|----------|-----------|
| Guest certificate generation (PKCS12, SAN, key usage) | Unit | `GuestCertificateServiceTest.java` |
| EKU is `emailProtection` (not `codeSigning`) | Unit | `GuestCertificateServiceTest.java` |
| Password determinism / uniqueness | Unit | `GuestCertificateServiceTest.java` |
| GUEST_CERT defaulted for external participants | Unit | `WorkflowParticipantControllerTest.java` |
| Registered users not defaulted to GUEST_CERT | Unit | `WorkflowParticipantControllerTest.java` |
| Audit trail: IP hashed, UA stored, timestamp present | Unit | `WorkflowParticipantControllerTest.java` |
| Audit trail: User-agent truncated at 500 chars | Unit | `WorkflowParticipantControllerTest.java` |
| Audit trail: null IP stored as null (not exception) | Unit | `WorkflowParticipantControllerTest.java` |
| GUEST_CERT password not stored in metadata | Unit | `WorkflowParticipantControllerTest.java` |
| Expired token → 403 | Unit | `WorkflowParticipantControllerTest.java` |
| Already-SIGNED → 400 | Unit | `WorkflowParticipantControllerTest.java` |
| Already-DECLINED → 400 | Unit | `WorkflowParticipantControllerTest.java` |
| Unknown token → 403 | Unit | `WorkflowParticipantControllerTest.java` |
| Blank token → 400 | Unit | `WorkflowParticipantControllerTest.java` |
| HTML injection in email: docName, ownerName, message | Unit | `EmailServiceTest.java` |
| `javascript:` URL replaced with `#` in email | Unit | `EmailServiceTest.java` |
| Email sends for null optional params | Unit | `EmailServiceTest.java` |
| `/sign/:token` — loading spinner shown | E2E | `GuestSigningE2E.spec.ts` |
| `/sign/:token` — expired (403) page | E2E | `GuestSigningE2E.spec.ts` |
| `/sign/:token` — already-SIGNED state on load | E2E | `GuestSigningE2E.spec.ts` |
| `/sign/:token` — already-DECLINED state on load | E2E | `GuestSigningE2E.spec.ts` |
| `/sign/:token` — 500 error page | E2E | `GuestSigningE2E.spec.ts` |
| Signing form renders with doc name, owner, message | E2E | `GuestSigningE2E.spec.ts` |
| PDF iframe present with correct src | E2E | `GuestSigningE2E.spec.ts` |
| Auto-cert selected by default + info alert | E2E | `GuestSigningE2E.spec.ts` |
| Switching to P12 shows file + password inputs | E2E | `GuestSigningE2E.spec.ts` |
| Switching back to auto-cert hides P12 inputs | E2E | `GuestSigningE2E.spec.ts` |
| Submit → success page; FormData contains GUEST_CERT + token | E2E | `GuestSigningE2E.spec.ts` |
| Submit failure shows error with server message | E2E | `GuestSigningE2E.spec.ts` |
| Submit button disabled while in-flight | E2E | `GuestSigningE2E.spec.ts` |
| Decline → opens modal with correct title + body | E2E | `GuestSigningE2E.spec.ts` |
| Decline → Cancel closes modal, form still visible | E2E | `GuestSigningE2E.spec.ts` |
| Decline → Confirm transitions to declined state | E2E | `GuestSigningE2E.spec.ts` |
| SelectParticipantsStep — registered/external tabs | Unit | `SelectParticipantsStep.test.tsx` |
| SelectParticipantsStep — email validation + duplicates | Unit | `SelectParticipantsStep.test.tsx` |
| SelectParticipantsStep — add by button / Enter key | Unit | `SelectParticipantsStep.test.tsx` |
| SelectParticipantsStep — remove participant | Unit | `SelectParticipantsStep.test.tsx` |
| SelectParticipantsStep — Continue disabled when empty | Unit | `SelectParticipantsStep.test.tsx` |
| GuestSignPage — all page states (loading/expired/signed/etc.) | Unit | `GuestSignPage.test.tsx` |
| GuestSignPage — submit calls correct endpoint | Unit | `GuestSignPage.test.tsx` |
---
## Running the automated tests
```bash
# Backend unit tests (from repo root)
./gradlew :app:proprietary:test \
--tests "stirling.software.proprietary.workflow.service.GuestCertificateServiceTest" \
--tests "stirling.software.proprietary.workflow.controller.WorkflowParticipantControllerTest" \
--tests "stirling.software.proprietary.security.service.EmailServiceTest"
# Frontend unit tests
cd frontend && npm test -- --run \
src/core/routes/GuestSignPage.test.tsx \
src/core/components/shared/signing/steps/SelectParticipantsStep.test.tsx
# Frontend E2E (requires dev server running)
cd frontend && npx playwright test src/core/tests/guestSigning/GuestSigningE2E.spec.ts
```
---
## Residual manual test plan
These scenarios require a running system with real SMTP, storage, and a PDF.
### Prerequisites
- Stirling PDF running with the config below applied
- A real SMTP server (or MailHog locally) receiving email
- A test PDF document
- A valid .p12 certificate for the P12 upload test
---
### MT-1 — Owner invites an external guest (email delivery)
**Steps:**
1. Log in as a registered user
2. Open a PDF and start a signing session
3. In the participants step, switch to the **External (by email)** tab
4. Enter a real email address and click Add
5. Continue through the session creation flow
6. Check the inbox of the guest email address
**Expected:**
- Email received with subject `Please sign: <document name>`
- Email shows owner's email, document name, optional message
- "Review and Sign Document" button links to `https://<your-host>/sign/<token>`
- No raw HTML visible in the email body (escaping check)
- No raw IP address visible anywhere in the email
---
### MT-2 — Guest signs with auto-generated certificate (happy path)
**Steps:**
1. Open the signing link from MT-1
2. Verify the loading spinner appears briefly
3. Verify document name and owner info are displayed
4. Verify PDF is visible in the embedded preview
5. Verify **"Use auto-generated certificate (recommended)"** is selected by default
6. Draw a signature in the canvas
7. Click **Submit Signature**
**Expected:**
- Success page: "Your signature has been submitted successfully."
- PDF in session now has a digital signature
- Signature certificate CN includes the guest's email (sanitized)
- Certificate SAN contains `rfc822Name=<email>` — verify in Adobe Acrobat / PDF viewer signature panel
- Participant status in admin panel changed to SIGNED
- Audit trail in database: `ipHash` is a Base64 SHA-256 (not raw IP), `userAgent` matches browser, `submittedAt` timestamp is recent
---
### MT-3 — Guest signs with their own P12 certificate
**Steps:**
1. Open a fresh signing link (new session)
2. Select **"Upload my own certificate"**
3. Upload a valid `.p12` file
4. Enter the certificate password
5. Draw a signature and submit
**Expected:**
- Success page shown
- PDF signed with the uploaded certificate (not a Stirling-generated one)
- Signature visible in PDF viewer with details from the P12
---
### MT-4 — Guest uses an expired signing link
**Steps:**
1. Set a participant's `expires_at` to the past in the database (or wait for expiry)
2. Navigate to the signing link
**Expected:**
- "This signing link has expired." page
- Contact message displayed
- No way to proceed to the signing form
---
### MT-5 — Guest declines and owner is notified
**Steps:**
1. Open a valid signing link
2. Click **Decline**
3. Confirm in the modal
**Expected:**
- "You have declined this signing request." page
- Participant status in session changes to DECLINED
- Session owner sees participant marked as declined in the session view
---
### MT-6 — Duplicate submission prevented
**Steps:**
1. Complete signing (MT-2)
2. Navigate back to the same `/sign/:token` URL
**Expected:**
- Page immediately shows the already-signed state ("Your signature has been submitted successfully.")
- No signing form is shown
---
### MT-7 — Email content security
**Steps:**
1. Create a session with a document named: `<img src=x onerror=alert(1)>.pdf`
2. Send invitation to a guest
**Expected:**
- Email subject: `Please sign: <img src=x onerror=alert(1)>.pdf` (angle brackets visible as text, not rendered)
- Email body: document name appears as text `&lt;img src=x onerror=alert(1)&gt;.pdf`
- No JavaScript executes in the email client
---
### MT-8 — Mobile / responsive layout
**Steps:**
1. Open the signing link on a mobile device or via browser DevTools responsive mode (375px width)
**Expected:**
- Page is usable at mobile width
- PDF preview, certificate chooser, and signature canvas are all visible and usable
- Buttons are appropriately sized for touch
---
### MT-9 — No-email configuration (mail disabled)
**Steps:**
1. Disable `mail.enabled` in config
2. Create a session with an external guest participant
**Expected:**
- Session creation succeeds
- No email is sent (no error in logs)
- Participant status remains `PENDING` (not `NOTIFIED`)
- Operator can still manually share the signing URL from the session detail view
---
## Config required
Add to your `settings.yml` (or environment variables):
```yaml
storage:
enabled: true # required for group signing
signing:
enabled: true # enables the signing session feature
mail:
enabled: true
host: smtp.example.com # your SMTP server
port: 587
username: stirling@example.com
password: your-smtp-password
from: noreply@stirling-pdf.example.com
startTlsEnable: true # recommended; use sslEnable: true + port 465 for implicit TLS
```
### Local development with MailHog
MailHog provides a local SMTP server with a web UI at `http://localhost:8025`.
```bash
# Start MailHog (Docker)
docker run -d -p 1025:1025 -p 8025:8025 mailhog/mailhog
# settings.yml for local dev
mail:
enabled: true
host: localhost
port: 1025
username: ""
password: ""
from: test@stirling-pdf.local
startTlsEnable: false
```
### Environment variable equivalents
```
STIRLING_STORAGE_ENABLED=true
STIRLING_STORAGE_SIGNING_ENABLED=true
MAIL_ENABLED=true
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=stirling@example.com
MAIL_PASSWORD=secret
MAIL_FROM=noreply@stirling-pdf.example.com
MAIL_STARTTLS_ENABLE=true
```
-78
View File
@@ -45,84 +45,6 @@ export function f2() { /* ... */ } // Custom desktop implementation
Building with this pattern minimises the duplicated code in the system and greatly reduces the chances that changing the core app will break the desktop app.
### Naming extension modules
Extension modules and the functions/hooks they export should be named after **what they do**, not **which build overrides them**.
Core code must never reference build targets (desktop, saas, etc.) by name — it should simply call a generic extension point and remain unaware of which layer is providing the implementation.
```ts
// ✅ CORRECT - named after the behaviour, not the build
// core/useFrontendVersionInfo.ts
export function useFrontendVersionInfo() { /* stub */ }
// desktop/useFrontendVersionInfo.ts
export function useFrontendVersionInfo() { /* real Tauri implementation */ }
```
```ts
// ❌ WRONG - core code reveals knowledge of the desktop layer
// core/useDesktopVersionInfo.ts
export function useDesktopVersionInfo() { /* stub */ }
```
Similarly, core code should never contain conditionals that check which build is active (e.g. `if (isDesktop)`).
If behaviour needs to vary, that variation belongs in an extension module - the core simply calls it.
The same principle applies in reverse: code inside `desktop/` is guaranteed to be running in the Tauri environment, so `isTauri()` checks are never needed there either.
If you find yourself writing `if (isDesktop())` or `if (isTauri())` anywhere, that is a sign the extension point has not been modelled correctly - the build system is already doing that separation for you.
### List extensions
When a build needs to _add_ behaviour rather than _replace_ it, the extension module can return a list of items and let core manage the rendering.
Core defines the function to return an empty list; the extension build overrides it to return a populated one.
```ts
// core/toolbarExtensions.ts
export interface ToolbarButton {
label: string;
onClick: () => void;
}
export function getToolbarButtons(): ToolbarButton[] {
return [];
}
```
```ts
// desktop/toolbarExtensions.ts
import { type ToolbarButton } from '@core/toolbarExtensions';
export { type ToolbarButton };
export function getToolbarButtons(): ToolbarButton[] {
return [
{ label: 'Open folder', onClick: () => { /* ... */ } },
];
}
```
```tsx
// core/Toolbar.tsx
import { getToolbarButtons } from '@app/toolbarExtensions';
export function Toolbar() {
return (
<div>
<button onClick={() => { /* ... */ }}>Download</button>
<button onClick={() => { /* ... */ }}>Print</button>
{getToolbarButtons().map((button) => (
<button key={button.label} onClick={button.onClick}>
{button.label}
</button>
))}
</div>
);
}
```
This pattern works well for things like menu items or toolbar actions - anything where a build contributes additional entries to a well-defined set.
### Import aliases
In general, all imports for app code should come via `@app` because it allows for other builds of the app to override behaviour if necessary.
The only time that it is beneficial to import via a specific folder (e.g. `@core`) is when you want to reduce duplication **in the file you are overriding**. For example:
+5 -30
View File
@@ -13,11 +13,6 @@ const nodeGlobs = [
'*.config.{js,ts,mjs}',
];
const baseRestrictedImportPatterns = [
{ regex: '^\\.', message: "Use @app/* imports instead of relative imports." },
{ regex: '^src/', message: "Use @app/* imports instead of absolute src/ imports." },
];
export default defineConfig(
{
// Everything that contains 3rd party code that we don't want to lint
@@ -35,7 +30,10 @@ export default defineConfig(
'no-restricted-imports': [
'error',
{
patterns: baseRestrictedImportPatterns,
patterns: [
".*", // Disallow any relative imports (they should be '@app/x/y/z' or similar)
"src/*", // Disallow any absolute imports (they should be '@app/x/y/z' or similar)
],
},
],
'@typescript-eslint/no-empty-object-type': [
@@ -61,32 +59,9 @@ export default defineConfig(
],
},
},
// Desktop-only packages must not be imported from core or proprietary code.
// Use the stub/shadow pattern instead: define a stub in src/core/ and override in src/desktop/.
{
files: srcGlobs,
ignores: ['src/desktop/**'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
...baseRestrictedImportPatterns,
{
regex: '^@tauri-apps/',
message: "Tauri APIs are desktop-only. Review frontend/DeveloperGuide.md for structure advice.",
},
],
},
],
},
},
// Folders that have been cleaned up and are now conformant - stricter rules enforced here
{
files: [
'src/proprietary/**/*.{js,mjs,jsx,ts,tsx}',
'src/saas/**/*.{js,mjs,jsx,ts,tsx}',
],
files: ['src/saas/**/*.{js,mjs,jsx,ts,tsx}'],
languageOptions: {
parserOptions: {
project: true,
+3 -3
View File
@@ -19,7 +19,7 @@ export default defineConfig({
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:5173',
baseURL: 'http://localhost:5174',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
@@ -68,8 +68,8 @@ export default defineConfig({
/* Run your local dev server before starting the tests */
webServer: {
command: 'npm run dev',
url: 'http://localhost:5173',
command: 'npm run dev -- --port 5174',
url: 'http://localhost:5174',
reuseExistingServer: !process.env.CI,
},
});
+41 -24
View File
@@ -3750,10 +3750,20 @@ selectedFile = "Selected document"
title = "Select Document"
[groupSigning.steps.selectParticipants]
addEmail = "Add"
badgeExternal = "Guest"
badgeRegistered = "User"
continue = "Continue to Signature Settings"
count = "{{count}} participant(s) selected"
count = "{{count}} participant(s)"
duplicateEmail = "This email has already been added"
emailInviteNote = "External participants will receive an email invitation with a signing link."
emailPlaceholder = "signer@example.com"
externalNote = "An invitation email will be sent with a signing link. No account required."
invalidEmail = "Please enter a valid email address"
label = "Select participants"
placeholder = "Choose participants to sign..."
tabExternal = "External (by email)"
tabRegistered = "Registered Users"
title = "Choose Participants"
[getPdfInfo]
@@ -3868,6 +3878,35 @@ message = "Create a free account to save your work, access more features, and su
signUp = "Sign Up Free"
title = "You're using Stirling PDF as a guest!"
[guestSigning]
certAutoNote = "A certificate will be generated using your email address for traceability."
certChoiceAuto = "Use auto-generated certificate (recommended)"
certChoiceUpload = "Upload my own certificate"
certFileLabel = "Certificate file (.p12 / .pfx)"
certFilePlaceholder = "Select .p12 or .pfx file"
certFileRequired = "Please select a certificate file."
certPasswordLabel = "Certificate password"
certPasswordPlaceholder = "Enter certificate password"
certSectionTitle = "Signing Certificate"
declineButton = "Decline"
declineConfirmBody = "Are you sure you want to decline? This action cannot be undone."
declineConfirmTitle = "Decline signing?"
declinedNote = "The document owner has been notified. You may close this window."
declineSuccess = "You have declined this signing request."
documentPreview = "Document"
dueDate = "Due {{date}}"
errorTitle = "Something went wrong"
expiredNote = "Please contact the document owner for a new link."
expiredToken = "This signing link has expired."
loadingSession = "Loading signing session..."
pageTitle = "Sign Document"
requestedBy = "Requested by {{owner}}"
signatureTitle = "Your Signature"
signedNote = "The document owner has been notified. You may close this window."
submitButton = "Submit Signature"
submitError = "Failed to submit signature."
submitSuccess = "Your signature has been submitted successfully."
[home]
alphabetical = "Alphabetical"
desc = "Your locally hosted one-stop-shop for all your PDF needs."
@@ -4856,7 +4895,7 @@ enableSepiaFilter = "Enable Sepia Filter"
firstPage = "First Page"
lastPage = "Last Page"
nextPage = "Next Page"
onlyPdfSupported = "This file format is not supported for preview."
onlyPdfSupported = "The viewer only supports PDF files. This file appears to be a different format."
previousPage = "Previous Page"
singlePageView = "Single Page View"
unknownFile = "Unknown file"
@@ -4864,21 +4903,6 @@ zoomIn = "Zoom In"
zoomOut = "Zoom Out"
resetZoom = "Reset zoom"
[viewer.nonPdf]
fileTypeBadge = "{{type}} File"
convertToPdf = "Convert to PDF"
loading = "Loading..."
emptyFile = "Empty file"
csvStats = "{{rows}} rows · {{columns}} columns · {{size}}"
sortedBy = "Sorted by: {{column}}"
columnDefault = "Column {{index}}"
htmlPreviewWarning = "HTML preview — external resources may not load · {{size}}"
htmlPreview = "HTML preview"
invalidJson = "Invalid JSON — showing raw content"
textStats = "{{lines}} lines · {{size}}"
lineNumbers = "Line numbers"
renderMarkdown = "Render markdown"
[rightRail]
closeSelected = "Close Selected Files"
selectAll = "Select All"
@@ -4896,7 +4920,6 @@ toggleAttachments = "Toggle Attachments"
toggleTheme = "Toggle Theme"
language = "Language"
toggleAnnotations = "Toggle Annotations Visibility"
toggleLayers = "Toggle Layers"
search = "Search PDF"
panMode = "Pan Mode"
applyRedactionsFirst = "Apply redactions first"
@@ -7994,7 +8017,6 @@ activeSession = "Active session"
addMembers = "Add Members"
admin = "Admin"
confirmDelete = "Are you sure you want to delete this user? This action cannot be undone."
confirmUnlock = "Are you sure you want to unlock this user account?"
deleteUser = "Delete User"
deleteUserError = "Failed to delete user"
deleteUserSuccess = "User deleted successfully"
@@ -8003,8 +8025,6 @@ disable = "Disable"
disabled = "Disabled"
editRole = "Edit Role"
enable = "Enable"
locked = "locked"
lockedBadge = "Locked"
loading = "Loading people..."
loginRequired = "Enable login mode first"
member = "Member"
@@ -8014,9 +8034,6 @@ searchMembers = "Search members..."
status = "Status"
team = "Team"
title = "People"
unlockAccount = "Unlock Account"
unlockUserError = "Failed to unlock user account"
unlockUserSuccess = "User account unlocked successfully"
user = "User"
[workspace.people.actions]
File diff suppressed because it is too large Load Diff
@@ -5,7 +5,6 @@ import {
import { Dropzone } from '@mantine/dropzone';
import { useFileSelection, useFileState, useFileManagement, useFileActions, useFileContext } from '@app/contexts/FileContext';
import { useNavigationActions } from '@app/contexts/NavigationContext';
import { useViewer } from '@app/contexts/ViewerContext';
import { zipFileService } from '@app/services/zipFileService';
import { detectFileExtension } from '@app/utils/fileUtils';
import FileEditorThumbnail from '@app/components/fileEditor/FileEditorThumbnail';
@@ -52,9 +51,6 @@ const FileEditor = ({
// Get navigation actions
const { actions: navActions } = useNavigationActions();
// Get viewer context for setting active file index
const { setActiveFileIndex } = useViewer();
// Get file selection context
const { setSelectedFiles } = useFileSelection();
@@ -349,14 +345,13 @@ const FileEditor = ({
}, [activeStirlingFileStubs, selectors, fileActions, removeFiles]);
const handleViewFile = useCallback((fileId: FileId) => {
const index = activeStirlingFileStubs.findIndex(r => r.id === fileId);
if (index !== -1) {
// Set the file as selected in context, sync the viewer index, and switch to viewer
const record = activeStirlingFileStubs.find(r => r.id === fileId);
if (record) {
// Set the file as selected in context and switch to viewer for preview
setSelectedFiles([fileId]);
setActiveFileIndex(index);
navActions.setWorkbench('viewer');
}
}, [activeStirlingFileStubs, setSelectedFiles, setActiveFileIndex, navActions.setWorkbench]);
}, [activeStirlingFileStubs, setSelectedFiles, navActions.setWorkbench]);
const handleLoadFromStorage = useCallback(async (selectedFiles: File[]) => {
if (selectedFiles.length === 0) return;
@@ -19,8 +19,6 @@ import AllToolsNavButton from '@app/components/shared/AllToolsNavButton';
import ActiveToolButton from "@app/components/shared/quickAccessBar/ActiveToolButton";
import AppConfigModal from '@app/components/shared/AppConfigModal';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useGroupSigningEnabled } from '@app/hooks/useGroupSigningEnabled';
import { useSharingEnabled } from '@app/hooks/useSharingEnabled';
import { useLicenseAlert } from "@app/hooks/useLicenseAlert";
import { requestStartTour } from '@app/constants/events';
import QuickAccessButton from '@app/components/shared/quickAccessBar/QuickAccessButton';
@@ -79,8 +77,9 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
const accessButtonRef = useRef<HTMLDivElement>(null);
const accessPopoverRef = useRef<HTMLDivElement>(null);
const [accessPopoverPosition, setAccessPopoverPosition] = useState({ top: 160, left: 84 });
const { sharingEnabled, shareLinksEnabled } = useSharingEnabled();
const groupSigningEnabled = useGroupSigningEnabled();
const sharingEnabled = config?.storageSharingEnabled === true;
const shareLinksEnabled = config?.storageShareLinksEnabled === true;
const groupSigningEnabled = config?.storageGroupSigningEnabled === true;
const isSignWorkbenchActive =
currentWorkbench === SIGN_REQUEST_WORKBENCH_TYPE ||
currentWorkbench === SESSION_DETAIL_WORKBENCH_TYPE;
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react";
import {
Paper,
Stack,
@@ -22,7 +22,8 @@ import type { ToolPanelMode } from "@app/constants/toolPanel";
import LocalIcon from "@app/components/shared/LocalIcon";
import { updateService, UpdateSummary } from "@app/services/updateService";
import UpdateModal from "@app/components/shared/UpdateModal";
import { useFrontendVersionInfo } from "@app/hooks/useFrontendVersionInfo";
import { getVersion } from "@tauri-apps/api/app";
import { isTauri } from "@tauri-apps/api/core";
const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;
const BANNER_DISMISSED_KEY = "stirlingpdf_features_banner_dismissed";
@@ -45,8 +46,10 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
const [updateSummary, setUpdateSummary] = useState<UpdateSummary | null>(null);
const [updateModalOpened, setUpdateModalOpened] = useState(false);
const [checkingUpdate, setCheckingUpdate] = useState(false);
const { appVersion, mismatchVersion } = useFrontendVersionInfo(config?.appVersion);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading..."); // null = loading, shown only when appVersion !== undefined
const [mismatchVersion, setMismatchVersion] = useState(false);
const isTauriApp = useMemo(() => isTauri(), []);
const [appVersion, setAppVersion] = useState<string | null>(null);
const frontendVersionLabel = appVersion ?? t("common.loading", "Loading...");
// Sync local state with preference changes
useEffect(() => {
@@ -88,6 +91,52 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
setCheckingUpdate(false);
};
useEffect(() => {
if (!isTauriApp) {
setMismatchVersion(false);
return;
}
let cancelled = false;
const fetchFrontendVersion = async () => {
try {
const frontendVersion = await getVersion();
if (!cancelled) {
setAppVersion(frontendVersion);
}
} catch (error) {
console.error("[GeneralSection] Failed to fetch frontend version:", error);
}
};
fetchFrontendVersion();
return () => {
cancelled = true;
};
}, [isTauriApp]);
useEffect(() => {
if (!isTauriApp) {
return;
}
if (!appVersion || !config?.appVersion) {
setMismatchVersion(false);
return;
}
if (appVersion !== config.appVersion) {
console.warn("[GeneralSection] Mismatch between Tauri version and AppConfig version:", {
backendVersion: config.appVersion,
frontendVersion: appVersion,
});
setMismatchVersion(true);
} else {
setMismatchVersion(false);
}
}, [isTauriApp, appVersion, config?.appVersion]);
// Check if login is disabled
const loginDisabled = !config?.enableLogin;
@@ -190,7 +239,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
)}
</Group>
</div>
{appVersion !== undefined && (
{isTauriApp && (
<Group justify="space-between" align="center">
<div>
<Text size="sm" c="dimmed">
@@ -3,7 +3,10 @@ import { Stack, Text, Group, Badge } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import CheckIcon from '@mui/icons-material/Check';
import { SelectDocumentStep } from '@app/components/shared/signing/steps/SelectDocumentStep';
import { SelectParticipantsStep } from '@app/components/shared/signing/steps/SelectParticipantsStep';
import {
SelectParticipantsStep,
type Participant,
} from '@app/components/shared/signing/steps/SelectParticipantsStep';
import { ConfigureSignatureDefaultsStep } from '@app/components/shared/signing/steps/ConfigureSignatureDefaultsStep';
import { ReviewSessionStep } from '@app/components/shared/signing/steps/ReviewSessionStep';
import { useGroupSigningTips } from '@app/components/tooltips/useGroupSigningTips';
@@ -13,8 +16,8 @@ import type { FileState } from '@app/types/file';
interface CreateSessionFlowProps {
selectedFiles: FileState[];
selectedUserIds: number[];
onSelectedUserIdsChange: (userIds: number[]) => void;
participants: Participant[];
onParticipantsChange: (participants: Participant[]) => void;
dueDate: string;
onDueDateChange: (date: string) => void;
creating: boolean;
@@ -102,8 +105,8 @@ const StepWrapper: React.FC<StepWrapperProps> = ({
export const CreateSessionFlow: React.FC<CreateSessionFlowProps> = ({
selectedFiles,
selectedUserIds,
onSelectedUserIdsChange,
participants,
onParticipantsChange,
dueDate,
onDueDateChange,
creating,
@@ -186,8 +189,8 @@ export const CreateSessionFlow: React.FC<CreateSessionFlowProps> = ({
isCompleted={currentStep > 2}
>
<SelectParticipantsStep
selectedUserIds={selectedUserIds}
onSelectedUserIdsChange={onSelectedUserIdsChange}
participants={participants}
onParticipantsChange={onParticipantsChange}
onBack={() => setCurrentStep(1)}
onNext={() => setCurrentStep(3)}
disabled={creating}
@@ -220,7 +223,7 @@ export const CreateSessionFlow: React.FC<CreateSessionFlowProps> = ({
{selectedFile && (
<ReviewSessionStep
selectedFile={selectedFile}
participantCount={selectedUserIds.length}
participantCount={participants.length}
signatureSettings={signatureSettings}
dueDate={dueDate}
onDueDateChange={onDueDateChange}
@@ -1,12 +1,17 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Text, Switch } from '@mantine/core';
import { ActionIcon, Badge, Group, Switch, Tabs, Text, TextInput } from '@mantine/core';
import CloseIcon from '@mui/icons-material/Close';
import PersonIcon from '@mui/icons-material/Person';
import EmailIcon from '@mui/icons-material/Email';
import UserSelector from '@app/components/shared/UserSelector';
import type { Participant } from '@app/components/shared/signing/steps/SelectParticipantsStep';
import type { FileState } from '@app/types/file';
interface CreateSessionPanelProps {
selectedFiles: FileState[];
selectedUserIds: number[];
onSelectedUserIdsChange: (userIds: number[]) => void;
participants: Participant[];
onParticipantsChange: (participants: Participant[]) => void;
dueDate: string;
onDueDateChange: (date: string) => void;
creating: boolean;
@@ -14,10 +19,12 @@ interface CreateSessionPanelProps {
onIncludeSummaryPageChange: (value: boolean) => void;
}
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const CreateSessionPanel = ({
selectedFiles,
selectedUserIds,
onSelectedUserIdsChange,
participants,
onParticipantsChange,
dueDate,
onDueDateChange,
creating,
@@ -25,9 +32,40 @@ const CreateSessionPanel = ({
onIncludeSummaryPageChange,
}: CreateSessionPanelProps) => {
const { t } = useTranslation();
const [emailInput, setEmailInput] = useState('');
const hasValidFile = selectedFiles.length === 1;
const registeredUserIds = participants
.filter((p) => p.type === 'registered' && p.userId != null)
.map((p) => p.userId as number);
function handleRegisteredChange(userIds: number[]) {
const external = participants.filter((p) => p.type === 'external');
onParticipantsChange([
...userIds.map((id): Participant => ({ type: 'registered', userId: id })),
...external,
]);
}
function handleAddEmail() {
const trimmed = emailInput.trim();
if (!EMAIL_RE.test(trimmed)) return;
if (participants.some((p) => p.email === trimmed)) return;
onParticipantsChange([...participants, { type: 'external', email: trimmed }]);
setEmailInput('');
}
function handleRemove(participant: Participant) {
onParticipantsChange(
participants.filter((p) =>
participant.type === 'registered'
? !(p.type === 'registered' && p.userId === participant.userId)
: !(p.type === 'external' && p.email === participant.email)
)
);
}
return (
<div className="quick-access-popout__panel">
{!hasValidFile ? (
@@ -46,14 +84,89 @@ const CreateSessionPanel = ({
</div>
<div className="quick-access-popout__section">
<div className="quick-access-popout__label">{t('quickAccess.selectUsers', 'Select users to sign')}</div>
<UserSelector
value={selectedUserIds}
onChange={onSelectedUserIdsChange}
size="xs"
placeholder={t('quickAccess.selectUsersPlaceholder', 'Choose participants...')}
disabled={creating}
/>
<div className="quick-access-popout__label">{t('quickAccess.selectUsers', 'Select participants to sign')}</div>
<Tabs defaultValue="registered" style={{ marginBottom: 8 }}>
<Tabs.List>
<Tabs.Tab value="registered" leftSection={<PersonIcon sx={{ fontSize: 13 }} />} style={{ fontSize: 11, padding: '4px 8px' }}>
{t('groupSigning.steps.selectParticipants.tabRegistered', 'Registered')}
</Tabs.Tab>
<Tabs.Tab value="external" leftSection={<EmailIcon sx={{ fontSize: 13 }} />} style={{ fontSize: 11, padding: '4px 8px' }}>
{t('groupSigning.steps.selectParticipants.tabExternal', 'External')}
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="registered" pt="xs">
<UserSelector
value={registeredUserIds}
onChange={handleRegisteredChange}
size="xs"
placeholder={t('quickAccess.selectUsersPlaceholder', 'Choose participants...')}
disabled={creating}
/>
</Tabs.Panel>
<Tabs.Panel value="external" pt="xs">
<Group gap="xs" align="center">
<TextInput
style={{ flex: 1 }}
size="xs"
placeholder="signer@example.com"
value={emailInput}
onChange={(e) => setEmailInput(e.currentTarget.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddEmail();
}
}}
disabled={creating}
/>
<button
type="button"
className="quick-access-popout__secondary"
onClick={handleAddEmail}
disabled={creating || !EMAIL_RE.test(emailInput.trim())}
style={{ padding: '4px 8px', fontSize: 12 }}
>
{t('groupSigning.steps.selectParticipants.addEmail', 'Add')}
</button>
</Group>
</Tabs.Panel>
</Tabs>
{/* Combined participant list */}
{participants.length > 0 && (
<div style={{ marginTop: 4 }}>
{participants.map((p, i) => (
<Group key={i} gap={4} justify="space-between" wrap="nowrap" style={{ marginBottom: 2 }}>
<Group gap={4} style={{ flex: 1, minWidth: 0 }}>
<Badge
variant="light"
color={p.type === 'external' ? 'orange' : 'blue'}
size="xs"
>
{p.type === 'external'
? t('groupSigning.steps.selectParticipants.badgeExternal', 'Guest')
: t('groupSigning.steps.selectParticipants.badgeRegistered', 'User')}
</Badge>
<Text size="xs" style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
{p.type === 'external' ? p.email : `#${p.userId}`}
</Text>
</Group>
<ActionIcon
variant="subtle"
color="red"
size="xs"
onClick={() => handleRemove(p)}
disabled={creating}
>
<CloseIcon sx={{ fontSize: 12 }} />
</ActionIcon>
</Group>
))}
</div>
)}
</div>
<div className="quick-access-popout__section">
@@ -0,0 +1,82 @@
import { Alert, FileInput, PasswordInput, Radio, Stack, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
export type GuestCertType = 'GUEST_CERT' | 'P12';
interface GuestCertificateChooserProps {
value: GuestCertType;
onChange: (certType: GuestCertType) => void;
onFileChange: (file: File | null) => void;
onPasswordChange: (password: string) => void;
p12File: File | null;
password: string;
}
export const GuestCertificateChooser: React.FC<GuestCertificateChooserProps> = ({
value,
onChange,
onFileChange,
onPasswordChange,
p12File,
password,
}) => {
const { t } = useTranslation();
return (
<Stack gap="sm">
<Text fw={500} size="sm">
{t('guestSigning.certSectionTitle', 'Signing Certificate')}
</Text>
<Radio.Group
value={value}
onChange={(val) => {
onChange(val as GuestCertType);
// Clear uploaded file when switching back to auto
if (val === 'GUEST_CERT') {
onFileChange(null);
onPasswordChange('');
}
}}
>
<Stack gap="xs">
<Radio
value="GUEST_CERT"
label={t('guestSigning.certChoiceAuto', 'Use auto-generated certificate (recommended)')}
/>
<Radio
value="P12"
label={t('guestSigning.certChoiceUpload', 'Upload my own certificate')}
/>
</Stack>
</Radio.Group>
{value === 'GUEST_CERT' && (
<Alert color="blue" variant="light">
{t(
'guestSigning.certAutoNote',
'A certificate will be generated using your email address for traceability.'
)}
</Alert>
)}
{value === 'P12' && (
<Stack gap="xs">
<FileInput
label={t('guestSigning.certFileLabel', 'Certificate file (.p12 / .pfx)')}
placeholder={t('guestSigning.certFilePlaceholder', 'Select .p12 or .pfx file')}
accept=".p12,.pfx"
value={p12File}
onChange={onFileChange}
/>
<PasswordInput
label={t('guestSigning.certPasswordLabel', 'Certificate password')}
placeholder={t('guestSigning.certPasswordPlaceholder', 'Enter certificate password')}
value={password}
onChange={(e) => onPasswordChange(e.currentTarget.value)}
/>
</Stack>
)}
</Stack>
);
};
@@ -82,7 +82,7 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
const [loading, setLoading] = useState(false);
// Create form state
const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
const [participants, setParticipants] = useState<import('@app/components/shared/signing/steps/SelectParticipantsStep').Participant[]>([]);
const [dueDate, setDueDate] = useState('');
const [creating, setCreating] = useState(false);
const [includeSummaryPage, setIncludeSummaryPage] = useState(false);
@@ -309,7 +309,7 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
// Create session handler
const handleCreateSession = useCallback(async () => {
if (selectedUserIds.length === 0 || selectedFiles.length !== 1) return;
if (participants.length === 0 || selectedFiles.length !== 1) return;
setCreating(true);
try {
@@ -321,8 +321,13 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
formData.append('file', stirlingFile, selectedFile.name);
formData.append('workflowType', 'SIGNING');
formData.append('documentName', selectedFile.name);
selectedUserIds.forEach((userId, index) => {
formData.append(`participantUserIds[${index}]`, userId.toString());
const registeredIds = participants.filter((p) => p.type === 'registered' && p.userId != null);
const externalEmails = participants.filter((p) => p.type === 'external' && p.email != null);
registeredIds.forEach((p, index) => {
formData.append(`participantUserIds[${index}]`, (p.userId as number).toString());
});
externalEmails.forEach((p, index) => {
formData.append(`participantEmails[${index}]`, p.email as string);
});
if (dueDate) formData.append('dueDate', dueDate);
formData.append('notifyOnCreate', 'true');
@@ -335,7 +340,9 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
formData.append('workflowMetadata', workflowMetadata);
}
await apiClient.post('/api/v1/security/cert-sign/sessions', formData);
await apiClient.post('/api/v1/security/cert-sign/sessions', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
alert({
alertType: 'success',
@@ -362,7 +369,7 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
} finally {
setCreating(false);
}
}, [selectedUserIds, dueDate, selectedFiles, fetchData, t, includeSummaryPage]);
}, [participants, dueDate, selectedFiles, fetchData, t, includeSummaryPage]);
// Handle clicking a sign request
const handleSignRequestClick = useCallback(async (request: SignRequestSummary) => {
@@ -463,8 +470,8 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
pdfFile,
onFinalize: () => handleFinalize(session.sessionId, session.documentName),
onLoadSignedPdf: () => handleLoadSignedPdf(session.sessionId, session.documentName),
onAddParticipants: (userIds: number[], defaultReason?: string) =>
handleAddParticipants(session.sessionId, userIds, defaultReason),
onAddParticipants: (userIds: number[], emails: string[], defaultReason?: string) =>
handleAddParticipants(session.sessionId, userIds, emails, defaultReason),
onRemoveParticipant: (participantId: number) => handleRemoveParticipant(session.sessionId, participantId),
onDelete: () => handleDeleteSession(session.sessionId),
onBack: () => {
@@ -491,7 +498,9 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
// Action handlers
const handleSign = async (sessionId: string, certificateData: FormData) => {
await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`, certificateData);
await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`, certificateData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
alert({
alertType: 'success',
title: t('success'),
@@ -562,12 +571,19 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
navigationActions.setWorkbench('viewer');
};
const handleAddParticipants = async (sessionId: string, userIds: number[], defaultReason?: string) => {
const requests = userIds.map(userId => ({
userId,
defaultReason: defaultReason || undefined,
sendNotification: true,
}));
const handleAddParticipants = async (sessionId: string, userIds: number[], emails: string[], defaultReason?: string) => {
const requests = [
...userIds.map(userId => ({
userId,
defaultReason: defaultReason || undefined,
sendNotification: true,
})),
...emails.map(email => ({
email,
defaultReason: defaultReason || undefined,
sendNotification: true,
})),
];
await apiClient.post(`/api/v1/security/cert-sign/sessions/${sessionId}/participants`, requests);
await handleRefreshSession(sessionId);
};
@@ -746,8 +762,8 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
{showCreatePanel ? (
<CreateSessionPanel
selectedFiles={selectedFiles}
selectedUserIds={selectedUserIds}
onSelectedUserIdsChange={setSelectedUserIds}
participants={participants}
onParticipantsChange={setParticipants}
dueDate={dueDate}
onDueDateChange={setDueDate}
creating={creating}
@@ -789,7 +805,7 @@ const SignPopout = ({ isOpen, onClose, buttonRef, isRTL, groupSigningEnabled }:
type="button"
className="quick-access-popout__primary"
onClick={handleCreateSession}
disabled={selectedFiles.length !== 1 || selectedUserIds.length === 0 || creating}
disabled={selectedFiles.length !== 1 || participants.length === 0 || creating}
>
<LocalIcon icon="send-rounded" width="1rem" height="1rem" />
{creating
@@ -0,0 +1,317 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MantineProvider } from '@mantine/core';
// ── i18n ────────────────────────────────────────────────────────────────────
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, fallback?: string | Record<string, unknown>) => {
if (typeof fallback === 'string') return fallback;
if (typeof fallback === 'object' && fallback !== null) {
// Handle interpolation like {{count}}
const defaultValue = (fallback as Record<string, unknown>).defaultValue;
if (typeof defaultValue === 'string') return defaultValue;
}
return key;
},
}),
initReactI18next: { type: '3rdParty', init: vi.fn() },
}));
// ── UserSelector stub — renders a simple multi-select ───────────────────────
vi.mock('@app/components/shared/UserSelector', () => ({
default: ({
value,
onChange,
}: {
value: number[];
onChange: (ids: number[]) => void;
}) => (
<div data-testid="user-selector">
<button onClick={() => onChange([...value, 42])}>Add User 42</button>
<button onClick={() => onChange([])}>Clear Users</button>
<span data-testid="user-count">{value.length}</span>
</div>
),
}));
// ── MUI icons stub (to avoid SVG transform issues in jsdom) ─────────────────
vi.mock('@mui/icons-material/ArrowBack', () => ({ default: () => null }));
vi.mock('@mui/icons-material/Close', () => ({ default: () => null }));
vi.mock('@mui/icons-material/Person', () => ({ default: () => null }));
vi.mock('@mui/icons-material/Email', () => ({ default: () => null }));
// ── Component under test ────────────────────────────────────────────────────
import { SelectParticipantsStep, Participant } from './SelectParticipantsStep';
// ── Test wrapper ────────────────────────────────────────────────────────────
const TestWrapper = ({ children }: { children: React.ReactNode }) => (
<MantineProvider>{children}</MantineProvider>
);
// ── Default props ───────────────────────────────────────────────────────────
function makeProps(overrides?: Partial<{
participants: Participant[];
onParticipantsChange: (p: Participant[]) => void;
onBack: () => void;
onNext: () => void;
}>) {
return {
participants: [] as Participant[],
onParticipantsChange: vi.fn(),
onBack: vi.fn(),
onNext: vi.fn(),
...overrides,
};
}
// ── Tests ───────────────────────────────────────────────────────────────────
describe('SelectParticipantsStep', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the registered users tab by default', () => {
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps()} />
</TestWrapper>
);
expect(screen.getByText('Registered Users')).toBeInTheDocument();
expect(screen.getByTestId('user-selector')).toBeInTheDocument();
});
it('renders the external tab', () => {
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps()} />
</TestWrapper>
);
expect(screen.getByText('External (by email)')).toBeInTheDocument();
});
it('Continue button is disabled when participants list is empty', () => {
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps({ participants: [] })} />
</TestWrapper>
);
const continueBtn = screen.getByText('Continue to Signature Settings');
expect(continueBtn.closest('button')).toBeDisabled();
});
it('Continue button is enabled when participants list has entries', () => {
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'alice@example.com' }],
})}
/>
</TestWrapper>
);
const continueBtn = screen.getByText('Continue to Signature Settings');
expect(continueBtn.closest('button')).not.toBeDisabled();
});
it('adds external email to participant list on Add button click', async () => {
const user = userEvent.setup();
const onParticipantsChange = vi.fn();
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({ onParticipantsChange })}
/>
</TestWrapper>
);
// Switch to external tab
await user.click(screen.getByText('External (by email)'));
const input = screen.getByPlaceholderText('signer@example.com');
await user.type(input, 'new@example.com');
await user.click(screen.getByText('Add'));
expect(onParticipantsChange).toHaveBeenCalledWith([
{ type: 'external', email: 'new@example.com' },
]);
});
it('adds external email on Enter keypress', async () => {
const user = userEvent.setup();
const onParticipantsChange = vi.fn();
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps({ onParticipantsChange })} />
</TestWrapper>
);
await user.click(screen.getByText('External (by email)'));
const input = screen.getByPlaceholderText('signer@example.com');
await user.type(input, 'enter@example.com{Enter}');
expect(onParticipantsChange).toHaveBeenCalledWith([
{ type: 'external', email: 'enter@example.com' },
]);
});
it('shows validation error for invalid email format', async () => {
const user = userEvent.setup();
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps()} />
</TestWrapper>
);
await user.click(screen.getByText('External (by email)'));
const input = screen.getByPlaceholderText('signer@example.com');
await user.type(input, 'not-an-email');
await user.click(screen.getByText('Add'));
expect(screen.getByText('Please enter a valid email address')).toBeInTheDocument();
});
it('shows duplicate email error when same email is added twice', async () => {
const user = userEvent.setup();
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'existing@example.com' }],
})}
/>
</TestWrapper>
);
await user.click(screen.getByText('External (by email)'));
const input = screen.getByPlaceholderText('signer@example.com');
await user.type(input, 'existing@example.com');
await user.click(screen.getByText('Add'));
expect(screen.getByText('This email has already been added')).toBeInTheDocument();
});
it('displays external participants as Guest badges', () => {
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'guest@example.com' }],
})}
/>
</TestWrapper>
);
expect(screen.getByText('guest@example.com')).toBeInTheDocument();
expect(screen.getByText('Guest')).toBeInTheDocument();
});
it('removes participant when close button is clicked', () => {
const onParticipantsChange = vi.fn();
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'remove@example.com' }],
onParticipantsChange,
})}
/>
</TestWrapper>
);
// The remove action icon
const removeButtons = screen.getAllByRole('button');
const removeBtn = removeButtons.find(
(btn) => btn.getAttribute('data-variant') === 'subtle'
);
expect(removeBtn).toBeDefined();
fireEvent.click(removeBtn!);
expect(onParticipantsChange).toHaveBeenCalledWith([]);
});
it('shows email invite alert when external participants are present', () => {
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'invited@example.com' }],
})}
/>
</TestWrapper>
);
expect(
screen.getByText(/External participants will receive an email invitation/i)
).toBeInTheDocument();
});
it('does not show email invite alert when only registered users are present', () => {
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'registered', userId: 1 }],
})}
/>
</TestWrapper>
);
expect(
screen.queryByText(/External participants will receive an email invitation/i)
).not.toBeInTheDocument();
});
it('calls onBack when Back button is clicked', async () => {
const user = userEvent.setup();
const onBack = vi.fn();
render(
<TestWrapper>
<SelectParticipantsStep {...makeProps({ onBack })} />
</TestWrapper>
);
await user.click(screen.getByText('Back'));
expect(onBack).toHaveBeenCalledOnce();
});
it('calls onNext when Continue button is clicked with participants', async () => {
const user = userEvent.setup();
const onNext = vi.fn();
render(
<TestWrapper>
<SelectParticipantsStep
{...makeProps({
participants: [{ type: 'external', email: 'a@b.com' }],
onNext,
})}
/>
</TestWrapper>
);
await user.click(screen.getByText('Continue to Signature Settings'));
expect(onNext).toHaveBeenCalledOnce();
});
});
@@ -1,58 +1,234 @@
import { Button, Stack, Text, Group } from '@mantine/core';
import { useState } from 'react';
import {
ActionIcon,
Alert,
Badge,
Button,
Group,
Stack,
Tabs,
Text,
TextInput,
} from '@mantine/core';
import { useTranslation } from 'react-i18next';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import CloseIcon from '@mui/icons-material/Close';
import PersonIcon from '@mui/icons-material/Person';
import EmailIcon from '@mui/icons-material/Email';
import UserSelector from '@app/components/shared/UserSelector';
// ─── Shared participant model ─────────────────────────────────────────────────
export interface Participant {
type: 'registered' | 'external';
/** Present for registered users */
userId?: number;
/** Present for external/guest users */
email?: string;
name?: string;
}
// ─── Props ───────────────────────────────────────────────────────────────────
interface SelectParticipantsStepProps {
selectedUserIds: number[];
onSelectedUserIdsChange: (userIds: number[]) => void;
participants: Participant[];
onParticipantsChange: (participants: Participant[]) => void;
onBack: () => void;
onNext: () => void;
disabled?: boolean;
}
// ─── Email validation ─────────────────────────────────────────────────────────
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// ─── Component ───────────────────────────────────────────────────────────────
export const SelectParticipantsStep: React.FC<SelectParticipantsStepProps> = ({
selectedUserIds,
onSelectedUserIdsChange,
participants,
onParticipantsChange,
onBack,
onNext,
disabled = false,
}) => {
const { t } = useTranslation();
const hasParticipants = selectedUserIds.length > 0;
// External email input state
const [emailInput, setEmailInput] = useState('');
const [emailError, setEmailError] = useState('');
const registeredUserIds = participants
.filter((p) => p.type === 'registered' && p.userId != null)
.map((p) => p.userId as number);
function handleRegisteredChange(userIds: number[]) {
const external = participants.filter((p) => p.type === 'external');
const registered: Participant[] = userIds.map((id) => ({ type: 'registered', userId: id }));
onParticipantsChange([...registered, ...external]);
}
function handleAddEmail() {
const trimmed = emailInput.trim();
if (!EMAIL_RE.test(trimmed)) {
setEmailError(
t(
'groupSigning.steps.selectParticipants.invalidEmail',
'Please enter a valid email address'
)
);
return;
}
if (participants.some((p) => p.email === trimmed)) {
setEmailError(
t(
'groupSigning.steps.selectParticipants.duplicateEmail',
'This email has already been added'
)
);
return;
}
onParticipantsChange([...participants, { type: 'external', email: trimmed }]);
setEmailInput('');
setEmailError('');
}
function handleRemove(participant: Participant) {
onParticipantsChange(
participants.filter((p) =>
participant.type === 'registered'
? !(p.type === 'registered' && p.userId === participant.userId)
: !(p.type === 'external' && p.email === participant.email)
)
);
}
return (
<Stack gap="md">
<div>
<Text size="sm" c="dimmed" mb="xs">
{t('groupSigning.steps.selectParticipants.label', 'Select participants')}
</Text>
<UserSelector
value={selectedUserIds}
onChange={onSelectedUserIdsChange}
placeholder={t(
'groupSigning.steps.selectParticipants.placeholder',
'Choose participants to sign...'
)}
disabled={disabled}
/>
</div>
<Tabs defaultValue="registered">
<Tabs.List>
<Tabs.Tab value="registered" leftSection={<PersonIcon sx={{ fontSize: 16 }} />}>
{t('groupSigning.steps.selectParticipants.tabRegistered', 'Registered Users')}
</Tabs.Tab>
<Tabs.Tab value="external" leftSection={<EmailIcon sx={{ fontSize: 16 }} />}>
{t('groupSigning.steps.selectParticipants.tabExternal', 'External (by email)')}
</Tabs.Tab>
</Tabs.List>
{selectedUserIds.length > 0 && (
<Text size="xs" c="dimmed">
{t('groupSigning.steps.selectParticipants.count', {
count: selectedUserIds.length,
defaultValue: '{{count}} participant(s) selected',
})}
</Text>
<Tabs.Panel value="registered" pt="sm">
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t('groupSigning.steps.selectParticipants.label', 'Select participants')}
</Text>
<UserSelector
value={registeredUserIds}
onChange={handleRegisteredChange}
placeholder={t(
'groupSigning.steps.selectParticipants.placeholder',
'Choose participants to sign...'
)}
disabled={disabled}
/>
</Stack>
</Tabs.Panel>
<Tabs.Panel value="external" pt="sm">
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t(
'groupSigning.steps.selectParticipants.externalNote',
'An invitation email will be sent with a signing link. No account required.'
)}
</Text>
<Group gap="xs" align="flex-start">
<TextInput
style={{ flex: 1 }}
placeholder={t(
'groupSigning.steps.selectParticipants.emailPlaceholder',
'signer@example.com'
)}
value={emailInput}
onChange={(e) => {
setEmailInput(e.currentTarget.value);
if (emailError) setEmailError('');
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddEmail();
}
}}
error={emailError}
disabled={disabled}
/>
<Button onClick={handleAddEmail} disabled={disabled} style={{ marginTop: emailError ? 0 : 0 }}>
{t('groupSigning.steps.selectParticipants.addEmail', 'Add')}
</Button>
</Group>
</Stack>
</Tabs.Panel>
</Tabs>
{/* Combined participant list */}
{participants.length > 0 && (
<Stack gap="xs">
<Text size="xs" c="dimmed">
{t('groupSigning.steps.selectParticipants.count', {
count: participants.length,
defaultValue: '{{count}} participant(s)',
})}
</Text>
{participants.map((p, i) => (
<Group key={i} gap="xs" justify="space-between" wrap="nowrap">
<Group gap="xs" style={{ flex: 1, minWidth: 0 }}>
<Badge
variant="light"
color={p.type === 'external' ? 'orange' : 'blue'}
size="xs"
>
{p.type === 'external'
? t('groupSigning.steps.selectParticipants.badgeExternal', 'Guest')
: t('groupSigning.steps.selectParticipants.badgeRegistered', 'User')}
</Badge>
<Text size="sm" style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
{p.type === 'external' ? p.email : `User #${p.userId}`}
</Text>
</Group>
<ActionIcon
variant="subtle"
color="red"
size="sm"
onClick={() => handleRemove(p)}
disabled={disabled}
>
<CloseIcon sx={{ fontSize: 14 }} />
</ActionIcon>
</Group>
))}
</Stack>
)}
{participants.some((p) => p.type === 'external') && (
<Alert color="blue" variant="light" icon={<EmailIcon sx={{ fontSize: 16 }} />}>
{t(
'groupSigning.steps.selectParticipants.emailInviteNote',
'External participants will receive an email invitation with a signing link.'
)}
</Alert>
)}
<Group gap="sm">
<Button variant="default" onClick={onBack} leftSection={<ArrowBackIcon sx={{ fontSize: 16 }} />}>
<Button
variant="default"
onClick={onBack}
leftSection={<ArrowBackIcon sx={{ fontSize: 16 }} />}
>
{t('groupSigning.steps.back', 'Back')}
</Button>
<Button onClick={onNext} disabled={!hasParticipants || disabled} style={{ flex: 1 }}>
<Button
onClick={onNext}
disabled={participants.length === 0 || disabled}
style={{ flex: 1 }}
>
{t('groupSigning.steps.selectParticipants.continue', 'Continue to Signature Settings')}
</Button>
</Group>
@@ -21,7 +21,7 @@ export interface SessionDetailWorkbenchData {
pdfFile: File | null;
onFinalize: () => Promise<void>;
onLoadSignedPdf: () => Promise<void>;
onAddParticipants: (userIds: number[], defaultReason?: string) => Promise<void>;
onAddParticipants: (userIds: number[], emails: string[], defaultReason?: string) => Promise<void>;
onRemoveParticipant: (participantId: number) => Promise<void>;
onDelete: () => Promise<void>;
onBack: () => void;
@@ -67,9 +67,9 @@ const SessionDetailWorkbenchView = ({ data }: SessionDetailWorkbenchViewProps) =
}
}, [session.finalized, onRefresh]);
const handleAddParticipants = async (userIds: number[], defaultReason?: string) => {
const handleAddParticipants = async (userIds: number[], emails: string[], defaultReason?: string) => {
try {
await onAddParticipants(userIds, defaultReason);
await onAddParticipants(userIds, emails, defaultReason);
alert({
alertType: 'success',
title: t('success'),
@@ -1,13 +1,28 @@
import { useState } from 'react';
import { Modal, Stack, TextInput, Button, Group } from '@mantine/core';
import {
ActionIcon,
Badge,
Button,
Group,
Modal,
Stack,
Tabs,
Text,
TextInput,
} from '@mantine/core';
import { useTranslation } from 'react-i18next';
import AddIcon from '@mui/icons-material/Add';
import CloseIcon from '@mui/icons-material/Close';
import PersonIcon from '@mui/icons-material/Person';
import EmailIcon from '@mui/icons-material/Email';
import UserSelector from '@app/components/shared/UserSelector';
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
interface AddParticipantsFlowProps {
opened: boolean;
onClose: () => void;
onSubmit: (userIds: number[], defaultReason?: string) => Promise<void>;
onSubmit: (userIds: number[], emails: string[], defaultReason?: string) => Promise<void>;
}
export const AddParticipantsFlow: React.FC<AddParticipantsFlowProps> = ({
@@ -17,19 +32,52 @@ export const AddParticipantsFlow: React.FC<AddParticipantsFlowProps> = ({
}) => {
const { t } = useTranslation();
const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
const [externalEmails, setExternalEmails] = useState<string[]>([]);
const [emailInput, setEmailInput] = useState('');
const [emailError, setEmailError] = useState('');
const [defaultReason, setDefaultReason] = useState('');
const [submitting, setSubmitting] = useState(false);
const totalCount = selectedUserIds.length + externalEmails.length;
const handleClose = () => {
setSelectedUserIds([]);
setExternalEmails([]);
setEmailInput('');
setEmailError('');
setDefaultReason('');
onClose();
};
function handleAddEmail() {
const trimmed = emailInput.trim();
if (!EMAIL_RE.test(trimmed)) {
setEmailError(
t(
'groupSigning.steps.selectParticipants.invalidEmail',
'Please enter a valid email address'
)
);
return;
}
if (externalEmails.includes(trimmed)) {
setEmailError(
t(
'groupSigning.steps.selectParticipants.duplicateEmail',
'This email has already been added'
)
);
return;
}
setExternalEmails((prev) => [...prev, trimmed]);
setEmailInput('');
setEmailError('');
}
const handleSubmit = async () => {
setSubmitting(true);
try {
await onSubmit(selectedUserIds, defaultReason.trim() || undefined);
await onSubmit(selectedUserIds, externalEmails, defaultReason.trim() || undefined);
handleClose();
} catch (error) {
console.error('Failed to add participants:', error);
@@ -46,18 +94,87 @@ export const AddParticipantsFlow: React.FC<AddParticipantsFlowProps> = ({
size="lg"
>
<Stack gap="md">
<UserSelector
value={selectedUserIds}
onChange={setSelectedUserIds}
placeholder={t('certSign.collab.sessionDetail.selectUsers', 'Select users...')}
/>
<Tabs defaultValue="registered">
<Tabs.List>
<Tabs.Tab value="registered" leftSection={<PersonIcon sx={{ fontSize: 16 }} />}>
{t('groupSigning.steps.selectParticipants.tabRegistered', 'Registered Users')}
</Tabs.Tab>
<Tabs.Tab value="external" leftSection={<EmailIcon sx={{ fontSize: 16 }} />}>
{t('groupSigning.steps.selectParticipants.tabExternal', 'External (by email)')}
</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="registered" pt="sm">
<UserSelector
value={selectedUserIds}
onChange={setSelectedUserIds}
placeholder={t('certSign.collab.sessionDetail.selectUsers', 'Select users...')}
/>
</Tabs.Panel>
<Tabs.Panel value="external" pt="sm">
<Stack gap="xs">
<Text size="sm" c="dimmed">
{t(
'groupSigning.steps.selectParticipants.externalNote',
'An invitation email will be sent with a signing link. No account required.'
)}
</Text>
<Group gap="xs" align="flex-start">
<TextInput
style={{ flex: 1 }}
placeholder="signer@example.com"
value={emailInput}
onChange={(e) => {
setEmailInput(e.currentTarget.value);
if (emailError) setEmailError('');
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddEmail();
}
}}
error={emailError}
/>
<Button onClick={handleAddEmail} variant="default">
{t('groupSigning.steps.selectParticipants.addEmail', 'Add')}
</Button>
</Group>
{externalEmails.map((email) => (
<Group key={email} gap="xs" justify="space-between" wrap="nowrap">
<Group gap="xs">
<Badge variant="light" color="orange" size="xs">
{t('groupSigning.steps.selectParticipants.badgeExternal', 'Guest')}
</Badge>
<Text size="sm">{email}</Text>
</Group>
<ActionIcon
variant="subtle"
color="red"
size="sm"
onClick={() => setExternalEmails((prev) => prev.filter((e) => e !== email))}
>
<CloseIcon sx={{ fontSize: 14 }} />
</ActionIcon>
</Group>
))}
</Stack>
</Tabs.Panel>
</Tabs>
<TextInput
label={t('certSign.reason', 'Default Reason')}
description={t('certSign.collab.addParticipants.reasonHelp', 'Pre-set a signing reason for these participants (optional, they can override when signing)')}
description={t(
'certSign.collab.addParticipants.reasonHelp',
'Pre-set a signing reason for these participants (optional, they can override when signing)'
)}
value={defaultReason}
onChange={(e) => setDefaultReason(e.currentTarget.value)}
placeholder={t('certSign.collab.addParticipants.reasonPlaceholder', 'e.g. Approval, Review...')}
placeholder={t(
'certSign.collab.addParticipants.reasonPlaceholder',
'e.g. Approval, Review...'
)}
size="sm"
/>
@@ -68,12 +185,12 @@ export const AddParticipantsFlow: React.FC<AddParticipantsFlowProps> = ({
<Button
onClick={handleSubmit}
loading={submitting}
disabled={selectedUserIds.length === 0}
disabled={totalCount === 0}
leftSection={<AddIcon sx={{ fontSize: 16 }} />}
color="green"
>
{t('certSign.collab.addParticipants.add', 'Add {{count}} Participant(s)', {
count: selectedUserIds.length,
count: totalCount,
})}
</Button>
</Group>
@@ -123,7 +123,6 @@ function ReviewStepContent<TParams = unknown>({
)}
{operation.downloadUrl && (
<Button
data-testid="download-result-button"
leftSection={<DownloadIcon />}
color="blue"
fullWidth
@@ -1,4 +1,63 @@
/* Attachment Sidebar - Attachment-specific styles (base styles in SidebarBase.css) */
/* Attachment Sidebar - Modern styling to match AllTools section */
.attachment-sidebar {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.attachment-sidebar__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.attachment-sidebar__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.attachment-sidebar__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section */
.attachment-sidebar__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.attachment-sidebar__content {
padding-top: 0.5rem !important;
}
.attachment-sidebar__empty-state,
.attachment-sidebar__error {
padding: 2rem 1rem;
text-align: center;
}
.attachment-sidebar__loading {
padding: 2rem 1rem !important;
}
/* Attachment List */
.attachment-list {
@@ -6,7 +6,6 @@ import { PdfAttachmentObject } from '@embedpdf/models';
import AttachmentIcon from '@mui/icons-material/AttachmentRounded';
import DownloadIcon from '@mui/icons-material/DownloadRounded';
import { useTranslation } from 'react-i18next';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/AttachmentSidebar.css';
interface AttachmentSidebarProps {
@@ -285,7 +284,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
return (
<Box
className="sidebar-base attachment-sidebar"
className="attachment-sidebar"
style={{
position: 'fixed',
right: `${(thumbnailVisible ? 15 : 0) + (bookmarkVisible ? 15 : 0)}rem`,
@@ -295,9 +294,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
zIndex: 998,
}}
>
<div className="sidebar-base__header attachment-sidebar__header">
<div className="sidebar-base__header-title attachment-sidebar__header-title">
<span className="sidebar-base__header-icon attachment-sidebar__header-icon">
<div className="attachment-sidebar__header">
<div className="attachment-sidebar__header-title">
<span className="attachment-sidebar__header-icon">
<AttachmentIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -306,7 +305,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</div>
</div>
<Box px="sm" pb="sm" className="sidebar-base__search attachment-sidebar__search">
<Box px="sm" pb="sm" className="attachment-sidebar__search">
<TextInput
value={searchTerm}
placeholder={t('viewer.attachments.searchPlaceholder', 'Search attachments')}
@@ -317,9 +316,9 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content attachment-sidebar__content">
<Box p="sm" className="attachment-sidebar__content">
{!attachmentSupport && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noSupport', 'Attachment support is unavailable for this viewer.')}
</Text>
@@ -327,7 +326,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && showNoDocument && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noDocument', 'Open a PDF to view its attachments.')}
</Text>
@@ -335,7 +334,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="sidebar-base__error">
<Stack gap="xs" align="center" className="attachment-sidebar__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -346,7 +345,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{attachmentSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Stack gap="md" align="center" c="dimmed" py="xl" className="attachment-sidebar__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
{t('viewer.attachments.loading', 'Loading attachments...')}
@@ -355,7 +354,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showEmptyState && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.empty', 'No attachments in this document')}
</Text>
@@ -369,7 +368,7 @@ export const AttachmentSidebar = ({ visible, thumbnailVisible, bookmarkVisible,
)}
{showSearchEmpty && (
<div className="sidebar-base__empty-state">
<div className="attachment-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
{t('viewer.attachments.noMatch', 'No attachments match your search')}
</Text>
@@ -1,4 +1,63 @@
/* Bookmark Sidebar - Bookmark-specific styles (base styles in SidebarBase.css) */
/* Bookmark Sidebar - Modern styling to match AllTools section */
.bookmark-sidebar {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.bookmark-sidebar__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.bookmark-sidebar__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.bookmark-sidebar__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section */
.bookmark-sidebar__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.bookmark-sidebar__content {
padding-top: 0.5rem !important;
}
.bookmark-sidebar__empty-state,
.bookmark-sidebar__error {
padding: 2rem 1rem;
text-align: center;
}
.bookmark-sidebar__loading {
padding: 2rem 1rem !important;
}
/* Bookmark List */
.bookmark-list {
@@ -134,3 +193,4 @@
animation: none;
}
}
@@ -4,7 +4,6 @@ import LocalIcon from '@app/components/shared/LocalIcon';
import { useViewer } from '@app/contexts/ViewerContext';
import { PdfBookmarkObject, PdfActionType } from '@embedpdf/models';
import BookmarksIcon from '@mui/icons-material/BookmarksRounded';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/BookmarkSidebar.css';
interface BookmarkSidebarProps {
@@ -430,7 +429,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
return (
<Box
className="sidebar-base bookmark-sidebar"
className="bookmark-sidebar"
style={{
position: 'fixed',
right: thumbnailVisible ? SIDEBAR_WIDTH : 0,
@@ -440,9 +439,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
zIndex: 998,
}}
>
<div className="sidebar-base__header bookmark-sidebar__header">
<div className="sidebar-base__header-title bookmark-sidebar__header-title">
<span className="sidebar-base__header-icon bookmark-sidebar__header-icon">
<div className="bookmark-sidebar__header">
<div className="bookmark-sidebar__header-title">
<span className="bookmark-sidebar__header-icon">
<BookmarksIcon />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5}>
@@ -476,7 +475,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
</div>
<Box px="sm" pb="sm" className="sidebar-base__search bookmark-sidebar__search">
<Box px="sm" pb="sm" className="bookmark-sidebar__search">
<TextInput
value={searchTerm}
placeholder="Search bookmarks"
@@ -487,9 +486,9 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
</Box>
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content bookmark-sidebar__content">
<Box p="sm" className="bookmark-sidebar__content">
{!bookmarkSupport && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
Bookmark support is unavailable for this viewer.
</Text>
@@ -497,7 +496,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && showNoDocument && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
Open a PDF to view its bookmarks.
</Text>
@@ -505,7 +504,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && currentError && (
<Stack gap="xs" align="center" className="sidebar-base__error">
<Stack gap="xs" align="center" className="bookmark-sidebar__error">
<Text size="sm" c="red" ta="center">
{currentError}
</Text>
@@ -516,7 +515,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{bookmarkSupport && documentCacheKey && isLocalLoading && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Stack gap="md" align="center" c="dimmed" py="xl" className="bookmark-sidebar__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
Loading bookmarks...
@@ -525,7 +524,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showEmptyState && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks in this document
</Text>
@@ -539,7 +538,7 @@ export const BookmarkSidebar = ({ visible, thumbnailVisible, documentCacheKey, p
)}
{showSearchEmpty && (
<div className="sidebar-base__empty-state">
<div className="bookmark-sidebar__empty-state">
<Text size="sm" c="dimmed" ta="center">
No bookmarks match your search
</Text>
@@ -10,7 +10,6 @@ import { PdfViewerToolbar } from '@app/components/viewer/PdfViewerToolbar';
import { ThumbnailSidebar } from '@app/components/viewer/ThumbnailSidebar';
import { BookmarkSidebar } from '@app/components/viewer/BookmarkSidebar';
import { AttachmentSidebar } from '@app/components/viewer/AttachmentSidebar';
import { LayerSidebar } from '@app/components/viewer/LayerSidebar';
import { useNavigationGuard, useNavigationState } from '@app/contexts/NavigationContext';
import { useSignature } from '@app/contexts/SignatureContext';
import { useRedaction } from '@app/contexts/RedactionContext';
@@ -25,7 +24,6 @@ import type { PDFDict, PDFNumber } from '@cantoo/pdf-lib';
import { useWheelZoom } from '@app/hooks/useWheelZoom';
import { useFormFill } from '@app/tools/formFill/FormFillContext';
import { FormSaveBar } from '@app/tools/formFill/FormSaveBar';
import { useViewerKeyCommand } from '@app/hooks/useViewerKeyCommand';
// ─── Measure dictionary extraction ────────────────────────────────────────────
@@ -127,8 +125,6 @@ const EmbedPdfViewerContent = ({
toggleThumbnailSidebar,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
setHasLayers,
isCommentsSidebarVisible,
isSearchInterfaceVisible,
searchInterfaceActions,
@@ -381,19 +377,15 @@ const EmbedPdfViewerContent = ({
onZoomOut: zoomActions.zoomOut,
});
const viewerKeyCommand = useViewerKeyCommand();
// Handle keyboard shortcuts
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const mod = event.ctrlKey || event.metaKey;
// Ctrl+P (print) must be intercepted unconditionally
// Ctrl+P (print) and Ctrl+R (rotate) must be intercepted unconditionally
// whenever the viewer is mounted, even before the user has hovered over it.
// Ctrl+R (rotate) is intercepted only on desktop (Tauri), while on web it still falls through to browser refresh.
// Without this, the browser falls through to its native "print HTML page"
// or "reload page" behaviour.
if (mod) {
const target = event.target as Element;
const isInTextInput =
@@ -402,15 +394,12 @@ const EmbedPdfViewerContent = ({
(target as HTMLElement).isContentEditable;
if (!isInTextInput) {
const wasOverridden = viewerKeyCommand(event)
if (!wasOverridden){
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
}
switch (event.key) {
case 'p':
case 'P':
event.preventDefault();
printActions.print();
return;
}
}
}
@@ -517,7 +506,7 @@ const EmbedPdfViewerContent = ({
}, [
isViewerHovered, isSearchInterfaceVisible, zoomActions, searchInterfaceActions,
scrollActions, printActions, exportActions, rotationActions, historyApiRef,
viewerApplyChanges, cyclePdfRenderMode, viewerKeyCommand,
viewerApplyChanges, cyclePdfRenderMode,
]);
// Watch the annotation history API to detect when the document becomes "dirty".
@@ -711,46 +700,6 @@ const EmbedPdfViewerContent = ({
return () => window.removeEventListener('formfill:apply', handler);
}, [handleFormApply]);
// Apply layer visibility changes - reload the modified PDF into the viewer
const layerApplyInProgressRef = useRef(false);
const handleLayerApply = useCallback(async (modifiedBlob: Blob) => {
if (layerApplyInProgressRef.current) return;
if (!currentFile || activeFileIds.length === 0) return;
layerApplyInProgressRef.current = true;
try {
const pageToRestore = lastKnownScrollPageRef.current;
const currentRotation = rotationState.rotation ?? 0;
const filename = currentFile.name || 'document.pdf';
const file = new File([modifiedBlob], filename, { type: 'application/pdf' });
const currentFileId = activeFiles[activeFileIndex]?.fileId;
if (!currentFileId) throw new Error('Current file ID not found');
const parentStub = selectors.getStirlingFileStub(currentFileId);
if (!parentStub) throw new Error('Parent stub not found');
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs([file], parentStub, 'multiTool');
pendingScrollRestoreRef.current = pageToRestore;
scrollRestoreAttemptsRef.current = 0;
pendingRotationRestoreRef.current = currentRotation;
rotationRestoreAttemptsRef.current = 0;
const newFileId = stubs[0]?.id;
if (newFileId) {
pendingFileIdRef.current = newFileId;
}
await actions.consumeFiles([currentFileId], stirlingFiles, stubs);
} catch (error) {
console.error('[Viewer] Apply layer changes failed:', error);
} finally {
layerApplyInProgressRef.current = false;
}
}, [currentFile, activeFiles, activeFileIndex, actions, selectors, activeFileIds.length, rotationState.rotation]);
// Discard pending redactions but save already-applied ones
// This is called when user clicks "Discard & Leave" - we want to:
// 1. NOT commit pending redaction marks (they get discarded)
@@ -970,7 +919,6 @@ const EmbedPdfViewerContent = ({
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) +
(isBookmarkSidebarVisible ? sidebarWidthRem : 0) +
(isAttachmentSidebarVisible ? sidebarWidthRem : 0) +
(isLayerSidebarVisible ? sidebarWidthRem : 0) +
(isCommentsSidebarVisible ? commentsSidebarWidthRem : 0);
return (
@@ -1039,7 +987,7 @@ const EmbedPdfViewerContent = ({
redactionTrackerRef={redactionTrackerRef as React.RefObject<RedactionPendingTrackerAPI>}
fileId={currentFileId}
isCommentsSidebarVisible={isCommentsSidebarVisible}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0) + (isLayerSidebarVisible ? sidebarWidthRem : 0)}rem`}
commentsSidebarRightOffset={`${(isThumbnailSidebarVisible ? sidebarWidthRem : 0) + (isBookmarkSidebarVisible ? sidebarWidthRem : 0) + (isAttachmentSidebarVisible ? sidebarWidthRem : 0)}rem`}
onSignatureAdded={() => {
// Handle signature added - for debugging, enable console logs as needed
// Future: Handle signature completion
@@ -1109,18 +1057,6 @@ const EmbedPdfViewerContent = ({
documentCacheKey={bookmarkCacheKey}
preloadCacheKeys={allBookmarkCacheKeys}
/>
<LayerSidebar
visible={isLayerSidebarVisible}
rightOffset={
(isThumbnailSidebarVisible ? sidebarWidthRem : 0) +
(isBookmarkSidebarVisible ? sidebarWidthRem : 0) +
(isAttachmentSidebarVisible ? sidebarWidthRem : 0)
}
file={effectiveFile?.file ?? null}
documentCacheKey={bookmarkCacheKey}
onApplyLayers={handleLayerApply}
onLayersDetected={setHasLayers}
/>
{/* Navigation Warning Modal */}
{!previewFile && (
@@ -1,140 +0,0 @@
/* Layer Sidebar - Layer-specific styles (base styles in SidebarBase.css) */
/* Header actions (show/hide all buttons) */
.layer-sidebar__header-actions {
display: flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
}
/* Layer List */
.layer-list {
display: flex;
flex-direction: column;
gap: 0.125rem;
}
/* Layer Items */
.layer-item-wrapper {
display: flex;
flex-direction: column;
}
.layer-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.65rem;
border-radius: 0.5rem;
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease;
background: transparent;
border: 1px solid transparent;
width: 100%;
box-sizing: border-box;
}
.layer-item:hover {
background: color-mix(in srgb, var(--text-primary) 6%, var(--bg-toolbar));
border-color: color-mix(in srgb, var(--text-primary) 14%, var(--border-subtle));
}
.layer-item:active {
background: color-mix(in srgb, var(--text-primary) 10%, var(--bg-toolbar));
}
.layer-item__expand-btn {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
width: 1.25rem;
height: 1.25rem;
cursor: pointer;
color: var(--text-muted);
opacity: 0.7;
transition: opacity 0.15s ease;
}
.layer-item__expand-btn:hover {
opacity: 1;
}
.layer-item__expand-placeholder {
flex-shrink: 0;
width: 1.25rem;
}
.layer-item__label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
line-height: 1.4;
cursor: pointer;
user-select: none;
}
.layer-item--hidden .layer-item__label {
color: var(--text-muted);
text-decoration: line-through;
text-decoration-color: color-mix(in srgb, var(--text-muted) 60%, transparent);
}
/* Children Container */
.layer-item__children {
display: flex;
flex-direction: column;
gap: 0.125rem;
margin-top: 0.125rem;
border-left: 2px solid color-mix(in srgb, var(--border-subtle) 60%, transparent);
margin-left: 0.875rem;
padding-left: 0.25rem;
}
/* Footer with Apply button */
.layer-sidebar__footer {
padding: 0.625rem 0.875rem;
background: var(--bg-toolbar);
border-top: 1px solid var(--border-subtle);
}
/* Dirty indicator badge */
.layer-sidebar__dirty-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background: var(--mantine-color-orange-5);
flex-shrink: 0;
}
/* Animation */
@keyframes layer-fade-in {
from {
opacity: 0;
transform: translateY(-3px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.layer-item__children {
animation: layer-fade-in 0.15s ease;
}
/* Accessibility & Reduced Motion */
@media (prefers-reduced-motion: reduce) {
.layer-item,
.layer-item__children {
transition: none;
animation: none;
}
}
@@ -1,377 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { Box, ScrollArea, Text, Checkbox, Stack, Loader, ActionIcon, Tooltip } from '@mantine/core';
import LayersIcon from '@mui/icons-material/Layers';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import '@app/components/viewer/SidebarBase.css';
import '@app/components/viewer/LayerSidebar.css';
import { readPdfLayers, applyOCGVisibilityToPdf, collectLeafIds } from '@app/components/viewer/layerUtils';
import type { LayerInfo } from '@app/components/viewer/layerUtils';
export type { LayerInfo };
interface LayerSidebarProps {
visible: boolean;
/** Right offset in rem (how far from the right edge). */
rightOffset: number;
/** The current PDF file to read layers from. */
file?: Blob | null;
/** Stable key that changes when the document changes (used to avoid re-fetching). */
documentCacheKey?: string;
/** Called when the user applies layer visibility changes. Receives the modified PDF blob. */
onApplyLayers: (modifiedBlob: Blob) => Promise<void>;
/** Called when layer detection completes, reporting whether the PDF has layers. */
onLayersDetected?: (hasLayers: boolean) => void;
}
const SIDEBAR_WIDTH = '15rem';
type LoadStatus = 'idle' | 'loading' | 'ready' | 'no-layers' | 'error';
export function LayerSidebar({
visible,
rightOffset,
file,
documentCacheKey,
onApplyLayers,
onLayersDetected,
}: LayerSidebarProps) {
const [layers, setLayers] = useState<LayerInfo[]>([]);
const [visibility, setVisibility] = useState<Record<string, boolean>>({});
const [status, setStatus] = useState<LoadStatus>('idle');
const [loadError, setLoadError] = useState<string | null>(null);
const [isApplying, setIsApplying] = useState(false);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const loadedKeyRef = useRef<string | null>(null);
// Track whether visibility was set by user interaction (not initial load)
const userChangedRef = useRef(false);
// Load layers when the document changes
useEffect(() => {
if (!file || !documentCacheKey) {
setStatus('idle');
setLayers([]);
setVisibility({});
loadedKeyRef.current = null;
userChangedRef.current = false;
onLayersDetected?.(false);
return;
}
if (loadedKeyRef.current === documentCacheKey) return;
setStatus('loading');
setLoadError(null);
userChangedRef.current = false;
let cancelled = false;
readPdfLayers(file)
.then(layerList => {
if (cancelled) return;
if (layerList.length === 0) {
setStatus('no-layers');
setLayers([]);
setVisibility({});
loadedKeyRef.current = documentCacheKey;
onLayersDetected?.(false);
return;
}
// Build visibility map from the layer defaults (all leaf IDs)
const visMap: Record<string, boolean> = {};
const populateVisibility = (items: LayerInfo[]) => {
for (const item of items) {
if (item.children && item.children.length > 0) {
populateVisibility(item.children);
} else {
visMap[item.id] = item.visible;
}
}
};
populateVisibility(layerList);
setLayers(layerList);
setVisibility(visMap);
setStatus('ready');
loadedKeyRef.current = documentCacheKey;
onLayersDetected?.(true);
})
.catch(err => {
if (cancelled) return;
setStatus('error');
setLoadError(err instanceof Error ? err.message : 'Failed to read PDF layers');
onLayersDetected?.(false);
});
return () => {
cancelled = true;
};
}, [file, documentCacheKey, onLayersDetected]);
// Reset when document changes
useEffect(() => {
setExpanded({});
userChangedRef.current = false;
}, [documentCacheKey]);
// Auto-apply: debounce visibility changes from user interaction
useEffect(() => {
if (!userChangedRef.current || !file || isApplying || layers.length === 0) return;
const timer = setTimeout(async () => {
setIsApplying(true);
try {
const nameVisibility: Record<string, boolean> = {};
const collectNames = (items: LayerInfo[]) => {
for (const item of items) {
if (item.children && item.children.length > 0) {
collectNames(item.children);
} else {
nameVisibility[item.name] = visibility[item.id] ?? item.visible;
}
}
};
collectNames(layers);
const arrayBuffer = await file.arrayBuffer();
const modifiedBytes = await applyOCGVisibilityToPdf(arrayBuffer, nameVisibility);
const blob = new Blob([new Uint8Array(modifiedBytes)], { type: 'application/pdf' });
await onApplyLayers(blob);
} catch (err) {
console.error('[LayerSidebar] Failed to apply layer changes:', err);
} finally {
setIsApplying(false);
userChangedRef.current = false;
}
}, 300);
return () => clearTimeout(timer);
}, [visibility, file, layers, isApplying, onApplyLayers]);
const toggleLayerVisibility = useCallback((id: string) => {
userChangedRef.current = true;
setVisibility(prev => ({ ...prev, [id]: !prev[id] }));
}, []);
const showAll = useCallback(() => {
userChangedRef.current = true;
setVisibility(prev => {
const updated: Record<string, boolean> = {};
for (const id of Object.keys(prev)) {
updated[id] = true;
}
return updated;
});
}, []);
const hideAll = useCallback(() => {
userChangedRef.current = true;
setVisibility(prev => {
const updated: Record<string, boolean> = {};
for (const id of Object.keys(prev)) {
updated[id] = false;
}
return updated;
});
}, []);
const toggleExpanded = useCallback((id: string) => {
setExpanded(prev => ({ ...prev, [id]: !(prev[id] ?? true) }));
}, []);
const renderLayer = (layer: LayerInfo & { depth: number }) => {
const hasChildren = Boolean(layer.children && layer.children.length > 0);
const isExpanded = expanded[layer.id] !== false; // default expanded
const isLeaf = !hasChildren;
const isVisible = isLeaf
? visibility[layer.id] ?? layer.visible
: collectLeafIds(layer.children ?? []).every(id => visibility[id] ?? true);
return (
<div
key={layer.id}
className="layer-item-wrapper"
style={{ marginLeft: layer.depth > 0 ? `${layer.depth * 0.875}rem` : '0' }}
>
<div
className={`layer-item ${!isVisible ? 'layer-item--hidden' : ''}`}
onClick={() => {
if (hasChildren) {
toggleExpanded(layer.id);
} else {
toggleLayerVisibility(layer.id);
}
}}
role="button"
tabIndex={0}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (hasChildren) {
toggleExpanded(layer.id);
} else {
toggleLayerVisibility(layer.id);
}
}
}}
>
{hasChildren ? (
<span
className="layer-item__expand-btn"
onClick={e => {
e.stopPropagation();
toggleExpanded(layer.id);
}}
>
{isExpanded ? (
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
<path d="M2 4l4 4 4-4z" />
</svg>
) : (
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
<path d="M4 2l4 4-4 4z" />
</svg>
)}
</span>
) : (
<span className="layer-item__expand-placeholder" />
)}
{isLeaf && (
<Checkbox
size="xs"
checked={visibility[layer.id] ?? layer.visible}
onChange={() => toggleLayerVisibility(layer.id)}
onClick={e => e.stopPropagation()}
style={{ flexShrink: 0 }}
/>
)}
<Tooltip
label={layer.name}
position="left"
withinPortal
disabled={layer.name.length < 20}
>
<span className="layer-item__label">
{layer.name}
</span>
</Tooltip>
</div>
{hasChildren && isExpanded && (
<div className="layer-item__children">
{(layer.children ?? []).map(child => renderLayer({ ...child, depth: 0 }))}
</div>
)}
</div>
);
};
if (!visible) return null;
const leafIds = collectLeafIds(layers);
const allVisible = leafIds.every(id => visibility[id] !== false);
const allHidden = leafIds.every(id => visibility[id] === false);
return (
<Box
className="sidebar-base layer-sidebar"
style={{
position: 'fixed',
right: `${rightOffset}rem`,
top: 0,
bottom: 0,
width: SIDEBAR_WIDTH,
zIndex: 998,
}}
>
{/* Header */}
<div className="sidebar-base__header">
<div className="sidebar-base__header-title">
<span className="sidebar-base__header-icon">
<LayersIcon fontSize="small" />
</span>
<Text fw={600} size="sm" tt="uppercase" lts={0.5} style={{ flex: 1 }}>
Layers
</Text>
{isApplying && <Loader size="xs" type="dots" />}
</div>
{status === 'ready' && leafIds.length > 0 && (
<div className="layer-sidebar__header-actions">
<ActionIcon
variant="subtle"
size="sm"
onClick={showAll}
disabled={allVisible || isApplying}
aria-label="Show all layers"
title="Show all"
>
<VisibilityIcon sx={{ fontSize: '1rem' }} />
</ActionIcon>
<ActionIcon
variant="subtle"
size="sm"
onClick={hideAll}
disabled={allHidden || isApplying}
aria-label="Hide all layers"
title="Hide all"
>
<VisibilityOffIcon sx={{ fontSize: '1rem' }} />
</ActionIcon>
</div>
)}
</div>
{/* Content */}
<ScrollArea style={{ flex: 1 }}>
<Box p="sm" className="sidebar-base__content">
{status === 'idle' && (
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
Open a PDF to view its layers.
</Text>
</div>
)}
{status === 'loading' && (
<Stack gap="md" align="center" c="dimmed" py="xl" className="sidebar-base__loading">
<Loader size="md" type="dots" />
<Text size="sm" ta="center">
Loading layers...
</Text>
</Stack>
)}
{status === 'error' && (
<div className="sidebar-base__error">
<Text size="sm" c="red" ta="center">
{loadError ?? 'Failed to load layers.'}
</Text>
</div>
)}
{status === 'no-layers' && (
<div className="sidebar-base__empty-state">
<Text size="sm" c="dimmed" ta="center">
This document has no layers.
</Text>
</div>
)}
{status === 'ready' && layers.length > 0 && (
<div className="layer-list">
{layers.map(layer => renderLayer({ ...layer, depth: 0 }))}
</div>
)}
</Box>
</ScrollArea>
</Box>
);
}
@@ -4,7 +4,6 @@ import type { PluginRegistry } from '@embedpdf/core';
import { EmbedPDF } from '@embedpdf/core/react';
import { usePdfiumEngine } from '@embedpdf/engines/react';
import { PrivateContent } from '@app/components/shared/PrivateContent';
import { useAppConfig } from '@app/contexts/AppConfigContext';
// Import the essential plugins
import { Viewport, ViewportPluginPackage } from '@embedpdf/plugin-viewport/react';
@@ -95,17 +94,15 @@ interface LocalEmbedPDFProps {
export function LocalEmbedPDF({ file, url, fileName, enableAnnotations = false, enableRedaction = false, enableFormFill = false, isManualRedactionMode = false, showBakedAnnotations = true, onSignatureAdded, signatureApiRef, annotationApiRef, historyApiRef, redactionTrackerRef, fileId, isCommentsSidebarVisible = false, commentsSidebarRightOffset = '0rem', isSignMode = false, pdfRenderMode = 'normal' }: LocalEmbedPDFProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [, setAnnotations] = useState<Array<{id: string, pageIndex: number, rect: Rect}>>([]);
const [commentAuthorName, setCommentAuthorName] = useState<string>('Guest');
useEffect(() => {
if (!config?.enableLogin) return;
accountService.getAccountData().then((data) => {
if (data?.username) setCommentAuthorName(data.username);
}).catch(() => {/* not logged in or security disabled */});
}, [config?.enableLogin]);
}, []);
// Convert File to URL if needed
useEffect(() => {
@@ -1,113 +0,0 @@
import { useCallback, useMemo } from 'react';
import { Box, Button, Center, Stack, Text } from '@mantine/core';
import ArticleIcon from '@mui/icons-material/Article';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import { useFileState } from '@app/contexts/FileContext';
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
import { detectFileExtension, detectNonPdfFileType } from '@app/utils/fileUtils';
import { CONVERSION_MATRIX } from '@app/constants/convertConstants';
import { NonPdfBanner } from '@app/components/viewer/nonpdf/NonPdfBanner';
import { getFileTypeMeta } from '@app/components/viewer/nonpdf/types';
import { ImageViewer } from '@app/components/viewer/nonpdf/ImageViewer';
import { CsvViewer } from '@app/components/viewer/nonpdf/CsvViewer';
import { JsonViewer } from '@app/components/viewer/nonpdf/JsonViewer';
import { TextViewer } from '@app/components/viewer/nonpdf/TextViewer';
import { HtmlViewer } from '@app/components/viewer/nonpdf/HtmlViewer';
export interface ViewerProps {
sidebarsVisible: boolean;
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
activeFileIndex?: number;
setActiveFileIndex?: (index: number) => void;
}
export interface NonPdfViewerProps extends ViewerProps {
file: File;
}
export function NonPdfViewer({ file }: NonPdfViewerProps) {
const fileType = useMemo(() => detectNonPdfFileType(file), [file]);
const meta = useMemo(() => getFileTypeMeta(fileType, file.name), [fileType, file.name]);
const { handleToolSelect, toolAvailability } = useToolWorkflow();
const fileExtension = detectFileExtension(file.name);
// Only show convert when the extension has an explicit entry in the conversion matrix
// (skip the 'any'/'image' wildcard fallbacks that would match everything)
const isConvertAvailable = toolAvailability['convert']?.available === true
&& fileExtension !== ''
&& fileExtension in CONVERSION_MATRIX;
const handleConvertToPdf = useCallback(() => {
handleToolSelect('convert');
}, [handleToolSelect]);
const renderContent = () => {
switch (fileType) {
case 'image':
return <ImageViewer file={file} fileName={file.name} />;
case 'csv':
return <CsvViewer file={file} isTsv={file.name.toLowerCase().endsWith('.tsv')} />;
case 'json':
return <JsonViewer file={file} />;
case 'markdown':
return <TextViewer file={file} isMarkdown />;
case 'text':
return <TextViewer file={file} isMarkdown={false} />;
case 'html':
return <HtmlViewer file={file} />;
default:
return (
<Center style={{ flex: 1 }}>
<Stack align="center" gap="sm">
<ArticleIcon style={{ fontSize: '3rem', color: 'var(--mantine-color-gray-4)' }} />
<Text c="dimmed" size="sm">Preview not available for this file type</Text>
{isConvertAvailable && (
<Button variant="light" color="orange" leftSection={<PictureAsPdfIcon />} onClick={handleConvertToPdf}>
Convert to PDF
</Button>
)}
</Stack>
</Center>
);
}
};
return (
<Stack gap={0} style={{ height: '100%', flex: 1, overflow: 'hidden', position: 'relative' }}>
<NonPdfBanner
meta={meta}
onConvertToPdf={isConvertAvailable ? handleConvertToPdf : undefined}
/>
<Box style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{renderContent()}
</Box>
</Stack>
);
}
// ─── Wrapper that resolves the active file from FileContext ───────────────────
export function NonPdfViewerWrapper(props: ViewerProps) {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
const activeFileIndex = props.activeFileIndex ?? 0;
const file = props.previewFile ?? activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
if (!file) {
return (
<Center style={{ flex: 1 }}>
<Text c="dimmed" size="sm">No file selected</Text>
</Center>
);
}
return <NonPdfViewer {...props} file={file} />;
}
export default NonPdfViewerWrapper;
@@ -1,61 +0,0 @@
/* Shared Sidebar Base - Common styles for all viewer sidebars */
/* Container */
.sidebar-base {
display: flex;
flex-direction: column;
background: linear-gradient(
135deg,
color-mix(in srgb, var(--bg-toolbar) 96%, transparent),
color-mix(in srgb, var(--bg-background) 90%, transparent)
);
border-left: 1px solid color-mix(in srgb, var(--border-subtle) 75%, transparent);
box-shadow: -2px 0 16px color-mix(in srgb, var(--shadow-color, rgba(15, 23, 42, 0.35)) 20%, transparent);
backdrop-filter: blur(12px);
}
/* Header Section */
.sidebar-base__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 0.875rem;
background: var(--bg-toolbar);
border-bottom: 1px solid var(--border-subtle);
}
.sidebar-base__header-title {
display: flex;
align-items: center;
gap: 0.5rem;
}
.sidebar-base__header-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--mantine-color-blue-6);
font-size: 1.1rem;
}
/* Search Section (used by bookmark & attachment sidebars) */
.sidebar-base__search {
background: var(--tool-panel-search-bg, var(--bg-toolbar));
border-bottom: 1px solid var(--tool-panel-search-border-bottom, var(--border-subtle));
padding-top: 0.75rem !important;
}
/* Content Section */
.sidebar-base__content {
padding-top: 0.5rem !important;
}
.sidebar-base__empty-state,
.sidebar-base__error {
padding: 2rem 1rem;
text-align: center;
}
.sidebar-base__loading {
padding: 2rem 1rem !important;
}
+9 -20
View File
@@ -1,27 +1,16 @@
import { useMemo } from 'react';
import EmbedPdfViewer from '@app/components/viewer/EmbedPdfViewer';
import { NonPdfViewerWrapper, type ViewerProps } from '@app/components/viewer/NonPdfViewer';
import { useFileState } from '@app/contexts/FileContext';
import { isPdfFile } from '@app/utils/fileUtils';
export type { ViewerProps };
export interface ViewerProps {
sidebarsVisible: boolean;
setSidebarsVisible: (v: boolean) => void;
onClose?: () => void;
previewFile?: File | null;
activeFileIndex?: number;
setActiveFileIndex?: (index: number) => void;
}
const Viewer = (props: ViewerProps) => {
const { selectors } = useFileState();
const activeFiles = selectors.getFiles();
const activeFileIndex = props.activeFileIndex ?? 0;
// Determine the active file — previewFile takes priority
const activeFile = useMemo(() => {
if (props.previewFile) return props.previewFile;
return activeFiles[activeFileIndex] ?? activeFiles[0] ?? null;
}, [props.previewFile, activeFiles, activeFileIndex]);
// Route to the appropriate viewer based on file type
if (activeFile && !isPdfFile(activeFile)) {
return <NonPdfViewerWrapper {...props} />;
}
// Default to EmbedPDF viewer
return <EmbedPdfViewer {...props} />;
};
@@ -1,228 +0,0 @@
export interface LayerInfo {
id: string;
name: string;
visible: boolean;
children?: LayerInfo[];
}
/**
* Reads OCG layer info from a PDF file using pdfjs-dist.
* Returns a flat list of all OCG groups with their names and default visibility.
*/
export async function readPdfLayers(file: Blob): Promise<LayerInfo[]> {
const { getDocument, GlobalWorkerOptions } = await import('pdfjs-dist/legacy/build/pdf.mjs');
if (!GlobalWorkerOptions.workerSrc) {
GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
import.meta.url
).toString();
}
const arrayBuffer = await file.arrayBuffer();
const loadingTask = getDocument({ data: arrayBuffer, verbosity: 0 });
const pdfDoc = await loadingTask.promise;
try {
const ocConfig = await pdfDoc.getOptionalContentConfig();
if (!ocConfig) return [];
// pdfjs v5 uses [Symbol.iterator] and getGroup(id), not getGroups()
const groups: Record<string, any> = {};
for (const [id, group] of ocConfig as any) {
groups[id] = group;
}
if (Object.keys(groups).length === 0) return [];
// Use getOrder() for hierarchical display
let order: any[] | null = null;
try {
order = ocConfig.getOrder?.() ?? null;
} catch {
// getOrder not available
}
if (order && Array.isArray(order) && order.length > 0) {
return buildLayerTree(order, groups);
}
// Fallback: flat list in enumeration order
return Object.entries(groups).map(([id, group]) => ({
id,
name: (group as any).name ?? id,
visible: (group as any).visible ?? true,
}));
} finally {
await pdfDoc.destroy();
}
}
/**
* Recursively builds a LayerInfo tree from pdfjs OCG order array.
* The order array can contain:
* - string: an OCG id
* - { name: string, order: any[] }: a named group with children
* - array: a nested group
*/
function buildLayerTree(
order: any[],
groups: Record<string, any>,
visited = new Set<string>()
): LayerInfo[] {
const result: LayerInfo[] = [];
for (const item of order) {
if (typeof item === 'string') {
// It's an OCG id
if (visited.has(item)) continue;
visited.add(item);
const group = groups[item];
if (group) {
result.push({
id: item,
name: (group as any).name ?? item,
visible: (group as any).visible ?? true,
});
}
} else if (Array.isArray(item)) {
// Nested group (unlabeled)
const children = buildLayerTree(item, groups, visited);
result.push(...children);
} else if (item && typeof item === 'object') {
// Named group with nested items
const { name, order: subOrder } = item as { name?: string; order?: any[] };
const children = subOrder ? buildLayerTree(subOrder, groups, visited) : [];
if (name && children.length > 0) {
// Use the first child's id as a synthetic group id
result.push({
id: `group-${name}`,
name: name,
visible: children.every(c => c.visible),
children,
});
} else {
result.push(...children);
}
}
}
return result;
}
/**
* Modifies OCG visibility in a PDF using @cantoo/pdf-lib.
* Accepts a flat map of { layerName -> visible } and rewrites the /D config.
*
* Strategy: set /BaseState to /OFF and only list visible layers in /ON.
* This is the most unambiguous approach and avoids conflicts between
* /BaseState, /ON, and /OFF that can confuse some viewers.
* Also removes /AS (auto-state) entries that can override visibility.
*/
export async function applyOCGVisibilityToPdf(
pdfBytes: ArrayBuffer,
layerVisibility: Record<string, boolean>
): Promise<Uint8Array> {
const { PDFDocument, PDFDict, PDFName, PDFArray, PDFString, PDFHexString } =
await import('@cantoo/pdf-lib');
const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
const context = doc.context;
// Access the catalog via the trailer's Root reference
const catalogRef = context.trailerInfo.Root;
const catalog = context.lookup(catalogRef) as unknown as typeof PDFDict.prototype;
// Get OCProperties dict (may be a direct dict or an indirect reference)
const ocPropsRaw = (catalog as any).lookup(PDFName.of('OCProperties'));
if (!ocPropsRaw) {
return doc.save();
}
const ocProps = (ocPropsRaw instanceof PDFDict
? ocPropsRaw
: context.lookup(ocPropsRaw)) as unknown as typeof PDFDict.prototype;
// Get the /OCGs array
const ocgsRaw = (ocProps as any).lookup(PDFName.of('OCGs'));
if (!(ocgsRaw instanceof PDFArray)) {
return doc.save();
}
const ocgsArray = ocgsRaw as unknown as typeof PDFArray.prototype;
// Get or create the /D (default config) dict
const dRaw = (ocProps as any).lookup(PDFName.of('D'));
if (!dRaw) {
return doc.save();
}
const dDict = (dRaw instanceof PDFDict
? dRaw
: context.lookup(dRaw)) as unknown as typeof PDFDict.prototype;
// Collect OCG refs for ON vs OFF based on user visibility settings
const onRefs: any[] = [];
const offRefs: any[] = [];
const size = (ocgsArray as any).size() as number;
for (let i = 0; i < size; i++) {
const ocgRef = (ocgsArray as any).get(i);
const ocgDict = context.lookup(ocgRef) as unknown as typeof PDFDict.prototype;
if (!ocgDict) continue;
// Get the OCG name
const nameRaw = (ocgDict as any).lookup(PDFName.of('Name'));
let ocgName = '';
if (nameRaw instanceof PDFString || nameRaw instanceof PDFHexString) {
ocgName = (nameRaw as any).decodeText?.() ?? (nameRaw as any).asString?.() ?? '';
} else if (nameRaw) {
ocgName = String(nameRaw);
}
// Look up visibility by name
const shouldBeVisible = layerVisibility[ocgName] ?? true;
if (shouldBeVisible) {
onRefs.push(ocgRef);
} else {
offRefs.push(ocgRef);
}
}
// Set /BaseState to /OFF so all layers start hidden, then /ON lists visible ones.
// This is unambiguous and avoids conflicts between /BaseState and /ON//OFF.
(dDict as any).set(PDFName.of('BaseState'), PDFName.of('OFF'));
// Set /ON to only the visible layers
if (onRefs.length > 0) {
(dDict as any).set(PDFName.of('ON'), context.obj(onRefs));
} else {
(dDict as any).delete?.(PDFName.of('ON'));
}
// Set /OFF to only the hidden layers (for viewers that check it)
if (offRefs.length > 0) {
(dDict as any).set(PDFName.of('OFF'), context.obj(offRefs));
} else {
(dDict as any).delete?.(PDFName.of('OFF'));
}
// Remove /AS (auto-state) array — it can contain usage-based overrides
// (e.g., print vs view) that conflict with our explicit visibility settings.
(dDict as any).delete?.(PDFName.of('AS'));
return doc.save();
}
/**
* Collects all leaf-level layer IDs (those that are actual OCGs, not synthetic groups).
*/
export function collectLeafIds(layers: LayerInfo[]): string[] {
const ids: string[] = [];
for (const layer of layers) {
if (layer.children && layer.children.length > 0) {
ids.push(...collectLeafIds(layer.children));
} else {
ids.push(layer.id);
}
}
return ids;
}
@@ -1,191 +0,0 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Badge, Center, Group, Paper, ScrollArea, Stack, Table, Text } from '@mantine/core';
import SortIcon from '@mui/icons-material/Sort';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
// ─── CSV parser ───────────────────────────────────────────────────────────────
function parseCsv(text: string, delimiter: string): string[][] {
const rows: string[][] = [];
let field = '';
let inQuotes = false;
let row: string[] = [];
for (let i = 0; i < text.length; i++) {
const ch = text[i];
const next = text[i + 1];
if (inQuotes) {
if (ch === '"' && next === '"') {
field += '"';
i++;
} else if (ch === '"') {
inQuotes = false;
} else {
field += ch;
}
} else if (ch === '"') {
inQuotes = true;
} else if (ch === delimiter) {
row.push(field);
field = '';
} else if (ch === '\r' && next === '\n') {
row.push(field);
field = '';
rows.push(row);
row = [];
i++;
} else if (ch === '\n' || ch === '\r') {
row.push(field);
field = '';
rows.push(row);
row = [];
} else {
field += ch;
}
}
if (field || row.length > 0) {
row.push(field);
rows.push(row);
}
// Remove trailing empty row
if (rows.length > 0 && rows[rows.length - 1].every(f => f === '')) {
rows.pop();
}
return rows;
}
// ─── CSV viewer ───────────────────────────────────────────────────────────────
interface CsvViewerProps {
file: File;
isTsv: boolean;
}
export function CsvViewer({ file, isTsv }: CsvViewerProps) {
const { t } = useTranslation();
const [rows, setRows] = useState<string[][]>([]);
const [loading, setLoading] = useState(true);
const [sortCol, setSortCol] = useState<number | null>(null);
const [sortAsc, setSortAsc] = useState(true);
useEffect(() => {
setLoading(true);
file.text().then(text => {
const delimiter = isTsv ? '\t' : ',';
setRows(parseCsv(text, delimiter));
setLoading(false);
});
}, [file, isTsv]);
const headers = rows[0] ?? [];
const dataRows = rows.slice(1);
const sortedDataRows = useMemo(() => {
if (sortCol === null) return dataRows;
return [...dataRows].sort((a, b) => {
const av = a[sortCol] ?? '';
const bv = b[sortCol] ?? '';
const numA = Number(av);
const numB = Number(bv);
const cmp = (!isNaN(numA) && !isNaN(numB)) ? numA - numB : av.localeCompare(bv);
return sortAsc ? cmp : -cmp;
});
}, [dataRows, sortCol, sortAsc]);
const handleSort = (colIdx: number) => {
if (sortCol === colIdx) {
setSortAsc(a => !a);
} else {
setSortCol(colIdx);
setSortAsc(true);
}
};
if (loading) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>;
}
if (rows.length === 0) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.emptyFile')}</Text></Center>;
}
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{/* Stats bar */}
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Group gap="md" align="center">
<Text size="xs" c="dimmed">
{t('viewer.nonPdf.csvStats', { rows: dataRows.length.toLocaleString(), columns: headers.length, size: formatFileSize(file.size) })}
</Text>
{sortCol !== null && (
<Badge
variant="light"
color="teal"
size="xs"
style={{ cursor: 'pointer' }}
onClick={() => { setSortCol(null); setSortAsc(true); }}
>
{t('viewer.nonPdf.sortedBy', { column: headers[sortCol] || t('viewer.nonPdf.columnDefault', { index: sortCol + 1 }) })} {sortAsc ? '\u2191' : '\u2193'} \u2715
</Badge>
)}
</Group>
</Paper>
{/* Table */}
<ScrollArea style={{ flex: 1 }}>
<Table
striped
highlightOnHover
withColumnBorders
withTableBorder={false}
style={{ fontSize: 'var(--mantine-font-size-xs)', whiteSpace: 'nowrap' }}
stickyHeader
>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 48, color: 'var(--mantine-color-dimmed)', textAlign: 'center', paddingInline: 8 }}>
#
</Table.Th>
{headers.map((h, i) => (
<Table.Th
key={i}
style={{ cursor: 'pointer', paddingInline: 8 }}
onClick={() => handleSort(i)}
>
<Group gap={4} align="center" wrap="nowrap">
<Text size="xs" fw={600} truncate style={{ maxWidth: 200 }}>{h || t('viewer.nonPdf.columnDefault', { index: i + 1 })}</Text>
<SortIcon
style={{
fontSize: '0.85rem',
opacity: sortCol === i ? 1 : 0.3,
color: sortCol === i ? 'var(--mantine-color-teal-6)' : undefined,
transform: sortCol === i && !sortAsc ? 'scaleY(-1)' : undefined,
}}
/>
</Group>
</Table.Th>
))}
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{sortedDataRows.map((row, ri) => (
<Table.Tr key={ri}>
<Table.Td style={{ color: 'var(--mantine-color-dimmed)', textAlign: 'center', paddingInline: 8 }}>
{ri + 1}
</Table.Td>
{headers.map((_, ci) => (
<Table.Td key={ci} style={{ paddingInline: 8, maxWidth: 300 }}>
<Text size="xs" truncate title={row[ci]}>{row[ci] ?? ''}</Text>
</Table.Td>
))}
</Table.Tr>
))}
</Table.Tbody>
</Table>
</ScrollArea>
</Stack>
);
}
@@ -1,36 +0,0 @@
import { useEffect, useState } from 'react';
import { Box, Paper, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
interface HtmlViewerProps {
file: File;
}
export function HtmlViewer({ file }: HtmlViewerProps) {
const { t } = useTranslation();
const [objectUrl, setObjectUrl] = useState<string | null>(null);
useEffect(() => {
const url = URL.createObjectURL(file);
setObjectUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<Box style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Text size="xs" c="dimmed">{t('viewer.nonPdf.htmlPreviewWarning', { size: formatFileSize(file.size) })}</Text>
</Paper>
{objectUrl && (
<iframe
src={objectUrl}
title={t('viewer.nonPdf.htmlPreview')}
sandbox="allow-scripts"
style={{ flex: 1, border: 'none', background: '#fff' }}
/>
)}
</Box>
);
}
@@ -1,44 +0,0 @@
import { useEffect, useState } from 'react';
import { Box } from '@mantine/core';
interface ImageViewerProps {
file: File;
fileName: string;
}
export function ImageViewer({ file, fileName }: ImageViewerProps) {
const [objectUrl, setObjectUrl] = useState<string | null>(null);
useEffect(() => {
const url = URL.createObjectURL(file);
setObjectUrl(url);
return () => URL.revokeObjectURL(url);
}, [file]);
return (
<Box
style={{
flex: 1,
overflow: 'hidden',
background: 'var(--mantine-color-gray-1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{objectUrl && (
<img
src={objectUrl}
alt={fileName}
draggable={false}
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
display: 'block',
}}
/>
)}
</Box>
);
}
@@ -1,57 +0,0 @@
import { useEffect, useState } from 'react';
import { Box, Center, Paper, ScrollArea, Stack, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
interface JsonViewerProps {
file: File;
}
export function JsonViewer({ file }: JsonViewerProps) {
const { t } = useTranslation();
const [content, setContent] = useState<string | null>(null);
const [isInvalidJson, setIsInvalidJson] = useState(false);
useEffect(() => {
file.text().then(text => {
try {
const parsed = JSON.parse(text);
setContent(JSON.stringify(parsed, null, 2));
setIsInvalidJson(false);
} catch (_e) {
// Show raw content if JSON is invalid
setContent(text);
setIsInvalidJson(true);
}
});
}, [file]);
if (content === null) {
return <Center style={{ flex: 1 }}><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>;
}
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{isInvalidJson && (
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-red-2)', background: 'var(--mantine-color-red-0)', flexShrink: 0 }}>
<Text size="xs" c="red">{t('viewer.nonPdf.invalidJson')}</Text>
</Paper>
)}
<ScrollArea style={{ flex: 1 }} type="auto">
<Box
component="pre"
style={{
margin: 0,
padding: 'var(--mantine-spacing-sm)',
fontFamily: 'monospace',
fontSize: '0.8rem',
lineHeight: 1.6,
whiteSpace: 'pre',
overflowX: 'auto',
}}
>
{content}
</Box>
</ScrollArea>
</Stack>
);
}
@@ -1,53 +0,0 @@
import { Badge, Box, Button, Group } from '@mantine/core';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import { useTranslation } from 'react-i18next';
import type { FileTypeMeta } from '@app/components/viewer/nonpdf/types';
interface NonPdfBannerProps {
meta: FileTypeMeta;
onConvertToPdf?: () => void;
}
export function NonPdfBanner({ meta, onConvertToPdf }: NonPdfBannerProps) {
const { t } = useTranslation();
return (
<Group
gap="xs"
wrap="nowrap"
align="center"
style={{
position: 'absolute',
top: 8,
right: 8,
zIndex: 10,
pointerEvents: 'auto',
}}
>
<Badge
variant="default"
size="lg"
leftSection={
<Box style={{ display: 'flex', alignItems: 'center', fontSize: '0.85rem' }}>
{meta.icon}
</Box>
}
style={{ fontWeight: 600 }}
>
{t('viewer.nonPdf.fileTypeBadge', { type: meta.label })}
</Badge>
{onConvertToPdf && (
<Button
size="xs"
variant="light"
color="orange"
leftSection={<PictureAsPdfIcon style={{ fontSize: '0.9rem' }} />}
onClick={onConvertToPdf}
>
{t('viewer.nonPdf.convertToPdf')}
</Button>
)}
</Group>
);
}
@@ -1,192 +0,0 @@
import React, { useEffect, useState } from 'react';
import { Box, Center, Checkbox, Group, Paper, ScrollArea, Stack, Text } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { formatFileSize } from '@app/utils/fileUtils';
// ─── Markdown renderer ────────────────────────────────────────────────────────
function renderInline(text: string): React.ReactNode[] {
const parts: React.ReactNode[] = [];
// Patterns: **bold**, *italic*, `code`, [link](url)
const re = /(\*\*(.+?)\*\*|\*(.+?)\*|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\))/g;
let last = 0;
let match;
let key = 0;
while ((match = re.exec(text)) !== null) {
if (match.index > last) parts.push(text.slice(last, match.index));
if (match[2]) parts.push(<strong key={key++}>{match[2]}</strong>);
else if (match[3]) parts.push(<em key={key++}>{match[3]}</em>);
else if (match[4]) parts.push(<code key={key++} style={{ background: 'var(--mantine-color-gray-1)', padding: '0 3px', borderRadius: 3, fontFamily: 'monospace', fontSize: '0.85em' }}>{match[4]}</code>);
else if (match[5]) parts.push(<a key={key++} href={match[6]} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--mantine-color-blue-6)' }}>{match[5]}</a>);
last = match.index + match[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts;
}
function renderMarkdown(text: string): React.ReactNode[] {
const lines = text.split('\n');
const elements: React.ReactNode[] = [];
let inCodeBlock = false;
let codeLines: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (line.startsWith('```')) {
if (inCodeBlock) {
elements.push(
<pre key={i} style={{ background: 'var(--mantine-color-gray-1)', padding: '8px 12px', borderRadius: 4, overflowX: 'auto', fontSize: '0.85em', margin: '4px 0' }}>
<code>{codeLines.join('\n')}</code>
</pre>
);
codeLines = [];
inCodeBlock = false;
} else {
inCodeBlock = true;
}
i++;
continue;
}
if (inCodeBlock) {
codeLines.push(line);
i++;
continue;
}
if (line.startsWith('### ')) {
elements.push(<Text key={i} fw={600} size="md" mt="xs" mb={2}>{renderInline(line.slice(4))}</Text>);
} else if (line.startsWith('## ')) {
elements.push(<Text key={i} fw={700} size="lg" mt="sm" mb={4}>{renderInline(line.slice(3))}</Text>);
} else if (line.startsWith('# ')) {
elements.push(<Text key={i} fw={800} size="xl" mt="md" mb={6}>{renderInline(line.slice(2))}</Text>);
} else if (line.startsWith('- ') || line.startsWith('* ')) {
elements.push(
<Group key={i} gap={6} align="flex-start" style={{ paddingLeft: 16 }}>
<Text size="sm" style={{ lineHeight: 1.6, flexShrink: 0 }}>{'\u2022'}</Text>
<Text size="sm" style={{ lineHeight: 1.6 }}>{renderInline(line.slice(2))}</Text>
</Group>
);
} else if (/^\d+\.\s/.test(line)) {
const num = line.match(/^(\d+)\.\s/)?.[1];
const rest = line.replace(/^\d+\.\s/, '');
elements.push(
<Group key={i} gap={6} align="flex-start" style={{ paddingLeft: 16 }}>
<Text size="sm" style={{ lineHeight: 1.6, flexShrink: 0 }}>{num}.</Text>
<Text size="sm" style={{ lineHeight: 1.6 }}>{renderInline(rest)}</Text>
</Group>
);
} else if (line.trim() === '' || line === '---' || line === '***') {
elements.push(<Box key={i} style={{ height: 8 }} />);
} else {
elements.push(<Text key={i} size="sm" style={{ lineHeight: 1.7 }}>{renderInline(line)}</Text>);
}
i++;
}
return elements;
}
// ─── Text / Markdown viewer ───────────────────────────────────────────────────
interface TextViewerProps {
file: File;
isMarkdown: boolean;
}
export function TextViewer({ file, isMarkdown }: TextViewerProps) {
const { t } = useTranslation();
const [content, setContent] = useState<string | null>(null);
const [showLineNumbers, setShowLineNumbers] = useState(!isMarkdown);
const [renderMd, setRenderMd] = useState(isMarkdown);
useEffect(() => {
file.text().then(setContent);
}, [file]);
const lines = content?.split('\n') ?? [];
return (
<Stack gap={0} style={{ height: '100%', flex: 1 }}>
{/* Toolbar */}
<Paper radius={0} p="xs" style={{ borderBottom: '1px solid var(--mantine-color-gray-2)', flexShrink: 0 }}>
<Group gap="md" align="center">
<Text size="xs" c="dimmed">{t('viewer.nonPdf.textStats', { lines: lines.length.toLocaleString(), size: formatFileSize(file.size) })}</Text>
{!isMarkdown && (
<Checkbox
label={<Text size="xs">{t('viewer.nonPdf.lineNumbers')}</Text>}
checked={showLineNumbers}
onChange={e => setShowLineNumbers(e.currentTarget.checked)}
size="xs"
/>
)}
{isMarkdown && (
<Checkbox
label={<Text size="xs">{t('viewer.nonPdf.renderMarkdown')}</Text>}
checked={renderMd}
onChange={e => setRenderMd(e.currentTarget.checked)}
size="xs"
/>
)}
</Group>
</Paper>
{/* Content */}
<ScrollArea style={{ flex: 1 }} p="md">
{content === null ? (
<Center><Text c="dimmed" size="sm">{t('viewer.nonPdf.loading')}</Text></Center>
) : isMarkdown && renderMd ? (
<Box style={{ maxWidth: 800, margin: '0 auto', padding: '8px 0' }}>
{renderMarkdown(content)}
</Box>
) : (
<Box
component="pre"
style={{
fontFamily: 'monospace',
fontSize: '0.8rem',
lineHeight: 1.6,
margin: 0,
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
display: 'table',
width: '100%',
}}
>
{lines.map((line, i) => (
<Box
key={i}
component="div"
style={{ display: 'table-row' }}
>
{showLineNumbers && (
<Box
component="span"
style={{
display: 'table-cell',
paddingRight: 16,
paddingLeft: 4,
textAlign: 'right',
color: 'var(--mantine-color-gray-5)',
userSelect: 'none',
borderRight: '1px solid var(--mantine-color-gray-2)',
minWidth: `${String(lines.length).length + 1}ch`,
}}
>
{i + 1}
</Box>
)}
<Box component="span" style={{ display: 'table-cell', paddingLeft: showLineNumbers ? 12 : 0 }}>
{line || '\u00A0'}
</Box>
</Box>
))}
</Box>
)}
</ScrollArea>
</Stack>
);
}
@@ -1,51 +0,0 @@
import React from 'react';
import ImageIcon from '@mui/icons-material/Image';
import TableChartIcon from '@mui/icons-material/TableChart';
import ArticleIcon from '@mui/icons-material/Article';
import CodeIcon from '@mui/icons-material/Code';
import DataObjectIcon from '@mui/icons-material/DataObject';
import HtmlIcon from '@mui/icons-material/Html';
import type { NonPdfFileType } from '@app/utils/fileUtils';
export interface FileTypeMeta {
label: string;
icon: React.ReactNode;
color: string; // Mantine color name (e.g. 'teal', 'violet')
accentColor: string;
borderColor: string;
bgColor: string;
textColor: string;
}
// Shared neutral color scheme for all file type badges — consistent in light & dark mode
const BADGE_COLORS = {
color: 'gray' as const,
accentColor: 'var(--mantine-color-gray-6)',
borderColor: 'var(--mantine-color-gray-3)',
bgColor: 'var(--mantine-color-gray-0)',
textColor: 'var(--mantine-color-gray-9)',
};
export function getFileTypeMeta(type: NonPdfFileType, fileName?: string): FileTypeMeta {
switch (type) {
case 'image':
return { label: 'Image', icon: React.createElement(ImageIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'csv':
return { label: 'Spreadsheet', icon: React.createElement(TableChartIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'json':
return { label: 'JSON', icon: React.createElement(DataObjectIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'markdown':
return { label: 'Markdown', icon: React.createElement(CodeIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'html':
return { label: 'HTML', icon: React.createElement(HtmlIcon, { fontSize: 'small' }), ...BADGE_COLORS };
case 'text':
return { label: 'Text', icon: React.createElement(ArticleIcon, { fontSize: 'small' }), ...BADGE_COLORS };
default: {
// For unknown types, derive label from the file extension (e.g. ".docx" → "DOCX")
const ext = fileName?.split('.').pop()?.toUpperCase();
const label = ext || 'File';
return { label, icon: React.createElement(ArticleIcon, { fontSize: 'small' }), ...BADGE_COLORS };
}
}
}
@@ -16,7 +16,6 @@ import { BASE_PATH, withBasePath } from '@app/constants/app';
import { useRedaction, useRedactionMode } from '@app/contexts/RedactionContext';
import TextFieldsIcon from '@mui/icons-material/TextFields';
import StraightenIcon from '@mui/icons-material/Straighten';
import LayersIcon from '@mui/icons-material/Layers';
import VolumeUpIcon from '@mui/icons-material/VolumeUp';
import StopIcon from '@mui/icons-material/Stop';
import { useViewerReadAloud } from '@app/components/viewer/useViewerReadAloud';
@@ -27,7 +26,7 @@ export function useViewerRightRailButtons(
) {
const { t, i18n } = useTranslation();
const viewer = useViewer();
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isLayerSidebarVisible, hasLayers, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const { isThumbnailSidebarVisible, isBookmarkSidebarVisible, isAttachmentSidebarVisible, isCommentsSidebarVisible, toggleCommentsSidebar, isSearchInterfaceVisible, registerImmediatePanUpdate } = viewer;
const [isPanning, setIsPanning] = useState<boolean>(() => viewer.getPanState()?.isPanning ?? false);
const { sidebarRefs } = useSidebarContext();
const { position: tooltipPosition } = useRightRailTooltipSide(sidebarRefs, 12);
@@ -84,7 +83,6 @@ export function useViewerRightRailButtons(
const sidebarLabel = t('rightRail.toggleSidebar', 'Toggle Sidebar');
const bookmarkLabel = t('rightRail.toggleBookmarks', 'Toggle Bookmarks');
const attachmentLabel = t('rightRail.toggleAttachments', 'Toggle Attachments');
const layersLabel = t('rightRail.toggleLayers', 'Toggle Layers');
const commentsLabel = t('rightRail.toggleComments', 'Comments');
const printLabel = t('rightRail.print', 'Print PDF');
const annotationsLabel = t('rightRail.annotations', 'Annotations');
@@ -238,18 +236,6 @@ export function useViewerRightRailButtons(
viewer.toggleAttachmentSidebar();
}
},
...(hasLayers ? [{
id: 'viewer-toggle-layers',
icon: <LayersIcon sx={{ fontSize: '1.5rem' }} />,
tooltip: layersLabel,
ariaLabel: layersLabel,
section: 'top' as const,
order: 56.3,
active: isLayerSidebarVisible,
onClick: () => {
viewer.toggleLayerSidebar();
}
}] : []),
{
id: 'viewer-toggle-comments',
icon: <LocalIcon icon="comment" width="1.5rem" height="1.5rem" />,
@@ -438,8 +424,6 @@ export function useViewerRightRailButtons(
isThumbnailSidebarVisible,
isBookmarkSidebarVisible,
isAttachmentSidebarVisible,
isLayerSidebarVisible,
hasLayers,
isSearchInterfaceVisible,
isPanning,
searchLabel,
@@ -450,7 +434,6 @@ export function useViewerRightRailButtons(
sidebarLabel,
bookmarkLabel,
attachmentLabel,
layersLabel,
printLabel,
tooltipPosition,
annotationsLabel,
@@ -86,10 +86,6 @@ export interface ViewerContextType {
toggleBookmarkSidebar: () => void;
isAttachmentSidebarVisible: boolean;
toggleAttachmentSidebar: () => void;
isLayerSidebarVisible: boolean;
toggleLayerSidebar: () => void;
hasLayers: boolean;
setHasLayers: (value: boolean) => void;
isCommentsSidebarVisible: boolean;
setCommentsSidebarVisible: (visible: boolean) => void;
toggleCommentsSidebar: () => void;
@@ -192,8 +188,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
const [isThumbnailSidebarVisible, setIsThumbnailSidebarVisible] = useState(false);
const [isBookmarkSidebarVisible, setIsBookmarkSidebarVisible] = useState(false);
const [isAttachmentSidebarVisible, setIsAttachmentSidebarVisible] = useState(false);
const [isLayerSidebarVisible, setIsLayerSidebarVisible] = useState(false);
const [hasLayers, setHasLayers] = useState(false);
const [isCommentsSidebarVisible, setIsCommentsSidebarVisible] = useState(false);
const [highlightCommentRequest, setHighlightCommentRequest] = useState<{
documentId: string;
@@ -295,10 +289,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
setIsAttachmentSidebarVisible(prev => !prev);
};
const toggleLayerSidebar = () => {
setIsLayerSidebarVisible(prev => !prev);
};
const setCommentsSidebarVisible = (visible: boolean) => {
setIsCommentsSidebarVisible(visible);
};
@@ -464,10 +454,6 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
toggleBookmarkSidebar,
isAttachmentSidebarVisible,
toggleAttachmentSidebar,
isLayerSidebarVisible,
toggleLayerSidebar,
hasLayers,
setHasLayers,
isCommentsSidebarVisible,
setCommentsSidebarVisible,
toggleCommentsSidebar,
@@ -1,8 +0,0 @@
export interface FrontendVersionInfo {
appVersion: string | null | undefined; // undefined = not applicable, null = loading, string = loaded
mismatchVersion: boolean;
}
export function useFrontendVersionInfo(_backendVersion: string | undefined): FrontendVersionInfo {
return { appVersion: undefined, mismatchVersion: false };
}
@@ -1,10 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
/**
* Returns whether the shared (group) signing feature is available.
* Core implementation reads directly from server config.
*/
export function useGroupSigningEnabled(): boolean {
const { config } = useAppConfig();
return config?.storageGroupSigningEnabled === true;
}
@@ -1,18 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
export interface SharingEnabledResult {
sharingEnabled: boolean;
shareLinksEnabled: boolean;
}
/**
* Returns whether file-sharing features are available.
* Core implementation reads directly from server config.
*/
export function useSharingEnabled(): SharingEnabledResult {
const { config } = useAppConfig();
return {
sharingEnabled: config?.storageSharingEnabled === true,
shareLinksEnabled: config?.storageShareLinksEnabled === true,
};
}
@@ -1,4 +0,0 @@
// Default implementation for non-desktop environments (overridden in desktop)
export function useViewerKeyCommand(): (event: KeyboardEvent) => boolean {
return () => false;
}
@@ -0,0 +1,321 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MantineProvider } from '@mantine/core';
// ── i18n ────────────────────────────────────────────────────────────────────
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, fallback?: string | Record<string, unknown>) => {
if (typeof fallback === 'string') return fallback;
return key;
},
}),
initReactI18next: { type: '3rdParty', init: vi.fn() },
}));
// ── react-router-dom: useParams returns our injected token ──────────────────
const mockToken = 'test-token-abc';
vi.mock('react-router-dom', () => ({
useParams: () => ({ token: mockToken }),
}));
// ── Heavy sub-components — stub them out so we don't need full canvas / MUI ─
vi.mock('@app/components/shared/wetSignature/DrawSignatureCanvas', () => ({
DrawSignatureCanvas: ({ onChange }: { onChange: (v: string | null) => void }) => (
<button onClick={() => onChange('sig-data-stub')}>Draw</button>
),
}));
vi.mock('@app/components/shared/wetSignature/SignatureTypeSelector', () => ({
SignatureTypeSelector: () => <div data-testid="sig-type-selector" />,
SignatureType: {},
}));
vi.mock('@app/components/shared/wetSignature/TypeSignatureText', () => ({
TypeSignatureText: () => <div data-testid="type-sig-text" />,
}));
vi.mock('@app/components/shared/wetSignature/UploadSignatureImage', () => ({
UploadSignatureImage: () => <div data-testid="upload-sig-image" />,
}));
vi.mock('@app/components/shared/signing/GuestCertificateChooser', () => ({
GuestCertificateChooser: ({
value,
onChange,
}: {
value: string;
onChange: (v: string) => void;
}) => (
<div data-testid="cert-chooser" data-value={value}>
<button onClick={() => onChange('GUEST_CERT')}>Auto Cert</button>
<button onClick={() => onChange('P12')}>Upload Cert</button>
</div>
),
GuestCertType: {},
}));
vi.mock('@app/types/signingSession', () => ({}));
// ── Component under test ────────────────────────────────────────────────────
import GuestSignPage from './GuestSignPage';
// ── Test wrapper ────────────────────────────────────────────────────────────
const TestWrapper = ({ children }: { children: React.ReactNode }) => (
<MantineProvider>{children}</MantineProvider>
);
// ── Fetch helpers ───────────────────────────────────────────────────────────
function mockFetchSuccess(
sessionData = { sessionId: '1', documentName: 'Contract.pdf', ownerEmail: 'owner@example.com' },
participantData = { id: 1, email: 'guest@example.com', name: 'Guest', status: 'VIEWED' }
) {
vi.stubGlobal(
'fetch',
vi.fn().mockImplementation((url: string) => {
if (url.includes('/session')) {
return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(sessionData) });
}
if (url.includes('/details')) {
return Promise.resolve({
ok: true,
status: 200,
json: () => Promise.resolve(participantData),
});
}
if (url.includes('/document')) {
return Promise.resolve({ ok: true, status: 200 });
}
// submit-signature or decline
return Promise.resolve({ ok: true, status: 200 });
})
);
}
function mockFetchForbidden() {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, status: 403 })
);
}
// ── Tests ───────────────────────────────────────────────────────────────────
describe('GuestSignPage', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders loading state on mount before fetch resolves', () => {
// Never resolve the fetch — stays in loading state
vi.stubGlobal('fetch', vi.fn(() => new Promise(() => {})));
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
expect(screen.getByText(/loading signing session/i)).toBeInTheDocument();
});
it('shows expired message when fetch returns 403', async () => {
mockFetchForbidden();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(
screen.getByText(/This signing link has expired\./i)
).toBeInTheDocument();
});
});
it('shows signed success state when participant status is SIGNED', async () => {
mockFetchSuccess(undefined, {
id: 1,
email: 'guest@example.com',
name: 'Guest',
status: 'SIGNED',
});
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(
screen.getByText(/Your signature has been submitted successfully\./i)
).toBeInTheDocument();
});
});
it('shows declined state when participant status is DECLINED', async () => {
mockFetchSuccess(undefined, {
id: 1,
email: 'guest@example.com',
name: 'Guest',
status: 'DECLINED',
});
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(
screen.getByText(/You have declined this signing request\./i)
).toBeInTheDocument();
});
});
it('renders the signing form in ready state', async () => {
mockFetchSuccess();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByText('Sign Document')).toBeInTheDocument();
expect(screen.getByText('Contract.pdf')).toBeInTheDocument();
});
});
it('shows auto-cert chooser selected by default', async () => {
mockFetchSuccess();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
const chooser = screen.getByTestId('cert-chooser');
expect(chooser).toHaveAttribute('data-value', 'GUEST_CERT');
});
});
it('submits with GUEST_CERT when auto cert is selected', async () => {
const user = userEvent.setup();
mockFetchSuccess();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByText('Sign Document')).toBeInTheDocument();
});
const submitButton = screen.getByText('Submit Signature');
await user.click(submitButton);
await waitFor(() => {
const fetchMock = vi.mocked(fetch);
const submitCall = fetchMock.mock.calls.find(([url]) =>
String(url).includes('submit-signature')
);
expect(submitCall).toBeDefined();
const body = submitCall![1]!.body as FormData;
expect(body.get('certType')).toBe('GUEST_CERT');
expect(body.get('participantToken')).toBe(mockToken);
});
});
it('shows success state after successful submission', async () => {
const user = userEvent.setup();
mockFetchSuccess();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByText('Sign Document')).toBeInTheDocument();
});
await user.click(screen.getByText('Submit Signature'));
await waitFor(() => {
expect(
screen.getByText(/Your signature has been submitted successfully\./i)
).toBeInTheDocument();
});
});
it('opens decline confirmation modal when Decline is clicked', async () => {
const user = userEvent.setup();
mockFetchSuccess();
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByText('Sign Document')).toBeInTheDocument();
});
// Click the outer Decline button (variant="subtle")
const outerDeclineBtn = screen.getAllByRole('button').find(
(btn) => btn.getAttribute('data-variant') === 'subtle'
);
expect(outerDeclineBtn).toBeDefined();
await user.click(outerDeclineBtn!);
// Modal confirmation dialog should appear
await waitFor(() => {
expect(screen.getByText('Decline signing?')).toBeInTheDocument();
expect(screen.getByText(/Are you sure you want to decline/i)).toBeInTheDocument();
});
// Cancel button should close the modal
await user.click(screen.getByRole('button', { name: /cancel/i }));
await waitFor(() => {
expect(screen.queryByText('Decline signing?')).not.toBeInTheDocument();
});
});
it('shows error state when fetch fails with non-403 error', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, status: 500 })
);
render(
<TestWrapper>
<GuestSignPage />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByText(/Something went wrong/i)).toBeInTheDocument();
});
});
});
+385
View File
@@ -0,0 +1,385 @@
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
Alert,
Button,
Center,
Divider,
Group,
Loader,
Modal,
Paper,
Stack,
Text,
Title,
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { useTranslation } from 'react-i18next';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import { DrawSignatureCanvas } from '@app/components/shared/wetSignature/DrawSignatureCanvas';
import { SignatureTypeSelector, SignatureType } from '@app/components/shared/wetSignature/SignatureTypeSelector';
import { TypeSignatureText } from '@app/components/shared/wetSignature/TypeSignatureText';
import { UploadSignatureImage } from '@app/components/shared/wetSignature/UploadSignatureImage';
import { GuestCertificateChooser, GuestCertType } from '@app/components/shared/signing/GuestCertificateChooser';
import type { WetSignatureMetadata } from '@app/types/signingSession';
// ─── Types ──────────────────────────────────────────────────────────────────
interface SessionInfo {
sessionId: string;
documentName: string;
ownerEmail: string;
message?: string;
dueDate?: string;
}
interface ParticipantDetails {
id: number;
email: string;
name: string;
status: string;
expiresAt?: string;
}
type PageState = 'loading' | 'ready' | 'expired' | 'signed' | 'declined' | 'error';
// ─── Component ──────────────────────────────────────────────────────────────
export default function GuestSignPage() {
const { token } = useParams<{ token: string }>();
const { t } = useTranslation();
// Page state
const [pageState, setPageState] = useState<PageState>('loading');
const [errorMessage, setErrorMessage] = useState<string>('');
const [session, setSession] = useState<SessionInfo | null>(null);
const [participant, setParticipant] = useState<ParticipantDetails | null>(null);
// Signature state
const [sigType, setSigType] = useState<SignatureType>('draw');
const [sigData, setSigData] = useState<string | null>(null);
// Certificate state
const [certType, setCertType] = useState<GuestCertType>('GUEST_CERT');
const [p12File, setP12File] = useState<File | null>(null);
const [certPassword, setCertPassword] = useState('');
// Submission state
const [submitting, setSubmitting] = useState(false);
const [declineOpen, { open: openDecline, close: closeDecline }] = useDisclosure(false);
const [declining, setDeclining] = useState(false);
// ── Load session on mount ──────────────────────────────────────────────
useEffect(() => {
if (!token) {
setPageState('error');
setErrorMessage('Missing signing token.');
return;
}
async function load() {
try {
const [sessionRes, detailsRes] = await Promise.all([
fetch(`/api/v1/workflow/participant/session?token=${encodeURIComponent(token!)}`),
fetch(`/api/v1/workflow/participant/details?token=${encodeURIComponent(token!)}`),
]);
if (sessionRes.status === 403 || detailsRes.status === 403) {
setPageState('expired');
return;
}
if (!sessionRes.ok || !detailsRes.ok) {
setPageState('error');
setErrorMessage('Unable to load signing session.');
return;
}
const sessionData: SessionInfo = await sessionRes.json();
const participantData: ParticipantDetails = await detailsRes.json();
setSession(sessionData);
setParticipant(participantData);
if (participantData.status === 'SIGNED') {
setPageState('signed');
} else if (participantData.status === 'DECLINED') {
setPageState('declined');
} else {
setPageState('ready');
}
} catch {
setPageState('error');
setErrorMessage('An unexpected error occurred.');
}
}
load();
}, [token]);
// ── Submit signature ───────────────────────────────────────────────────
async function handleSubmit() {
if (!token) return;
setSubmitting(true);
try {
const formData = new FormData();
formData.append('participantToken', token);
formData.append('certType', certType);
if (certType === 'P12') {
if (!p12File) {
alert(t('guestSigning.certFileRequired', 'Please select a certificate file.'));
setSubmitting(false);
return;
}
formData.append('p12File', p12File);
formData.append('password', certPassword);
}
if (sigData) {
const wetSig: WetSignatureMetadata = {
type: sigType === 'type' ? 'text' : sigType === 'draw' ? 'canvas' : 'image',
data: sigData,
page: 0,
x: 50,
y: 50,
width: 200,
height: 60,
};
formData.append('wetSignaturesData', JSON.stringify([wetSig]));
}
const res = await fetch('/api/v1/workflow/participant/submit-signature', {
method: 'POST',
body: formData,
});
if (!res.ok) {
const body = await res.text();
setErrorMessage(body || t('guestSigning.submitError', 'Failed to submit signature.'));
setPageState('error');
return;
}
setPageState('signed');
} finally {
setSubmitting(false);
}
}
// ── Decline ────────────────────────────────────────────────────────────
async function handleDecline() {
if (!token) return;
setDeclining(true);
try {
const res = await fetch(
`/api/v1/workflow/participant/decline?token=${encodeURIComponent(token)}`,
{ method: 'POST' }
);
if (res.ok) {
setPageState('declined');
}
} finally {
setDeclining(false);
closeDecline();
}
}
// ── Render helpers ─────────────────────────────────────────────────────
if (pageState === 'loading') {
return (
<Center h="100vh">
<Stack align="center" gap="md">
<Loader size="lg" />
<Text>{t('guestSigning.loadingSession', 'Loading signing session...')}</Text>
</Stack>
</Center>
);
}
if (pageState === 'expired') {
return (
<Center h="100vh">
<Paper shadow="sm" p="xl" maw={480} w="100%">
<Stack align="center" gap="md">
<ErrorOutlineIcon style={{ fontSize: 48, color: '#fa5252' }} />
<Title order={3}>{t('guestSigning.expiredToken', 'This signing link has expired.')}</Title>
<Text c="dimmed" ta="center">
{t('guestSigning.expiredNote', 'Please contact the document owner for a new link.')}
</Text>
</Stack>
</Paper>
</Center>
);
}
if (pageState === 'signed') {
return (
<Center h="100vh">
<Paper shadow="sm" p="xl" maw={480} w="100%">
<Stack align="center" gap="md">
<CheckCircleIcon style={{ fontSize: 48, color: '#40c057' }} />
<Title order={3}>{t('guestSigning.submitSuccess', 'Your signature has been submitted successfully.')}</Title>
<Text c="dimmed" ta="center">
{t('guestSigning.signedNote', 'The document owner has been notified. You may close this window.')}
</Text>
</Stack>
</Paper>
</Center>
);
}
if (pageState === 'declined') {
return (
<Center h="100vh">
<Paper shadow="sm" p="xl" maw={480} w="100%">
<Stack align="center" gap="md">
<ErrorOutlineIcon style={{ fontSize: 48, color: '#fab005' }} />
<Title order={3}>{t('guestSigning.declineSuccess', 'You have declined this signing request.')}</Title>
<Text c="dimmed" ta="center">
{t('guestSigning.declinedNote', 'The document owner has been notified. You may close this window.')}
</Text>
</Stack>
</Paper>
</Center>
);
}
if (pageState === 'error') {
return (
<Center h="100vh">
<Paper shadow="sm" p="xl" maw={480} w="100%">
<Stack align="center" gap="md">
<ErrorOutlineIcon style={{ fontSize: 48, color: '#fa5252' }} />
<Title order={3}>{t('guestSigning.errorTitle', 'Something went wrong')}</Title>
<Text c="dimmed" ta="center">{errorMessage}</Text>
</Stack>
</Paper>
</Center>
);
}
// ── Main signing form ──────────────────────────────────────────────────
return (
<Center py="xl" px="md">
<Paper shadow="sm" p="xl" maw={680} w="100%">
<Stack gap="lg">
{/* Header */}
<Stack gap="xs">
<Title order={2}>{t('guestSigning.pageTitle', 'Sign Document')}</Title>
{session && (
<>
<Text size="lg" fw={500}>{session.documentName}</Text>
<Text c="dimmed" size="sm">
{t('guestSigning.requestedBy', 'Requested by {{owner}}', {
owner: session.ownerEmail,
})}
</Text>
{session.dueDate && (
<Text c="orange" size="sm">
{t('guestSigning.dueDate', 'Due {{date}}', { date: session.dueDate })}
</Text>
)}
{session.message && (
<Alert color="gray" variant="light">
{session.message}
</Alert>
)}
</>
)}
</Stack>
<Divider />
{/* PDF preview */}
{token && (
<Stack gap="xs">
<Text fw={500} size="sm">
{t('guestSigning.documentPreview', 'Document')}
</Text>
<iframe
src={`/api/v1/workflow/participant/document?token=${encodeURIComponent(token)}`}
title="Document to sign"
style={{ width: '100%', height: 400, border: '1px solid #dee2e6', borderRadius: 4 }}
/>
</Stack>
)}
<Divider />
{/* Certificate chooser */}
<GuestCertificateChooser
value={certType}
onChange={setCertType}
onFileChange={setP12File}
onPasswordChange={setCertPassword}
p12File={p12File}
password={certPassword}
/>
<Divider />
{/* Wet signature */}
<Stack gap="sm">
<Text fw={500} size="sm">
{t('guestSigning.signatureTitle', 'Your Signature')}
</Text>
<SignatureTypeSelector value={sigType} onChange={setSigType} />
{sigType === 'draw' && (
<DrawSignatureCanvas signature={sigData} onChange={setSigData} />
)}
{sigType === 'type' && (
<TypeSignatureText value={sigData ?? ''} onChange={setSigData} />
)}
{sigType === 'upload' && (
<UploadSignatureImage value={sigData} onChange={setSigData} />
)}
</Stack>
<Divider />
{/* Actions */}
<Group justify="space-between">
<Button variant="subtle" color="red" onClick={openDecline} disabled={submitting}>
{t('guestSigning.declineButton', 'Decline')}
</Button>
<Button onClick={handleSubmit} loading={submitting}>
{t('guestSigning.submitButton', 'Submit Signature')}
</Button>
</Group>
</Stack>
</Paper>
{/* Decline confirmation modal */}
<Modal
opened={declineOpen}
onClose={closeDecline}
title={t('guestSigning.declineConfirmTitle', 'Decline signing?')}
centered
>
<Stack gap="md">
<Text>
{t(
'guestSigning.declineConfirmBody',
"Are you sure you want to decline? This action cannot be undone."
)}
</Text>
<Group justify="flex-end">
<Button variant="default" onClick={closeDecline}>
{t('common.cancel', 'Cancel')}
</Button>
<Button color="red" onClick={handleDecline} loading={declining}>
{t('guestSigning.declineButton', 'Decline')}
</Button>
</Group>
</Stack>
</Modal>
</Center>
);
}
+458 -151
View File
@@ -1,184 +1,491 @@
/**
* End-to-End Tests for Convert Tool
*
* All backend API calls are mocked via page.route() — no real backend required.
* The Vite dev server must be running (handled by playwright.config.ts webServer).
* These tests dynamically discover available conversion endpoints and test them.
* Tests are automatically skipped if the backend endpoint is not available.
*
* Run with: npm run test:e2e or npx playwright test
*/
import { test, expect, type Page } from '@playwright/test';
import path from 'path';
import { test, expect, Page } from '@playwright/test';
import {
conversionDiscovery,
type ConversionEndpoint
} from '@app/tests/helpers/conversionEndpointDiscovery';
import * as path from 'path';
import * as fs from 'fs';
const FIXTURES_DIR = path.join(__dirname, '../test-fixtures');
const SAMPLE_PDF = path.join(FIXTURES_DIR, 'sample.pdf');
// Test configuration
const BASE_URL = process.env.BASE_URL || 'http://localhost:5173';
// ---------------------------------------------------------------------------
// Endpoint availability map — all conversion endpoints enabled
// ---------------------------------------------------------------------------
const MOCK_ENDPOINTS_AVAILABILITY = Object.fromEntries(
[
'pdf-to-img', 'img-to-pdf', 'pdf-to-word', 'file-to-pdf', 'pdf-to-text',
'pdf-to-html', 'pdf-to-xml', 'pdf-to-csv', 'pdf-to-xlsx', 'pdf-to-pdfa',
'pdf-to-pdfx', 'pdf-to-presentation', 'pdf-to-markdown', 'pdf-to-cbz',
'pdf-to-cbr', 'pdf-to-epub', 'html-to-pdf', 'svg-to-pdf', 'markdown-to-pdf',
'eml-to-pdf', 'cbz-to-pdf', 'cbr-to-pdf',
].map((k) => [k, { enabled: true }])
);
/**
* Resolves test fixture paths dynamically based on current working directory.
* Works from both top-level project directory and frontend subdirectory.
*/
function resolveTestFixturePath(filename: string): string {
const cwd = process.cwd();
// ---------------------------------------------------------------------------
// Helper: mock all standard app APIs needed to load the main UI
// ---------------------------------------------------------------------------
async function mockAppApis(page: Page) {
// Backend probe — must return UP so Landing shows app in anonymous mode
await page.route('**/api/v1/info/status', (route) =>
route.fulfill({ json: { status: 'UP' } })
);
// Try frontend/src/tests/test-fixtures/ first (from top-level)
const topLevelPath = path.join(cwd, 'frontend', 'src', 'tests', 'test-fixtures', filename);
if (fs.existsSync(topLevelPath)) {
return topLevelPath;
}
// App config — enableLogin:false puts the app in anonymous mode
await page.route('**/api/v1/config/app-config', (route) =>
route.fulfill({
json: { enableLogin: false, languages: ['en-GB'], defaultLocale: 'en-GB' },
})
);
// Try src/tests/test-fixtures/ (from frontend directory)
const frontendPath = path.join(cwd, 'src', 'tests', 'test-fixtures', filename);
if (fs.existsSync(frontendPath)) {
return frontendPath;
}
// Auth — fallback if anything calls auth/me
await page.route('**/api/v1/auth/me', (route) =>
route.fulfill({
json: { id: 1, username: 'testuser', email: 'test@example.com', roles: ['ROLE_USER'] },
})
);
// Try relative path from current test file location
const relativePath = path.join(__dirname, '..', 'test-fixtures', filename);
if (fs.existsSync(relativePath)) {
return relativePath;
}
// Endpoint availability — queried by ConvertSettings
await page.route('**/api/v1/config/endpoints-availability', (route) =>
route.fulfill({ json: MOCK_ENDPOINTS_AVAILABILITY })
);
// Single-endpoint check — queried by Convert.tsx for the execute button
await page.route('**/api/v1/config/endpoint-enabled*', (route) =>
route.fulfill({ json: true })
);
// Group-enabled check
await page.route('**/api/v1/config/group-enabled*', (route) =>
route.fulfill({ json: true })
);
// Footer info — non-critical
await page.route('**/api/v1/ui-data/footer-info', (route) =>
route.fulfill({ json: {} })
);
// Proprietary endpoints — silence proxy errors in the Vite dev server
await page.route('**/api/v1/proprietary/**', (route) =>
route.fulfill({ json: {} })
);
// Fallback to the original path format (should work from top-level)
return path.join('.', 'frontend', 'src', 'tests', 'test-fixtures', filename);
}
// ---------------------------------------------------------------------------
// Helper: upload a file through the Files modal
// Uses the HiddenFileInput (data-testid="file-input") which has the correct
// onChange handler. Waits for the modal to auto-close after upload.
// ---------------------------------------------------------------------------
async function uploadFile(page: Page, filePath: string) {
await page.getByTestId('files-button').click();
// Test file paths (dynamically resolved based on current working directory)
const TEST_FILES = {
pdf: resolveTestFixturePath('sample.pdf'),
docx: resolveTestFixturePath('sample.docx'),
doc: resolveTestFixturePath('sample.doc'),
pptx: resolveTestFixturePath('sample.pptx'),
ppt: resolveTestFixturePath('sample.ppt'),
xlsx: resolveTestFixturePath('sample.xlsx'),
xls: resolveTestFixturePath('sample.xls'),
png: resolveTestFixturePath('sample.png'),
jpg: resolveTestFixturePath('sample.jpg'),
jpeg: resolveTestFixturePath('sample.jpeg'),
gif: resolveTestFixturePath('sample.gif'),
bmp: resolveTestFixturePath('sample.bmp'),
tiff: resolveTestFixturePath('sample.tiff'),
webp: resolveTestFixturePath('sample.webp'),
md: resolveTestFixturePath('sample.md'),
eml: resolveTestFixturePath('sample.eml'),
html: resolveTestFixturePath('sample.html'),
txt: resolveTestFixturePath('sample.txt'),
xml: resolveTestFixturePath('sample.xml'),
csv: resolveTestFixturePath('sample.csv')
};
// File format to test file mapping
const getTestFileForFormat = (format: string): string => {
const formatMap: Record<string, string> = {
'pdf': TEST_FILES.pdf,
'docx': TEST_FILES.docx,
'doc': TEST_FILES.doc,
'pptx': TEST_FILES.pptx,
'ppt': TEST_FILES.ppt,
'xlsx': TEST_FILES.xlsx,
'xls': TEST_FILES.xls,
'office': TEST_FILES.docx, // Default office file
'image': TEST_FILES.png, // Default image file
'png': TEST_FILES.png,
'jpg': TEST_FILES.jpg,
'jpeg': TEST_FILES.jpeg,
'gif': TEST_FILES.gif,
'bmp': TEST_FILES.bmp,
'tiff': TEST_FILES.tiff,
'webp': TEST_FILES.webp,
'md': TEST_FILES.md,
'eml': TEST_FILES.eml,
'html': TEST_FILES.html,
'txt': TEST_FILES.txt,
'xml': TEST_FILES.xml,
'csv': TEST_FILES.csv
};
return formatMap[format] || TEST_FILES.pdf; // Fallback to PDF
};
// Expected file extensions for target formats
const getExpectedExtension = (toFormat: string): string => {
const extensionMap: Record<string, string> = {
'pdf': '.pdf',
'docx': '.docx',
'pptx': '.pptx',
'txt': '.txt',
'html': '.zip', // HTML is zipped
'xml': '.xml',
'csv': '.csv',
'md': '.md',
'image': '.png', // Default for image conversion
'png': '.png',
'jpg': '.jpg',
'jpeg': '.jpeg',
'gif': '.gif',
'bmp': '.bmp',
'tiff': '.tiff',
'webp': '.webp',
'pdfa': '.pdf'
};
return extensionMap[toFormat] || '.pdf';
};
/**
* Helper function to upload files through the modal system
*/
async function uploadFileViaModal(page: Page, filePath: string) {
// Click the Files button in the QuickAccessBar to open the modal
await page.click('[data-testid="files-button"]');
// Wait for the modal to open
await page.waitForSelector('.mantine-Modal-overlay', { state: 'visible', timeout: 5000 });
await page.locator('[data-testid="file-input"]').setInputFiles(filePath);
// Modal auto-closes after file is selected
await page.waitForSelector('.mantine-Modal-overlay', { state: 'hidden', timeout: 10000 });
//await page.waitForSelector('[data-testid="file-upload-modal"]', { timeout: 5000 });
// Upload the file through the modal's file input
await page.setInputFiles('input[type="file"]', filePath);
// Wait for the file to be processed and the modal to close
await page.waitForSelector('[data-testid="file-upload-modal"]', { state: 'hidden' });
// Wait for the file thumbnail to appear in the main interface
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 10000 });
}
// ---------------------------------------------------------------------------
// Helper: navigate to the Convert tool panel
// Tools use data-tour="tool-button-{key}" anchors in the ToolPanel.
// After clicking, the URL changes to /convert and the settings appear.
// ---------------------------------------------------------------------------
async function navigateToConvert(page: Page) {
await page.locator('[data-tour="tool-button-convert"]').click();
/**
* Generic test function for any conversion
*/
async function testConversion(page: Page, conversion: ConversionEndpoint) {
const expectedExtension = getExpectedExtension(conversion.toFormat);
console.log(`Testing ${conversion.endpoint}: ${conversion.fromFormat} → ${conversion.toFormat}`);
// File should already be uploaded, click the Convert tool button
await page.click('[data-testid="tool-convert"]');
// Wait for the FileEditor to load in convert mode with file thumbnails
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 5000 });
// Click the file thumbnail checkbox to select it in the FileEditor
await page.click('[data-testid="file-thumbnail-checkbox"]');
// Wait for the conversion settings to appear after file selection
await page.waitForSelector('[data-testid="convert-from-dropdown"]', { timeout: 5000 });
// Select FROM format
await page.click('[data-testid="convert-from-dropdown"]');
const fromFormatOption = page.locator(`[data-testid="format-option-${conversion.fromFormat}"]`);
await fromFormatOption.scrollIntoViewIfNeeded();
await fromFormatOption.click();
// Select TO format
await page.click('[data-testid="convert-to-dropdown"]');
const toFormatOption = page.locator(`[data-testid="format-option-${conversion.toFormat}"]`);
await toFormatOption.scrollIntoViewIfNeeded();
await toFormatOption.click();
// Handle format-specific options
if (conversion.toFormat === 'image' || ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'webp'].includes(conversion.toFormat)) {
// Set image conversion options if they appear
const imageOptionsVisible = await page.locator('[data-testid="image-options-section"]').isVisible().catch(() => false);
if (imageOptionsVisible) {
// Click the color type dropdown and select "Color"
await page.click('[data-testid="color-type-select"]');
await page.getByRole('option', { name: 'Color' }).click();
// Set DPI value
await page.fill('[data-testid="dpi-input"]', '150');
// Click the output type dropdown and select "Multiple"
await page.click('[data-testid="output-type-select"]');
await page.getByRole('option', { name: 'single' }).click();
}
}
if (conversion.fromFormat === 'image' && conversion.toFormat === 'pdf') {
// Set PDF creation options if they appear
const pdfOptionsVisible = await page.locator('[data-testid="pdf-options-section"]').isVisible().catch(() => false);
if (pdfOptionsVisible) {
// Click the color type dropdown and select "Color"
await page.click('[data-testid="color-type-select"]');
await page.locator('[data-value="color"]').click();
}
}
if (conversion.fromFormat === 'pdf' && conversion.toFormat === 'csv') {
// Set CSV extraction options if they appear
const csvOptionsVisible = await page.locator('[data-testid="csv-options-section"]').isVisible().catch(() => false);
if (csvOptionsVisible) {
// Set specific page numbers for testing (test pages 1-2)
await page.fill('[data-testid="page-numbers-input"]', '1-2');
}
}
// Start conversion
await page.click('[data-testid="convert-button"]');
// Wait for conversion to complete (with generous timeout)
await page.waitForSelector('[data-testid="download-button"]', { timeout: 60000 });
// Verify download is available
const downloadButton = page.locator('[data-testid="download-button"]');
await expect(downloadButton).toBeVisible();
// Start download and verify file
const downloadPromise = page.waitForEvent('download');
await downloadButton.click();
const download = await downloadPromise;
// Verify file extension
expect(download.suggestedFilename()).toMatch(new RegExp(`\\${expectedExtension}$`));
// Save and verify file is not empty
const path = await download.path();
if (path) {
const fs = require('fs');
const stats = fs.statSync(path);
expect(stats.size).toBeGreaterThan(0);
// Format-specific validations
if (conversion.toFormat === 'pdf' || conversion.toFormat === 'pdfa') {
// Verify PDF header
const buffer = fs.readFileSync(path);
const header = buffer.toString('utf8', 0, 4);
expect(header).toBe('%PDF');
}
if (conversion.toFormat === 'txt') {
// Verify text content exists
const content = fs.readFileSync(path, 'utf8');
expect(content.length).toBeGreaterThan(0);
}
if (conversion.toFormat === 'csv') {
// Verify CSV content contains separators
const content = fs.readFileSync(path, 'utf8');
expect(content).toContain(',');
}
}
}
// ---------------------------------------------------------------------------
// Helper: select the TO format in the convert dropdown
// The FROM format is auto-detected from the uploaded file (e.g. PDF → "Document (PDF)").
// Opening the TO dropdown renders format-option-{value} buttons in a portal.
// ---------------------------------------------------------------------------
async function selectToFormat(page: Page, toValue: string) {
await page.getByTestId('convert-to-dropdown').click();
await page.getByTestId(`format-option-${toValue}`).click();
}
// Discover conversions at module level before tests are defined
let availableConversions: ConversionEndpoint[] = [];
let unavailableConversions: ConversionEndpoint[] = [];
// Pre-populate conversions synchronously for test generation
(async () => {
try {
availableConversions = await conversionDiscovery.getAvailableConversions();
unavailableConversions = await conversionDiscovery.getUnavailableConversions();
} catch (error) {
console.error('Failed to discover conversions during module load:', error);
}
})();
test.describe('Convert Tool E2E Tests', () => {
test.beforeAll(async () => {
// Re-discover to ensure fresh data at test time
console.log('Re-discovering available conversion endpoints...');
availableConversions = await conversionDiscovery.getAvailableConversions();
unavailableConversions = await conversionDiscovery.getUnavailableConversions();
console.log(`Found ${availableConversions.length} available conversions:`);
availableConversions.forEach(conv => {
console.log(` ✓ ${conv.endpoint}: ${conv.fromFormat} → ${conv.toFormat}`);
});
if (unavailableConversions.length > 0) {
console.log(`Found ${unavailableConversions.length} unavailable conversions:`);
unavailableConversions.forEach(conv => {
console.log(` ✗ ${conv.endpoint}: ${conv.fromFormat} → ${conv.toFormat}`);
});
}
});
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test.describe('Convert Tool', () => {
test.beforeEach(async ({ page }) => {
await mockAppApis(page);
await page.goto('/?bypassOnboarding=true');
// Navigate to the homepage
await page.goto(`${BASE_URL}`);
// Wait for the page to load
await page.waitForLoadState('networkidle');
// Wait for the QuickAccessBar to appear
await page.waitForSelector('[data-testid="files-button"]', { timeout: 10000 });
});
test('convert button is disabled before a TO format is selected', async ({ page }) => {
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
test.describe('Dynamic Conversion Tests', () => {
// FROM is auto-detected as PDF; TO not selected → button visible but disabled
const convertBtn = page.getByTestId('convert-button');
await expect(convertBtn).toBeVisible({ timeout: 3000 });
await expect(convertBtn).toBeDisabled();
// Generate a test for each potentially available conversion
// We'll discover all possible conversions and then skip unavailable ones at runtime
test('PDF to PNG conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/img',
fromFormat: 'pdf',
toFormat: 'png',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to DOCX conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/word',
fromFormat: 'pdf',
toFormat: 'docx',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('DOCX to PDF conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/file/pdf',
fromFormat: 'docx',
toFormat: 'pdf',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('Image to PDF conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/img/pdf',
fromFormat: 'png',
toFormat: 'pdf',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to TXT conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/text',
fromFormat: 'pdf',
toFormat: 'txt',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to HTML conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/html',
fromFormat: 'pdf',
toFormat: 'html',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to XML conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/xml',
fromFormat: 'pdf',
toFormat: 'xml',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to CSV conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/csv',
fromFormat: 'pdf',
toFormat: 'csv',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
test('PDF to PDFA conversion', async ({ page }) => {
const conversion: ConversionEndpoint = {
endpoint: '/api/v1/convert/pdf/pdfa',
fromFormat: 'pdf',
toFormat: 'pdfa',
description: '',
apiPath: ''
};
const isAvailable = availableConversions.some(c => c.apiPath === conversion.endpoint);
test.skip(!isAvailable, `Endpoint ${conversion.endpoint} is not available`);
const testFile = getTestFileForFormat(conversion.fromFormat);
await uploadFileViaModal(page, testFile);
await testConversion(page, conversion);
});
});
test('successful PDF to PNG conversion shows download option', async ({ page }) => {
// Minimal valid PNG header (8 bytes signature + padding)
const fakePng = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
...Array(504).fill(0),
]);
test.describe('Static Tests', () => {
await page.route('**/api/v1/convert/pdf/img', (route) =>
route.fulfill({
status: 200,
contentType: 'image/png',
headers: { 'Content-Disposition': 'attachment; filename="sample.png"' },
body: fakePng,
})
);
// Test that disabled conversions don't appear in dropdowns when they shouldn't
test('should not show conversion button when no valid conversions available', async ({ page }) => {
// This test ensures the convert button is disabled when no valid conversion is possible
await uploadFileViaModal(page, TEST_FILES.pdf);
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
await selectToFormat(page, 'png');
await page.getByTestId('convert-button').click();
// Click the Convert tool button
await page.click('[data-testid="tool-convert"]');
await expect(page.getByTestId('download-result-button')).toBeVisible({ timeout: 10000 });
});
// Wait for convert mode and select file
await page.waitForSelector('[data-testid="file-thumbnail"]', { timeout: 5000 });
await page.click('[data-testid="file-thumbnail-checkbox"]');
test('conversion API error shows error notification', async ({ page }) => {
await page.route('**/api/v1/convert/pdf/img', (route) =>
route.fulfill({
status: 500,
contentType: 'text/plain',
body: 'Internal server error: conversion failed',
})
);
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
await selectToFormat(page, 'png');
await page.getByTestId('convert-button').click();
// Mantine Notification renders as role="alert"
await expect(page.getByRole('alert').first()).toBeVisible({ timeout: 5000 });
});
test('convert button becomes enabled after selecting a valid TO format', async ({ page }) => {
await uploadFile(page, SAMPLE_PDF);
await navigateToConvert(page);
// Before selecting TO format — button visible but disabled
const convertBtn = page.getByTestId('convert-button');
await expect(convertBtn).toBeVisible({ timeout: 3000 });
await expect(convertBtn).toBeDisabled();
// After selecting PNG as TO format — button enabled
await selectToFormat(page, 'png');
await expect(convertBtn).toBeEnabled({ timeout: 3000 });
// Don't select any formats - convert button should not exist
const convertButton = page.locator('[data-testid="convert-button"]');
await expect(convertButton).toHaveCount(0);
});
});
});
@@ -0,0 +1,342 @@
/**
* E2E tests for the Guest Signing flow (/sign/:token).
*
* These tests use Playwright's route mocking to intercept all API calls, so no
* running backend is required. They cover the full page-state machine from the
* browser perspective.
*
* Run: npx playwright test src/core/tests/guestSigning/GuestSigningE2E.spec.ts
*/
import { test, expect, Page, Route } from '@playwright/test';
// ─── Shared fixtures ─────────────────────────────────────────────────────────
const TOKEN = 'test-share-token-abc';
const SIGN_URL = `/sign/${TOKEN}`;
const SESSION_PAYLOAD = {
sessionId: 'session-1',
documentName: 'Contract_2026.pdf',
ownerEmail: 'owner@company.com',
message: 'Please review and sign by end of week.',
};
const PARTICIPANT_PENDING = {
id: 1,
email: 'guest@example.com',
name: 'Guest Signer',
status: 'PENDING',
};
const PARTICIPANT_SIGNED = { ...PARTICIPANT_PENDING, status: 'SIGNED' };
const PARTICIPANT_DECLINED = { ...PARTICIPANT_PENDING, status: 'DECLINED' };
// ─── Route helpers ────────────────────────────────────────────────────────────
async function mockHappyPath(page: Page) {
await page.route('**/workflow/participant/session**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_PENDING) })
);
await page.route('**/workflow/participant/document**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/pdf', body: Buffer.from('%PDF-1.4 stub') })
);
await page.route('**/workflow/participant/submit-signature', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'SIGNED' }) })
);
await page.route('**/workflow/participant/decline**', (route: Route) =>
route.fulfill({ status: 200 })
);
}
async function mockForbidden(page: Page) {
await page.route('**/workflow/participant/**', (route: Route) =>
route.fulfill({ status: 403 })
);
}
async function mockAlreadySigned(page: Page) {
await page.route('**/workflow/participant/session**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_SIGNED) })
);
}
async function mockAlreadyDeclined(page: Page) {
await page.route('**/workflow/participant/session**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route: Route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_DECLINED) })
);
}
async function mockServerError(page: Page) {
await page.route('**/workflow/participant/**', (route: Route) =>
route.fulfill({ status: 500 })
);
}
// ─── Tests ────────────────────────────────────────────────────────────────────
test.describe('GuestSignPage', () => {
// ── Page state machine ──────────────────────────────────────────────────
test('shows loading spinner before API responds', async ({ page }) => {
// Delay the session response so we can catch the loading state
await page.route('**/workflow/participant/session**', async (route) => {
await new Promise(resolve => setTimeout(resolve, 500));
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) });
});
await page.route('**/workflow/participant/details**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_PENDING) })
);
await page.goto(SIGN_URL);
await expect(page.getByText(/loading signing session/i)).toBeVisible();
});
test('shows expired message for 403 response', async ({ page }) => {
await mockForbidden(page);
await page.goto(SIGN_URL);
await expect(page.getByText(/this signing link has expired/i)).toBeVisible();
await expect(page.getByText(/contact the document owner for a new link/i)).toBeVisible();
});
test('shows already-signed state when participant status is SIGNED', async ({ page }) => {
await mockAlreadySigned(page);
await page.goto(SIGN_URL);
await expect(page.getByText(/your signature has been submitted successfully/i)).toBeVisible();
await expect(page.getByText(/you may close this window/i)).toBeVisible();
});
test('shows declined state when participant status is DECLINED', async ({ page }) => {
await mockAlreadyDeclined(page);
await page.goto(SIGN_URL);
await expect(page.getByText(/you have declined this signing request/i)).toBeVisible();
});
test('shows error state on 500 server error', async ({ page }) => {
await mockServerError(page);
await page.goto(SIGN_URL);
await expect(page.getByText(/something went wrong/i)).toBeVisible();
});
// ── Ready (signing form) ────────────────────────────────────────────────
test('renders signing form with document details', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await expect(page.getByText('Contract_2026.pdf')).toBeVisible();
await expect(page.getByText(/Requested by owner@company.com/i)).toBeVisible();
await expect(page.getByText('Please review and sign by end of week.')).toBeVisible();
});
test('shows document preview iframe', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.locator('iframe[title="Document to sign"]')).toBeVisible();
const iframeSrc = await page.locator('iframe[title="Document to sign"]').getAttribute('src');
expect(iframeSrc).toContain(TOKEN);
expect(iframeSrc).toContain('document');
});
test('auto-cert option is selected by default', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
// The auto-cert radio should be checked
const autoRadio = page.getByLabel(/use auto-generated certificate/i);
await expect(autoRadio).toBeChecked();
});
test('shows auto-cert info alert when auto cert is selected', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.getByText(/a certificate will be generated using your email address/i)).toBeVisible();
});
// ── Certificate chooser ─────────────────────────────────────────────────
test('switching to P12 shows file input and password field', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await page.getByLabel(/upload my own certificate/i).check();
await expect(page.getByLabel(/certificate file/i)).toBeVisible();
await expect(page.getByLabel(/certificate password/i)).toBeVisible();
// Auto-cert alert should be hidden
await expect(page.getByText(/a certificate will be generated using your email address/i)).not.toBeVisible();
});
test('switching back to auto-cert hides file inputs', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await page.getByLabel(/upload my own certificate/i).check();
await expect(page.getByLabel(/certificate file/i)).toBeVisible();
await page.getByLabel(/use auto-generated certificate/i).check();
await expect(page.getByLabel(/certificate file/i)).not.toBeVisible();
await expect(page.getByText(/a certificate will be generated using your email address/i)).toBeVisible();
});
// ── Submit signature ────────────────────────────────────────────────────
test('submits with GUEST_CERT and shows success state', async ({ page }) => {
let capturedFormData: Record<string, string> = {};
await page.route('**/workflow/participant/session**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_PENDING) })
);
await page.route('**/workflow/participant/document**', (route) =>
route.fulfill({ status: 200, contentType: 'application/pdf', body: Buffer.from('%PDF-1.4') })
);
await page.route('**/workflow/participant/submit-signature', async (route) => {
const request = route.request();
const postData = request.postData();
if (postData) capturedFormData.raw = postData;
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'SIGNED' }) });
});
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
// Submit with default auto-cert
await page.getByRole('button', { name: /submit signature/i }).click();
// Should transition to success state
await expect(page.getByText(/your signature has been submitted successfully/i)).toBeVisible();
// Verify certType was GUEST_CERT
expect(capturedFormData.raw).toContain('GUEST_CERT');
expect(capturedFormData.raw).toContain(TOKEN);
});
test('shows error message when submission fails', async ({ page }) => {
await page.route('**/workflow/participant/session**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_PENDING) })
);
await page.route('**/workflow/participant/document**', (route) =>
route.fulfill({ status: 200, contentType: 'application/pdf', body: Buffer.from('%PDF-1.4') })
);
await page.route('**/workflow/participant/submit-signature', (route) =>
route.fulfill({ status: 400, body: 'Session has expired' })
);
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await page.getByRole('button', { name: /submit signature/i }).click();
await expect(page.getByText(/something went wrong/i)).toBeVisible();
await expect(page.getByText('Session has expired')).toBeVisible();
});
test('Submit Signature button shows loading state while in flight', async ({ page }) => {
await page.route('**/workflow/participant/session**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(SESSION_PAYLOAD) })
);
await page.route('**/workflow/participant/details**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(PARTICIPANT_PENDING) })
);
await page.route('**/workflow/participant/document**', (route) =>
route.fulfill({ status: 200, contentType: 'application/pdf', body: Buffer.from('%PDF-1.4') })
);
await page.route('**/workflow/participant/submit-signature', async (route) => {
await new Promise(resolve => setTimeout(resolve, 600));
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ status: 'SIGNED' }) });
});
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await page.getByRole('button', { name: /submit signature/i }).click();
// Button should be in loading/disabled state
const submitBtn = page.getByRole('button', { name: /submit signature/i });
await expect(submitBtn).toBeDisabled();
// Eventually success
await expect(page.getByText(/your signature has been submitted successfully/i)).toBeVisible();
});
// ── Decline flow ────────────────────────────────────────────────────────
test('decline button opens confirmation modal', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await page.getByRole('button', { name: /decline/i }).first().click();
await expect(page.getByText('Decline signing?')).toBeVisible();
await expect(page.getByText(/are you sure you want to decline/i)).toBeVisible();
});
test('Cancel in decline modal closes modal without declining', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await page.getByRole('button', { name: /decline/i }).first().click();
await expect(page.getByText('Decline signing?')).toBeVisible();
await page.getByRole('button', { name: /cancel/i }).click();
await expect(page.getByText('Decline signing?')).not.toBeVisible();
// Signing form still present
await expect(page.getByRole('button', { name: /submit signature/i })).toBeVisible();
});
test('confirming decline transitions to declined state', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await page.getByRole('button', { name: /decline/i }).first().click();
await expect(page.getByText('Decline signing?')).toBeVisible();
// Click the confirm Decline button inside the modal
const modalDeclineBtn = page.getByRole('dialog').getByRole('button', { name: /decline/i });
await modalDeclineBtn.click();
await expect(page.getByText(/you have declined this signing request/i)).toBeVisible();
});
// ── Accessibility ───────────────────────────────────────────────────────
test('Submit Signature button is initially enabled', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await expect(page.getByRole('button', { name: /submit signature/i })).toBeEnabled();
});
test('Decline button is initially enabled', async ({ page }) => {
await mockHappyPath(page);
await page.goto(SIGN_URL);
await expect(page.getByText('Sign Document')).toBeVisible();
await expect(page.getByRole('button', { name: /decline/i }).first()).toBeEnabled();
});
});
@@ -0,0 +1,325 @@
/**
* Conversion Endpoint Discovery for E2E Testing
*
* Uses the backend's endpoint configuration API to discover available conversions
*/
import { useMultipleEndpointsEnabled } from '@app/hooks/useEndpointConfig';
export interface ConversionEndpoint {
endpoint: string;
fromFormat: string;
toFormat: string;
description: string;
apiPath: string;
}
// Complete list of conversion endpoints based on EndpointConfiguration.java
const ALL_CONVERSION_ENDPOINTS: ConversionEndpoint[] = [
{
endpoint: 'pdf-to-img',
fromFormat: 'pdf',
toFormat: 'image',
description: 'Convert PDF to images (PNG, JPG, GIF, etc.)',
apiPath: '/api/v1/convert/pdf/img'
},
{
endpoint: 'img-to-pdf',
fromFormat: 'image',
toFormat: 'pdf',
description: 'Convert images to PDF',
apiPath: '/api/v1/convert/img/pdf'
},
{
endpoint: 'pdf-to-pdfa',
fromFormat: 'pdf',
toFormat: 'pdfa',
description: 'Convert PDF to PDF/A',
apiPath: '/api/v1/convert/pdf/pdfa'
},
{
endpoint: 'file-to-pdf',
fromFormat: 'office',
toFormat: 'pdf',
description: 'Convert office files to PDF',
apiPath: '/api/v1/convert/file/pdf'
},
{
endpoint: 'pdf-to-word',
fromFormat: 'pdf',
toFormat: 'docx',
description: 'Convert PDF to Word document',
apiPath: '/api/v1/convert/pdf/word'
},
{
endpoint: 'pdf-to-presentation',
fromFormat: 'pdf',
toFormat: 'pptx',
description: 'Convert PDF to PowerPoint presentation',
apiPath: '/api/v1/convert/pdf/presentation'
},
{
endpoint: 'pdf-to-text',
fromFormat: 'pdf',
toFormat: 'txt',
description: 'Convert PDF to plain text',
apiPath: '/api/v1/convert/pdf/text'
},
{
endpoint: 'pdf-to-html',
fromFormat: 'pdf',
toFormat: 'html',
description: 'Convert PDF to HTML',
apiPath: '/api/v1/convert/pdf/html'
},
{
endpoint: 'pdf-to-xml',
fromFormat: 'pdf',
toFormat: 'xml',
description: 'Convert PDF to XML',
apiPath: '/api/v1/convert/pdf/xml'
},
{
endpoint: 'html-to-pdf',
fromFormat: 'html',
toFormat: 'pdf',
description: 'Convert HTML to PDF',
apiPath: '/api/v1/convert/html/pdf'
},
{
endpoint: 'url-to-pdf',
fromFormat: 'url',
toFormat: 'pdf',
description: 'Convert web page to PDF',
apiPath: '/api/v1/convert/url/pdf'
},
{
endpoint: 'markdown-to-pdf',
fromFormat: 'md',
toFormat: 'pdf',
description: 'Convert Markdown to PDF',
apiPath: '/api/v1/convert/markdown/pdf'
},
{
endpoint: 'pdf-to-csv',
fromFormat: 'pdf',
toFormat: 'csv',
description: 'Extract CSV data from PDF',
apiPath: '/api/v1/convert/pdf/csv'
},
{
endpoint: 'pdf-to-xlsx',
fromFormat: 'pdf',
toFormat: 'xlsx',
description: 'Extract Excel spreadsheet from PDF',
apiPath: '/api/v1/convert/pdf/xlsx'
},
{
endpoint: 'pdf-to-markdown',
fromFormat: 'pdf',
toFormat: 'md',
description: 'Convert PDF to Markdown',
apiPath: '/api/v1/convert/pdf/markdown'
},
{
endpoint: 'eml-to-pdf',
fromFormat: 'eml',
toFormat: 'pdf',
description: 'Convert email (EML) to PDF',
apiPath: '/api/v1/convert/eml/pdf'
},
{
endpoint: 'pdf-to-epub',
fromFormat: 'pdf',
toFormat: 'epub',
description: 'Convert PDF to EPUB/AZW3',
apiPath: '/api/v1/convert/pdf/epub'
},
{
endpoint: 'eml-to-pdf', // MSG uses same endpoint as EML
fromFormat: 'msg',
toFormat: 'pdf',
description: 'Convert Outlook email (MSG) to PDF',
apiPath: '/api/v1/convert/eml/pdf'
}
];
export class ConversionEndpointDiscovery {
private baseUrl: string;
private cache: Map<string, boolean> | null = null;
private cacheExpiry: number = 0;
private readonly CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
constructor(baseUrl: string = process.env.BACKEND_URL || 'http://localhost:8080') {
this.baseUrl = baseUrl;
}
/**
* Get all available conversion endpoints by checking with backend
*/
async getAvailableConversions(): Promise<ConversionEndpoint[]> {
const endpointStatuses = await this.getEndpointStatuses();
return ALL_CONVERSION_ENDPOINTS.filter(conversion =>
endpointStatuses.get(conversion.endpoint) === true
);
}
/**
* Get all unavailable conversion endpoints
*/
async getUnavailableConversions(): Promise<ConversionEndpoint[]> {
const endpointStatuses = await this.getEndpointStatuses();
return ALL_CONVERSION_ENDPOINTS.filter(conversion =>
endpointStatuses.get(conversion.endpoint) === false
);
}
/**
* Check if a specific conversion is available
*/
async isConversionAvailable(endpoint: string): Promise<boolean> {
const endpointStatuses = await this.getEndpointStatuses();
return endpointStatuses.get(endpoint) === true;
}
/**
* Get available conversions grouped by source format
*/
async getConversionsByFormat(): Promise<Record<string, ConversionEndpoint[]>> {
const availableConversions = await this.getAvailableConversions();
const grouped: Record<string, ConversionEndpoint[]> = {};
availableConversions.forEach(conversion => {
if (!grouped[conversion.fromFormat]) {
grouped[conversion.fromFormat] = [];
}
grouped[conversion.fromFormat].push(conversion);
});
return grouped;
}
/**
* Get supported target formats for a given source format
*/
async getSupportedTargetFormats(fromFormat: string): Promise<string[]> {
const availableConversions = await this.getAvailableConversions();
return availableConversions
.filter(conversion => conversion.fromFormat === fromFormat)
.map(conversion => conversion.toFormat);
}
/**
* Get all supported source formats
*/
async getSupportedSourceFormats(): Promise<string[]> {
const availableConversions = await this.getAvailableConversions();
const sourceFormats = new Set(
availableConversions.map(conversion => conversion.fromFormat)
);
return Array.from(sourceFormats);
}
/**
* Get endpoint statuses from backend using batch API
*/
private async getEndpointStatuses(): Promise<Map<string, boolean>> {
// Return cached result if still valid
if (this.cache && Date.now() < this.cacheExpiry) {
return this.cache;
}
try {
const endpointNames = ALL_CONVERSION_ENDPOINTS.map(conv => conv.endpoint);
const endpointsParam = endpointNames.join(',');
const response = await fetch(
`${this.baseUrl}/api/v1/config/endpoints-enabled?endpoints=${encodeURIComponent(endpointsParam)}`
);
if (!response.ok) {
throw new Error(`Failed to fetch endpoint statuses: ${response.status} ${response.statusText}`);
}
const statusMap: Record<string, boolean> = await response.json();
// Convert to Map and cache
this.cache = new Map(Object.entries(statusMap));
this.cacheExpiry = Date.now() + this.CACHE_DURATION;
console.log(`Retrieved status for ${Object.keys(statusMap).length} conversion endpoints`);
return this.cache;
} catch (error) {
console.error('Failed to get endpoint statuses:', error);
// Fallback: assume all endpoints are disabled
const fallbackMap = new Map<string, boolean>();
ALL_CONVERSION_ENDPOINTS.forEach(conv => {
fallbackMap.set(conv.endpoint, false);
});
return fallbackMap;
}
}
/**
* Utility to create a skipping condition for tests
*/
static createSkipCondition(endpoint: string, discovery: ConversionEndpointDiscovery) {
return async () => {
const available = await discovery.isConversionAvailable(endpoint);
return !available;
};
}
/**
* Get detailed conversion info by endpoint name
*/
getConversionInfo(endpoint: string): ConversionEndpoint | undefined {
return ALL_CONVERSION_ENDPOINTS.find(conv => conv.endpoint === endpoint);
}
/**
* Get all conversion endpoints (regardless of availability)
*/
getAllConversions(): ConversionEndpoint[] {
return [...ALL_CONVERSION_ENDPOINTS];
}
}
// Export singleton instance for reuse across tests
export const conversionDiscovery = new ConversionEndpointDiscovery();
/**
* React hook version for use in components (wraps the class)
*/
export function useConversionEndpoints() {
const endpointNames = ALL_CONVERSION_ENDPOINTS.map(conv => conv.endpoint);
const { endpointStatus, loading, error, refetch } = useMultipleEndpointsEnabled(endpointNames);
const availableConversions = ALL_CONVERSION_ENDPOINTS.filter(
conv => endpointStatus[conv.endpoint] === true
);
const unavailableConversions = ALL_CONVERSION_ENDPOINTS.filter(
conv => endpointStatus[conv.endpoint] === false
);
return {
availableConversions,
unavailableConversions,
allConversions: ALL_CONVERSION_ENDPOINTS,
endpointStatus,
loading,
error,
refetch,
isConversionAvailable: (endpoint: string) => endpointStatus[endpoint] === true
};
}
+1 -1
View File
@@ -37,7 +37,7 @@ const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
};
const hasFiles = selectedFiles.length > 0;
const hasResults = convertOperation.files.length > 0 || convertOperation.downloadUrl !== null || !!convertOperation.errorMessage;
const hasResults = convertOperation.files.length > 0 || convertOperation.downloadUrl !== null;
const settingsCollapsed = hasResults;
// When operation completes, flag the next selection change to skip reset
-42
View File
@@ -97,45 +97,3 @@ export function isPdfFile(file: { name?: string; type?: string } | File | Blob |
return false;
}
export type NonPdfFileType = 'image' | 'csv' | 'json' | 'text' | 'markdown' | 'html' | 'unknown';
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff', 'tif', 'webp']);
const CSV_EXTENSIONS = new Set(['csv', 'tsv']);
const JSON_EXTENSIONS = new Set(['json']);
const TEXT_EXTENSIONS = new Set(['txt']);
const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']);
const HTML_EXTENSIONS = new Set(['html', 'htm']);
/**
* Detects the non-PDF file type category for viewer routing.
* Returns 'unknown' for PDFs or unrecognized formats.
*/
export function detectNonPdfFileType(file: { name?: string; type?: string } | File | null | undefined): NonPdfFileType {
if (!file) return 'unknown';
const name = 'name' in file ? file.name : undefined;
const mimeType = file.type ?? '';
// Check MIME type first
if (mimeType.startsWith('image/')) return 'image';
if (mimeType === 'text/csv') return 'csv';
if (mimeType === 'text/tab-separated-values') return 'csv';
if (mimeType === 'application/json') return 'json';
if (mimeType === 'text/html') return 'html';
if (mimeType === 'text/markdown') return 'markdown';
// Fall back to extension
if (name) {
const ext = detectFileExtension(name);
if (IMAGE_EXTENSIONS.has(ext)) return 'image';
if (CSV_EXTENSIONS.has(ext)) return 'csv';
if (JSON_EXTENSIONS.has(ext)) return 'json';
if (MARKDOWN_EXTENSIONS.has(ext)) return 'markdown';
if (TEXT_EXTENSIONS.has(ext)) return 'text';
if (HTML_EXTENSIONS.has(ext)) return 'html';
}
return 'unknown';
}
@@ -1,44 +0,0 @@
import { useState, useEffect } from "react";
import { getVersion } from "@tauri-apps/api/app";
import type { FrontendVersionInfo } from "@core/hooks/useFrontendVersionInfo";
export function useFrontendVersionInfo(backendVersion: string | undefined): FrontendVersionInfo {
const [appVersion, setAppVersion] = useState<string | null>(null);
const [mismatchVersion, setMismatchVersion] = useState(false);
useEffect(() => {
let cancelled = false;
const fetchVersion = async () => {
try {
const version = await getVersion();
if (!cancelled) {
setAppVersion(version);
}
} catch (error) {
console.error("[useFrontendVersionInfo] Failed to fetch frontend version:", error);
}
};
fetchVersion();
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (!appVersion || !backendVersion) {
setMismatchVersion(false);
return;
}
if (appVersion !== backendVersion) {
console.warn("[useFrontendVersionInfo] Mismatch between frontend version and AppConfig version:", {
backendVersion,
frontendVersion: appVersion,
});
setMismatchVersion(true);
} else {
setMismatchVersion(false);
}
}, [appVersion, backendVersion]);
return { appVersion, mismatchVersion };
}
@@ -1,12 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useSelfHostedAuth } from '@app/hooks/useSelfHostedAuth';
/**
* Desktop override: shared (group) signing requires self-hosted mode AND
* an authenticated session. Returns false in SaaS/local mode or when logged out.
*/
export function useGroupSigningEnabled(): boolean {
const { config } = useAppConfig();
const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
return isSelfHosted && isAuthenticated && config?.storageGroupSigningEnabled === true;
}
@@ -1,41 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { authService } from '@app/services/authService';
import { connectionModeService } from '@app/services/connectionModeService';
export interface SelfHostedAuthState {
isSelfHosted: boolean;
isAuthenticated: boolean;
}
/**
* Tracks whether the desktop app is in self-hosted mode with an active
* authenticated session. Refetches app config when the mode first transitions
* to selfhosted, since the jwt-available config fetch fires against the local
* bundled backend before the SetupWizard has switched the mode.
*/
export function useSelfHostedAuth(): SelfHostedAuthState {
const { refetch } = useAppConfig();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isSelfHosted, setIsSelfHosted] = useState(false);
const wasSelfHosted = useRef(false);
useEffect(() => {
void connectionModeService.getCurrentMode().then(mode => setIsSelfHosted(mode === 'selfhosted'));
return connectionModeService.subscribeToModeChanges(cfg => setIsSelfHosted(cfg.mode === 'selfhosted'));
}, []);
useEffect(() => {
void authService.isAuthenticated().then(setIsAuthenticated);
return authService.subscribeToAuth(status => setIsAuthenticated(status === 'authenticated'));
}, []);
useEffect(() => {
if (isSelfHosted && !wasSelfHosted.current) {
void refetch();
}
wasSelfHosted.current = isSelfHosted;
}, [isSelfHosted, refetch]);
return { isSelfHosted, isAuthenticated };
}
@@ -1,18 +0,0 @@
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useSelfHostedAuth } from '@app/hooks/useSelfHostedAuth';
import type { SharingEnabledResult } from '@core/hooks/useSharingEnabled';
/**
* Desktop override: file-sharing features require self-hosted mode AND an
* authenticated session. Returns false for both in SaaS/local mode or when
* logged out.
*/
export function useSharingEnabled(): SharingEnabledResult {
const { config } = useAppConfig();
const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
const allowed = isSelfHosted && isAuthenticated;
return {
sharingEnabled: allowed && config?.storageSharingEnabled === true,
shareLinksEnabled: allowed && config?.storageShareLinksEnabled === true,
};
}
@@ -1,20 +0,0 @@
import { useViewer } from "@app/contexts/ViewerContext"
import { useCallback } from "react";
export function useViewerKeyCommand(): (event: KeyboardEvent) => boolean {
const { rotationActions } = useViewer();
return useCallback((event:KeyboardEvent): boolean => {
switch (event.key) {
case 'r':
case 'R':
event.preventDefault();
if (event.shiftKey) {
rotationActions.rotateBackward();
} else {
rotationActions.rotateForward();
}
return true;
}
return false;
}, [rotationActions]);
}
@@ -218,26 +218,48 @@ class TauriHttpClient {
const response = await fetch(url, fetchOptions);
// Parse response based on responseType
let data: T;
const responseType = finalConfig.responseType || 'json';
if (responseType === 'json') {
data = await response.json() as T;
} else if (responseType === 'text') {
data = (await response.text()) as T;
} else if (responseType === 'blob') {
// Standard fetch doesn't set blob.type from Content-Type header (unlike axios)
// Set it manually to match axios behavior
const blob = await response.blob();
if (!blob.type) {
const contentType = response.headers.get('content-type') || 'application/octet-stream';
data = new Blob([blob], { type: contentType }) as T;
} else {
data = blob as T;
}
} else if (responseType === 'arraybuffer') {
data = (await response.arrayBuffer()) as T;
} else {
data = await response.json() as T;
}
// Convert Headers to plain object
const responseHeaders: Record<string, string> = {};
response.headers.forEach((value, key) => {
responseHeaders[key] = value;
});
// Check for HTTP errors BEFORE reading the body so that a plain-text error
// response from the server doesn't cause a JSON parse failure that gets
// misreported as ERR_NETWORK.
if (!response.ok) {
// Read the body as text to surface the real server error message
let errorBody: string;
try {
errorBody = await response.text();
} catch {
errorBody = '';
}
const httpResponse: TauriHttpResponse<T> = {
data,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
// Check for HTTP errors
if (!response.ok) {
// Create more descriptive error messages based on status code
let errorMessage = errorBody || `Request failed with status code ${response.status}`;
let errorMessage = `Request failed with status code ${response.status}`;
let errorCode = 'ERR_BAD_REQUEST';
if (response.status === 401) {
@@ -262,22 +284,13 @@ class TauriHttpClient {
method,
status: response.status,
statusText: response.statusText,
body: errorBody,
});
const errorResponse: TauriHttpResponse<T> = {
data: errorBody as T,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
const error = this.createError(
errorMessage,
finalConfig,
errorCode,
errorResponse
httpResponse
);
// Run error interceptors
@@ -294,39 +307,6 @@ class TauriHttpClient {
throw finalError;
}
// Parse response body for successful responses
let data: T;
const responseType = finalConfig.responseType || 'json';
if (responseType === 'json') {
const text = await response.text();
data = (text ? JSON.parse(text) : null) as T;
} else if (responseType === 'text') {
data = (await response.text()) as T;
} else if (responseType === 'blob') {
// Standard fetch doesn't set blob.type from Content-Type header (unlike axios)
// Set it manually to match axios behavior
const blob = await response.blob();
if (!blob.type) {
const contentType = response.headers.get('content-type') || 'application/octet-stream';
data = new Blob([blob], { type: contentType }) as T;
} else {
data = blob as T;
}
} else if (responseType === 'arraybuffer') {
data = (await response.arrayBuffer()) as T;
} else {
data = await response.json() as T;
}
const httpResponse: TauriHttpResponse<T> = {
data,
status: response.status,
statusText: response.statusText || '',
headers: responseHeaders,
config: finalConfig,
};
// Run response interceptors
let finalResponse = httpResponse;
for (const handler of this.interceptors.response.handlers) {
+22
View File
@@ -13,6 +13,7 @@ import InviteAccept from "@app/routes/InviteAccept";
import ShareLinkPage from "@app/routes/ShareLinkPage";
import ParticipantView from "@app/components/workflow/ParticipantView";
import MobileScannerPage from "@app/pages/MobileScannerPage";
import GuestSignPage from "@app/routes/GuestSignPage";
import Onboarding from "@app/components/onboarding/Onboarding";
// Import global styles
@@ -42,6 +43,17 @@ function ParticipantViewPage() {
return <ParticipantView token={token} />;
}
// Minimal providers for guest signing - token-based, no authentication required
function GuestSigningProviders({ children }: { children: React.ReactNode }) {
return (
<PreferencesProvider>
<RainbowThemeProvider>
{children}
</RainbowThemeProvider>
</PreferencesProvider>
);
}
export default function App() {
return (
<Suspense fallback={<LoadingFallback />}>
@@ -66,6 +78,16 @@ export default function App() {
}
/>
{/* Guest signing route - token-based, no authentication required */}
<Route
path="/sign/:token"
element={
<GuestSigningProviders>
<GuestSignPage />
</GuestSigningProviders>
}
/>
{/* All other routes need AppProviders for backend integration */}
<Route
path="*"
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { springAuth } from '@app/auth/springAuthClient';
import { startOAuthNavigation } from '@app/extensions/oauthNavigation';
import apiClient from '@app/services/apiClient';
import { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
import { AxiosError } from 'axios';
// Mock apiClient
vi.mock('@app/services/apiClient');
@@ -45,7 +45,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
status: 200,
data: { user: mockUser },
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.getSession();
@@ -74,7 +74,7 @@ describe('SpringAuthClient', () => {
statusText: 'Unauthorized',
data: {},
headers: {},
config: {} as InternalAxiosRequestConfig,
config: {} as any,
}
);
@@ -102,7 +102,7 @@ describe('SpringAuthClient', () => {
statusText: 'Forbidden',
data: {},
headers: {},
config: {} as InternalAxiosRequestConfig,
config: {} as any,
}
);
@@ -141,7 +141,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as unknown as AxiosResponse);
} as any);
// Spy on window.dispatchEvent
const dispatchEventSpy = vi.spyOn(window, 'dispatchEvent');
@@ -208,7 +208,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: { user: mockUser },
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.signUp(credentials);
@@ -259,7 +259,7 @@ describe('SpringAuthClient', () => {
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: {},
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.signOut();
@@ -308,7 +308,7 @@ describe('SpringAuthClient', () => {
expires_in: 3600,
},
},
} as unknown as AxiosResponse);
} as any);
const result = await springAuth.refreshSession();
@@ -85,7 +85,7 @@ export interface User {
is_anonymous?: boolean;
isFirstLogin?: boolean;
authenticationType?: string;
app_metadata?: Record<string, unknown>;
app_metadata?: Record<string, any>;
}
export interface Session {
@@ -447,7 +447,7 @@ class SpringAuthClient {
*/
async signInWithOAuth(params: {
provider: OAuthProvider;
options?: { redirectTo?: string; queryParams?: Record<string, string> };
options?: { redirectTo?: string; queryParams?: Record<string, any> };
}): Promise<{ error: AuthError | null }> {
try {
const redirectPath = normalizeRedirectPath(params.options?.redirectTo);
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
ActionIcon,
@@ -126,10 +125,8 @@ export default function ChangeUserPasswordModal({ opened, onClose, user, onSucce
alert({ alertType: 'success', title: t('workspace.people.changePassword.success', 'Password updated successfully') });
onSuccess();
handleClose();
} catch (error: unknown) {
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.changePassword.error', 'Failed to update password');
} catch (error: any) {
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.changePassword.error', 'Failed to update password');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -12,7 +12,7 @@ interface TextDividerProps {
export default function DividerWithText({ text, className = '', style, variant = 'default', respondsToDarkMode = true, opacity }: TextDividerProps) {
const variantClass = variant === 'subcategory' ? 'subcategory' : '';
const themeClass = respondsToDarkMode ? '' : 'force-light';
const styleWithOpacity = opacity !== undefined ? { ...(style || {}), ['--text-divider-opacity' as string]: opacity } : style;
const styleWithOpacity = opacity !== undefined ? { ...(style || {}), ['--text-divider-opacity' as any]: opacity } : style;
if (text) {
return (
@@ -1,5 +1,4 @@
import { useState, useEffect, useRef } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Modal,
@@ -159,11 +158,9 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
forceChange: false,
forceMFA: false,
});
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to invite user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.addMember.error');
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.addMember.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -214,11 +211,12 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
body: response.errors || response.error
});
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to invite users:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.emailInvite.error', 'Failed to send invites');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.emailInvite.error', 'Failed to send invites');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -241,11 +239,9 @@ export default function InviteMembersModal({ opened, onClose, onSuccess }: Invit
if (inviteLinkForm.sendEmail && inviteLinkForm.email) {
alert({ alertType: 'success', title: t('workspace.people.inviteLink.emailSent', 'Invite link generated and sent via email') });
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to generate invite link:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.inviteLink.error', 'Failed to generate invite link');
const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('workspace.people.inviteLink.error', 'Failed to generate invite link');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -34,12 +34,12 @@ export const ManageBillingButton: React.FC<ManageBillingButtonProps> = ({
// Open billing portal in new tab
window.open(response.url, '_blank');
setLoading(false);
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: (error instanceof Error ? error.message : undefined) || 'Please try again or contact support.',
body: error.message || 'Please try again or contact support.',
});
setLoading(false);
}
@@ -86,7 +86,7 @@ const UpgradeBanner: React.FC = () => {
const scenarioProvidesInfo =
scenarioKey && scenarioKey !== 'unknown' && scenarioKey !== 'licensed';
const derivedIsAdmin = scenarioProvidesInfo
? scenarioKey.includes('admin')
? scenarioKey!.includes('admin')
: isAdmin;
const derivedHasPaidLicense =
scenarioKey === 'licensed'
@@ -95,10 +95,10 @@ const UpgradeBanner: React.FC = () => {
? hasPaidLicense
: false;
const derivedIsUnderLimit = scenarioProvidesInfo
? scenarioKey.includes('under-limit')
? scenarioKey!.includes('under-limit')
: isUnderLimit === true;
const derivedIsOverLimit = scenarioProvidesInfo
? scenarioKey.includes('over-limit')
? scenarioKey!.includes('over-limit')
: isOverLimit === true;
const effectiveIsAdmin = scenario
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import { NumberInput, Switch, Button, Stack, Paper, Text, Loader, Group, Accordion, TextInput, MultiSelect } from '@mantine/core';
import { alert } from '@app/components/toast';
@@ -73,7 +72,7 @@ export default function AdminAdvancedSection() {
isFieldPending,
} = useAdminSettings<AdvancedSettingsData>({
sectionName: 'advanced',
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<AdvancedSettingsData & { _pending?: Record<string, any> }> => {
const [systemResponse, processExecutorResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/system'),
apiClient.get('/api/v1/admin/settings/section/processExecutor')
@@ -82,7 +81,7 @@ export default function AdminAdvancedSection() {
const systemData = systemResponse.data || {};
const processExecutorData = processExecutorResponse.data || {};
const result: AdvancedSettingsData & { _pending?: Record<string, unknown> } = {
const result: AdvancedSettingsData & { _pending?: Record<string, any> } = {
enableAlphaFunctionality: systemData.enableAlphaFunctionality || false,
maxDPI: systemData.maxDPI || 0,
enableUrlToPDF: systemData.enableUrlToPDF || false,
@@ -102,7 +101,7 @@ export default function AdminAdvancedSection() {
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (systemData._pending?.enableAlphaFunctionality !== undefined) {
pendingBlock.enableAlphaFunctionality = systemData._pending.enableAlphaFunctionality;
}
@@ -132,7 +131,7 @@ export default function AdminAdvancedSection() {
return result;
},
saveTransformer: (settings) => {
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
'system.enableAlphaFunctionality': settings.enableAlphaFunctionality,
'system.maxDPI': settings.maxDPI,
'system.enableUrlToPDF': settings.enableUrlToPDF,
@@ -282,8 +281,9 @@ export default function AdminAdvancedSection() {
setManualDownloadLinks([]);
} catch (error) {
console.error('[AdminAdvancedSection] Download tessdata languages failed', error);
const status = isAxiosError(error) ? error.response?.status : undefined;
const serverMessage = isAxiosError(error) ? error.response?.data?.message : undefined;
const response = (error as any)?.response;
const status = response?.status;
const serverMessage = response?.data?.message;
if (status === 403) {
console.warn('[AdminAdvancedSection] Tessdata directory not writable, falling back to manual download:', serverMessage);
@@ -309,12 +309,12 @@ export default function AdminAdvancedSection() {
}
let message: string;
if (!isAxiosError(error) || !error.response) {
if (!response) {
message = t(
'admin.settings.advanced.tessdataDir.downloadErrorNetwork',
'Download failed due to a network error. Please check your connection and try again.'
);
} else if (status !== undefined && status >= 500) {
} else if (status >= 500) {
message = t(
'admin.settings.advanced.tessdataDir.downloadErrorServer',
'The server encountered an error while downloading tessdata languages. Please try again later.'
@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { Tabs, Loader, Alert, Stack, Text, Button, Accordion } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -36,9 +35,9 @@ const AdminAuditSection: React.FC = () => {
setError(null);
const status = await auditService.getSystemStatus();
setSystemStatus(status);
} catch (err: unknown) {
} catch (err: any) {
// Check if this is a permission/license error (403/404)
const status = isAxiosError(err) ? err.response?.status : undefined;
const status = err?.response?.status;
if (status === 403 || status === 404) {
setError('enterprise-license-required');
} else {
@@ -44,66 +44,6 @@ interface TelegramSettingsData {
feedback?: FeedbackSettings;
}
interface MailSettings {
enabled?: boolean;
enableInvites?: boolean;
host?: string;
port?: number;
username?: string;
password?: string;
from?: string;
}
interface GoogleDriveSettings {
enabled?: boolean;
clientId?: string;
apiKey?: string;
appId?: string;
}
interface OAuth2GenericSettings {
enabled?: boolean;
provider?: string;
issuer?: string;
clientId?: string;
clientSecret?: string;
scopes?: string;
useAsUsername?: string;
autoCreateUser?: boolean;
blockRegistration?: boolean;
}
interface Saml2Settings {
enabled?: boolean;
provider?: string;
registrationId?: string;
idpMetadataUri?: string;
idpSingleLoginUrl?: string;
idpSingleLogoutUrl?: string;
idpIssuer?: string;
idpCert?: string;
privateKey?: string;
spCert?: string;
autoCreateUser?: boolean;
blockRegistration?: boolean;
}
interface OAuth2ClientSettings {
clientId?: string;
clientSecret?: string;
scopes?: string;
useAsUsername?: string;
issuer?: string;
}
type ProviderSettings =
| MailSettings
| TelegramSettingsData
| GoogleDriveSettings
| OAuth2GenericSettings
| Saml2Settings
| OAuth2ClientSettings;
interface ConnectionsSettingsData {
oauth2?: {
enabled?: boolean;
@@ -115,10 +55,22 @@ interface ConnectionsSettingsData {
blockRegistration?: boolean;
useAsUsername?: string;
scopes?: string;
client?: Record<string, OAuth2ClientSettings>;
client?: {
[key: string]: any;
};
};
saml2?: {
[key: string]: any;
};
mail?: {
enabled?: boolean;
enableInvites?: boolean;
host?: string;
port?: number;
username?: string;
password?: string;
from?: string;
};
saml2?: Saml2Settings;
mail?: MailSettings;
telegram?: TelegramSettingsData;
ssoAutoLogin?: boolean;
enableMobileScanner?: boolean;
@@ -141,7 +93,7 @@ export default function AdminConnectionsSection() {
const adminSettings = useAdminSettings<ConnectionsSettingsData>({
sectionName: 'connections',
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<ConnectionsSettingsData & { _pending?: Record<string, any> }> => {
// Fetch security settings (oauth2, saml2)
const securityResponse = await apiClient.get('/api/v1/admin/settings/section/security');
const securityData = securityResponse.data || {};
@@ -162,7 +114,7 @@ export default function AdminConnectionsSection() {
const systemResponse = await apiClient.get('/api/v1/admin/settings/section/system');
const systemData = systemResponse.data || {};
const result: ConnectionsSettingsData & { _pending?: Record<string, unknown> } = {
const result: ConnectionsSettingsData & { _pending?: Record<string, any> } = {
oauth2: securityData.oauth2 || {},
saml2: securityData.saml2 || {},
mail: mailData || {},
@@ -180,7 +132,7 @@ export default function AdminConnectionsSection() {
};
// Merge pending blocks from all endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (securityData._pending?.oauth2) {
pendingBlock.oauth2 = securityData._pending.oauth2;
}
@@ -231,13 +183,13 @@ export default function AdminConnectionsSection() {
return result;
},
saveTransformer: (currentSettings: ConnectionsSettingsData) => {
const deltaSettings: Record<string, unknown> = {};
const deltaSettings: Record<string, any> = {};
// Build delta for oauth2 settings
if (currentSettings.oauth2) {
Object.keys(currentSettings.oauth2).forEach((key) => {
if (key !== 'client') {
deltaSettings[`security.oauth2.${key}`] = (currentSettings.oauth2 as Record<string, unknown>)[key];
deltaSettings[`security.oauth2.${key}`] = (currentSettings.oauth2 as Record<string, any>)[key];
}
});
@@ -245,7 +197,7 @@ export default function AdminConnectionsSection() {
const oauth2Client = currentSettings.oauth2.client;
if (oauth2Client) {
Object.keys(oauth2Client).forEach((providerId) => {
const providerSettings = oauth2Client[providerId] as Record<string, unknown>;
const providerSettings = oauth2Client[providerId];
Object.keys(providerSettings).forEach((key) => {
deltaSettings[`security.oauth2.client.${providerId}.${key}`] = providerSettings[key];
});
@@ -255,25 +207,22 @@ export default function AdminConnectionsSection() {
// Build delta for saml2 settings
if (currentSettings.saml2) {
const saml2 = currentSettings.saml2 as Record<string, unknown>;
Object.keys(saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = saml2[key];
Object.keys(currentSettings.saml2).forEach((key) => {
deltaSettings[`security.saml2.${key}`] = (currentSettings.saml2 as Record<string, any>)[key];
});
}
// Mail settings
if (currentSettings.mail) {
const mail = currentSettings.mail as Record<string, unknown>;
Object.keys(mail).forEach((key) => {
deltaSettings[`mail.${key}`] = mail[key];
Object.keys(currentSettings.mail).forEach((key) => {
deltaSettings[`mail.${key}`] = (currentSettings.mail as Record<string, any>)[key];
});
}
// Telegram settings
if (currentSettings.telegram) {
const telegram = currentSettings.telegram as Record<string, unknown>;
Object.keys(telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = telegram[key];
Object.keys(currentSettings.telegram).forEach((key) => {
deltaSettings[`telegram.${key}`] = (currentSettings.telegram as Record<string, any>)[key];
});
}
@@ -383,7 +332,7 @@ export default function AdminConnectionsSection() {
return !!(providerSettings?.clientId);
};
const getProviderSettings = (provider: Provider): ProviderSettings => {
const getProviderSettings = (provider: Provider): Record<string, any> => {
if (provider.id === 'saml2') {
return settings?.saml2 || {};
}
@@ -397,17 +346,17 @@ export default function AdminConnectionsSection() {
}
if (provider.id === 'googledrive') {
const gd: GoogleDriveSettings = {
return {
enabled: settings?.googleDriveEnabled,
clientId: settings?.googleDriveClientId,
apiKey: settings?.googleDriveApiKey,
appId: settings?.googleDriveAppId,
};
return gd;
}
if (provider.id === 'oauth2-generic') {
const generic: OAuth2GenericSettings = {
// Generic OAuth2 settings are at the root oauth2 level
return {
enabled: settings?.oauth2?.enabled,
provider: settings?.oauth2?.provider,
issuer: settings?.oauth2?.issuer,
@@ -418,7 +367,6 @@ export default function AdminConnectionsSection() {
autoCreateUser: settings?.oauth2?.autoCreateUser,
blockRegistration: settings?.oauth2?.blockRegistration,
};
return generic;
}
// Specific OAuth2 provider settings
@@ -438,35 +386,32 @@ export default function AdminConnectionsSection() {
const linkedProviders = allProviders.filter((p) => isProviderConfigured(p));
const availableProviders = allProviders.filter((p) => !isProviderConfigured(p));
const updateProviderSettings = (provider: Provider, updatedSettings: Record<string, unknown>) => {
const updateProviderSettings = (provider: Provider, updatedSettings: Record<string, any>) => {
if (provider.id === 'smtp') {
setSettings({ ...settings, mail: updatedSettings as MailSettings });
setSettings({ ...settings, mail: updatedSettings });
} else if (provider.id === 'telegram') {
setSettings({ ...settings, telegram: updatedSettings as TelegramSettingsData });
setSettings({ ...settings, telegram: updatedSettings });
} else if (provider.id === 'googledrive') {
const gd = updatedSettings as GoogleDriveSettings;
setSettings({
...settings,
googleDriveEnabled: gd.enabled,
googleDriveClientId: gd.clientId,
googleDriveApiKey: gd.apiKey,
googleDriveAppId: gd.appId,
googleDriveEnabled: updatedSettings.enabled,
googleDriveClientId: updatedSettings.clientId,
googleDriveApiKey: updatedSettings.apiKey,
googleDriveAppId: updatedSettings.appId,
});
} else if (provider.id === 'saml2') {
setSettings({ ...settings, saml2: updatedSettings as Saml2Settings });
setSettings({ ...settings, saml2: updatedSettings });
} else if (provider.id === 'oauth2-generic') {
const generic = updatedSettings as OAuth2GenericSettings;
setSettings({ ...settings, oauth2: { ...settings.oauth2, ...generic } });
setSettings({ ...settings, oauth2: updatedSettings });
} else {
// Specific OAuth2 provider
const clientSettings = updatedSettings as OAuth2ClientSettings;
setSettings({
...settings,
oauth2: {
...settings.oauth2,
client: {
...settings.oauth2?.client,
[provider.id]: clientSettings,
[provider.id]: updatedSettings
}
}
});
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { isAxiosError } from "axios";
import { useTranslation } from "react-i18next";
import {
NumberInput,
@@ -69,7 +68,7 @@ export default function AdminDatabaseSection() {
const { settings, setSettings, loading, saving, fetchSettings, saveSettings, isFieldPending } =
useAdminSettings<DatabaseSettingsData>({
sectionName: "database",
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<DatabaseSettingsData & { _pending?: Record<string, any> }> => {
const response = await apiClient.get("/api/v1/admin/settings/section/system");
const systemData = response.data || {};
@@ -86,7 +85,7 @@ export default function AdminDatabaseSection() {
};
// Map pending changes from system._pending.datasource to root level
const result: DatabaseSettingsData & { _pending?: Record<string, unknown> } = { ...datasource };
const result: DatabaseSettingsData & { _pending?: Record<string, any> } = { ...datasource };
if (systemData._pending?.datasource) {
result._pending = systemData._pending.datasource;
}
@@ -95,7 +94,7 @@ export default function AdminDatabaseSection() {
},
saveTransformer: (settings: DatabaseSettingsData) => {
// Convert flat settings to dot-notation for delta endpoint
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
"system.datasource.enableCustomDatabase": settings.enableCustomDatabase,
"system.datasource.customDatabaseUrl": settings.customDatabaseUrl,
"system.datasource.username": settings.username,
@@ -142,8 +141,8 @@ export default function AdminDatabaseSection() {
const data = await databaseManagementService.getDatabaseData();
setBackupFiles(data.backupFiles || []);
setDatabaseVersion(data.databaseVersion || null);
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.loadError", "Failed to load database backups"),
@@ -190,8 +189,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.createBackup();
alert({ alertType: "success", title: t("admin.settings.database.backupCreated", "Backup created successfully") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.backupFailed", "Failed to create backup"),
@@ -210,8 +209,8 @@ export default function AdminDatabaseSection() {
alert({ alertType: "success", title: t("admin.settings.database.importSuccess", "Backup imported successfully") });
setUploadFile(null);
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -271,8 +270,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.importFromFileName(fileName);
alert({ alertType: "success", title: t("admin.settings.database.importSuccess", "Backup imported successfully") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.importFailed", "Failed to import backup"),
@@ -290,8 +289,8 @@ export default function AdminDatabaseSection() {
await databaseManagementService.deleteBackup(fileName);
alert({ alertType: "success", title: t("admin.settings.database.deleteSuccess", "Backup deleted") });
await loadBackupData();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.deleteFailed", "Failed to delete backup"),
@@ -321,8 +320,8 @@ export default function AdminDatabaseSection() {
link.download = fileName;
document.body.appendChild(link);
link.click();
} catch (error: unknown) {
const message = isAxiosError(error) ? (error.response?.data?.message || error.message) : undefined;
} catch (error: any) {
const message = error?.response?.data?.message || error?.message;
alert({
alertType: "error",
title: t("admin.settings.database.downloadFailed", "Failed to download backup"),
@@ -38,11 +38,11 @@ export default function AdminFeaturesSection() {
isFieldPending,
} = useAdminSettings<FeaturesSettingsData>({
sectionName: 'features',
fetchTransformer: async (): Promise<FeaturesSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<FeaturesSettingsData & { _pending?: Record<string, any> }> => {
const systemResponse = await apiClient.get('/api/v1/admin/settings/section/system');
const systemData = systemResponse.data || {};
const result: FeaturesSettingsData & { _pending?: Record<string, unknown> } = {
const result: FeaturesSettingsData & { _pending?: Record<string, any> } = {
serverCertificate: systemData.serverCertificate || {
enabled: true,
organizationName: 'Stirling-PDF',
@@ -59,7 +59,7 @@ export default function AdminFeaturesSection() {
return result;
},
saveTransformer: (settings: FeaturesSettingsData) => {
const deltaSettings: Record<string, unknown> = {};
const deltaSettings: Record<string, any> = {};
if (settings.serverCertificate) {
deltaSettings['system.serverCertificate.enabled'] = settings.serverCertificate.enabled;
@@ -91,7 +91,7 @@ export default function AdminGeneralSection() {
isFieldPending,
} = useAdminSettings<GeneralSettingsData>({
sectionName: 'general',
fetchTransformer: async (): Promise<GeneralSettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<GeneralSettingsData & { _pending?: Record<string, any> }> => {
const [uiResponse, systemResponse, premiumResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/ui'),
apiClient.get('/api/v1/admin/settings/section/system'),
@@ -113,7 +113,7 @@ export default function AdminGeneralSection() {
? watchedFoldersDirs
: (pipelinePaths.watchedFoldersDir ? [pipelinePaths.watchedFoldersDir] : []);
const result: GeneralSettingsData & { _pending?: Record<string, unknown> } = {
const result: GeneralSettingsData & { _pending?: Record<string, any> } = {
ui,
system,
customPaths: {
@@ -140,7 +140,7 @@ export default function AdminGeneralSection() {
};
// Merge pending blocks from all three endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (ui._pending) {
pendingBlock.ui = ui._pending;
}
@@ -161,7 +161,7 @@ export default function AdminGeneralSection() {
return result;
},
saveTransformer: (settings: GeneralSettingsData) => {
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
// UI settings
'ui.appNameNavbar': settings.ui?.appNameNavbar,
'ui.languages': settings.ui?.languages,
@@ -72,12 +72,12 @@ const AdminPlanSection: React.FC = () => {
// Open billing portal in new tab
window.open(response.url, '_blank');
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to open billing portal:', error);
alert({
alertType: 'error',
title: t('billing.portal.error', 'Failed to open billing portal'),
body: (error instanceof Error ? error.message : undefined) || 'Please try again or contact support.',
body: error.message || 'Please try again or contact support.',
});
}
}, [licenseInfo, t, validateLoginEnabled]);
@@ -33,7 +33,7 @@ export default function AdminPrivacySection() {
isFieldPending,
} = useAdminSettings<PrivacySettingsData>({
sectionName: 'privacy',
fetchTransformer: async (): Promise<PrivacySettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<PrivacySettingsData & { _pending?: Record<string, any> }> => {
const [metricsResponse, systemResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/metrics'),
apiClient.get('/api/v1/admin/settings/section/system')
@@ -42,14 +42,14 @@ export default function AdminPrivacySection() {
const metrics = metricsResponse.data;
const system = systemResponse.data;
const result: PrivacySettingsData & { _pending?: Record<string, unknown> } = {
const result: PrivacySettingsData & { _pending?: Record<string, any> } = {
enableAnalytics: system.enableAnalytics || false,
googleVisibility: system.googlevisibility || false,
metricsEnabled: metrics.enabled || false
};
// Merge pending blocks from both endpoints
const pendingBlock: Record<string, unknown> = {};
const pendingBlock: Record<string, any> = {};
if (system._pending?.enableAnalytics !== undefined) {
pendingBlock.enableAnalytics = system._pending.enableAnalytics;
}
@@ -67,7 +67,7 @@ export default function AdminSecuritySection() {
isFieldPending,
} = useAdminSettings<SecuritySettingsData>({
sectionName: 'security',
fetchTransformer: async (): Promise<SecuritySettingsData & { _pending?: Record<string, unknown> }> => {
fetchTransformer: async (): Promise<SecuritySettingsData & { _pending?: Record<string, any> }> => {
const [securityResponse, premiumResponse, systemResponse] = await Promise.all([
apiClient.get('/api/v1/admin/settings/section/security'),
apiClient.get('/api/v1/admin/settings/section/premium'),
@@ -93,7 +93,7 @@ export default function AdminSecuritySection() {
systemPending: JSON.parse(JSON.stringify(systemPending || {}))
});
const combined: SecuritySettingsData & { _pending?: Record<string, unknown> } = {
const combined: SecuritySettingsData & { _pending?: Record<string, any> } = {
...securityActive
};
@@ -108,7 +108,7 @@ export default function AdminSecuritySection() {
}
// Merge all _pending blocks
const mergedPending: Record<string, unknown> = {};
const mergedPending: Record<string, any> = {};
if (securityPending) {
Object.assign(mergedPending, securityPending);
}
@@ -128,7 +128,7 @@ export default function AdminSecuritySection() {
saveTransformer: (settings: SecuritySettingsData) => {
const { audit, html, ...securitySettings } = settings;
const deltaSettings: Record<string, unknown> = {
const deltaSettings: Record<string, any> = {
// Security settings
'security.enableLogin': securitySettings.enableLogin,
'security.loginMethod': securitySettings.loginMethod,
@@ -155,10 +155,10 @@ const AdminUsageSection: React.FC = () => {
const displayedVisits = endpoints.reduce((sum, e) => sum + e.visits, 0);
const totalVisits = Number.isFinite(data?.totalVisits)
? Math.max(0, data?.totalVisits ?? 0)
? Math.max(0, data?.totalVisits as number)
: displayedVisits;
const totalEndpoints = Number.isFinite(data?.totalEndpoints)
? Math.max(0, data?.totalEndpoints ?? 0)
? Math.max(0, data?.totalEndpoints as number)
: endpoints.length;
const displayedPercentage = totalVisits > 0
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -18,7 +17,6 @@ import {
CloseButton,
Avatar,
Box,
type ComboboxItem,
} from '@mantine/core';
import LocalIcon from '@app/components/shared/LocalIcon';
import { alert } from '@app/components/toast';
@@ -53,7 +51,6 @@ export default function PeopleSection() {
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [processing, setProcessing] = useState(false);
const [mailEnabled, setMailEnabled] = useState(false);
const [lockedUsers, setLockedUsers] = useState<string[]>([]);
// License information
const [licenseInfo, setLicenseInfo] = useState<{
@@ -83,7 +80,6 @@ export default function PeopleSection() {
: null;
const isCurrentUser = (user: User) => currentUser?.username === user.username;
const isLockedUser = (user: User) => lockedUsers.includes(user.username);
// Form state for edit user modal
const [editForm, setEditForm] = useState({
@@ -116,7 +112,7 @@ export default function PeopleSection() {
...user,
isActive: adminData.userSessions[user.username] || false,
lastRequest: adminData.userLastRequest[user.username] || undefined,
mfaEnabled: (adminData.userSettings?.[user.username] as Record<string, unknown> | undefined)?.mfaEnabled === 'true',
mfaEnabled: adminData.userSettings?.[user.username]?.mfaEnabled === 'true',
}));
setUsers(enrichedUsers);
@@ -132,7 +128,6 @@ export default function PeopleSection() {
totalUsers: adminData.totalUsers,
});
setMailEnabled(adminData.mailEnabled);
setLockedUsers(adminData.lockedUsers || []);
} else {
// Provide example data when login is disabled
const exampleUsers: User[] = [
@@ -194,7 +189,6 @@ export default function PeopleSection() {
setUsers(exampleUsers);
setTeams(exampleTeams);
setMailEnabled(false);
setLockedUsers([]);
// Example license information
setLicenseInfo({
@@ -227,11 +221,12 @@ export default function PeopleSection() {
alert({ alertType: 'success', title: t('workspace.people.editMember.success') });
closeEditModal();
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to update user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.editMember.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.editMember.error');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -243,11 +238,12 @@ export default function PeopleSection() {
await userManagementService.toggleUserEnabled(user.username, !user.enabled);
alert({ alertType: 'success', title: t('workspace.people.toggleEnabled.success') });
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to toggle user status:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.toggleEnabled.error');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.toggleEnabled.error');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -262,31 +258,12 @@ export default function PeopleSection() {
await userManagementService.deleteUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.deleteUserSuccess', 'User deleted successfully') });
fetchData();
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to delete user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
}
};
const handleUnlockUser = async (user: User) => {
const confirmMessage = t('workspace.people.confirmUnlock', 'Are you sure you want to unlock this user account?');
if (!window.confirm(`${confirmMessage}\n\nUser: ${user.username}`)) {
return;
}
try {
await userManagementService.unlockUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.unlockUserSuccess', 'User account unlocked successfully') });
fetchData();
} catch (error: unknown) {
console.error('[PeopleSection] Failed to unlock user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.unlockUserError', 'Failed to unlock user account');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
}
};
@@ -338,9 +315,9 @@ export default function PeopleSection() {
},
];
const renderRoleOption = ({ option }: { option: ComboboxItem & { icon?: string; description?: string } }) => (
const renderRoleOption = ({ option }: { option: any }) => (
<Group gap="sm" wrap="nowrap">
<LocalIcon icon={option.icon ?? ''} width="1.25rem" height="1.25rem" style={{ flexShrink: 0 }} />
<LocalIcon icon={option.icon} width="1.25rem" height="1.25rem" style={{ flexShrink: 0 }} />
<Box style={{ flex: 1 }}>
<Text size="sm" fw={500}>{option.label}</Text>
<Text size="xs" c="dimmed" style={{ whiteSpace: 'normal', lineHeight: 1.4 }}>
@@ -412,12 +389,6 @@ export default function PeopleSection() {
</Text>
)}
{lockedUsers.length > 0 && (
<Badge color="orange" variant="light" size="sm">
{lockedUsers.length} {t('workspace.people.locked', 'locked')}
</Badge>
)}
{licenseInfo.premiumEnabled && licenseInfo.licenseMaxUsers > 0 && (
<Badge color="blue" variant="light" size="sm">
+{licenseInfo.licenseMaxUsers} {t('workspace.people.license.fromLicense', 'from license')}
@@ -526,29 +497,22 @@ export default function PeopleSection() {
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<Group gap={6} wrap="nowrap" align="center">
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{isLockedUser(user) && (
<Badge color="orange" variant="light" size="xs">
{t('workspace.people.lockedBadge', 'Locked')}
</Badge>
)}
</Group>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -648,15 +612,6 @@ export default function PeopleSection() {
{user.enabled ? t('workspace.people.disable') : t('workspace.people.enable')}
</Menu.Item>
)}
{!isCurrentUser(user) && isLockedUser(user) && (
<Menu.Item
leftSection={<LocalIcon icon="lock-open" width="1rem" height="1rem" />}
onClick={() => handleUnlockUser(user)}
disabled={!loginEnabled}
>
{t('workspace.people.unlockAccount', 'Unlock Account')}
</Menu.Item>
)}
{!isCurrentUser(user) && user.mfaEnabled && (
<>
<Menu.Divider />
@@ -667,12 +622,12 @@ export default function PeopleSection() {
try {
await userManagementService.disableMfaByAdmin(user.username);
alert({ alertType: 'success', title: t('workspace.people.mfa.adminDisableSuccess', 'MFA disabled successfully for user') });
} catch (error: unknown) {
} catch (error: any) {
console.error('[PeopleSection] Failed to disable MFA for user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.mfa.adminDisableError', 'Failed to disable MFA for user');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.mfa.adminDisableError', 'Failed to disable MFA for user');
alert({ alertType: 'error', title: errorMessage });
}
}}
@@ -1,5 +1,4 @@
import { useState, useEffect } from 'react';
import { isAxiosError } from 'axios';
import { useTranslation } from 'react-i18next';
import {
Stack,
@@ -52,9 +51,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
availableSlots: number;
} | null>(null);
const [mailEnabled, setMailEnabled] = useState(false);
const [lockedUsers, setLockedUsers] = useState<string[]>([]);
const isLockedUser = (user: User) => lockedUsers.includes(user.username);
useEffect(() => {
fetchTeamDetails();
@@ -79,7 +75,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
availableSlots: adminData.availableSlots,
});
setMailEnabled(adminData.mailEnabled);
setLockedUsers(adminData.lockedUsers || []);
} catch (error) {
console.error('Failed to fetch team details:', error);
alert({ alertType: 'error', title: t('workspace.teams.loadError', 'Failed to load team details') });
@@ -111,11 +106,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setAddMemberModalOpened(false);
setSelectedUserId('');
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to add member:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.addMemberToTeam.error', 'Failed to add user to team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.addMemberToTeam.error', 'Failed to add user to team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -140,11 +136,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
await teamService.moveUserToTeam(user.username, user.rolesAsString || 'ROLE_USER', defaultTeam.id);
alert({ alertType: 'success', title: t('workspace.teams.removeMemberSuccess', 'User removed from team') });
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to remove member:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.teams.removeMemberError', 'Failed to remove user from team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.removeMemberError', 'Failed to remove user from team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -162,37 +159,18 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
await userManagementService.deleteUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.deleteUserSuccess', 'User deleted successfully') });
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to delete user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.people.deleteUserError', 'Failed to delete user');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.people.deleteUserError', 'Failed to delete user');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
}
};
const handleUnlockUser = async (user: User) => {
const confirmMessage = t('workspace.people.confirmUnlock', 'Are you sure you want to unlock this user account?');
if (!window.confirm(`${confirmMessage}\n\nUser: ${user.username}`)) {
return;
}
try {
await userManagementService.unlockUser(user.username);
alert({ alertType: 'success', title: t('workspace.people.unlockUserSuccess', 'User account unlocked successfully') });
fetchTeamDetails();
} catch (error: unknown) {
console.error('[TeamDetailsSection] Failed to unlock user:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) || t('workspace.people.unlockUserError', 'Failed to unlock user account');
alert({ alertType: 'error', title: errorMessage });
}
};
const openChangeTeamModal = (user: User) => {
setSelectedUser(user);
setSelectedTeamId(user.team?.id?.toString() || '');
@@ -223,12 +201,12 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
setSelectedUser(null);
setSelectedTeamId('');
fetchTeamDetails();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to change team:', error);
const errorMessage = isAxiosError(error)
? (error.response?.data?.message || error.response?.data?.error || error.message)
: (error instanceof Error ? error.message : undefined) ||
t('workspace.teams.changeTeam.error', 'Failed to change team');
const errorMessage = error.response?.data?.message ||
error.response?.data?.error ||
error.message ||
t('workspace.teams.changeTeam.error', 'Failed to change team');
alert({ alertType: 'error', title: errorMessage });
} finally {
setProcessing(false);
@@ -357,29 +335,22 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
</Avatar>
</Tooltip>
<Box style={{ minWidth: 0, flex: 1 }}>
<Group gap={6} wrap="nowrap" align="center">
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{isLockedUser(user) && (
<Badge color="orange" variant="light" size="xs">
{t('workspace.people.lockedBadge', 'Locked')}
</Badge>
)}
</Group>
<Tooltip label={user.username} disabled={user.username.length <= 20} zIndex={Z_INDEX_OVER_CONFIG_MODAL}>
<Text
size="sm"
fw={500}
maw={200}
style={{
lineHeight: 1.3,
opacity: user.enabled ? 1 : 0.6,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{user.username}
</Text>
</Tooltip>
{user.email && (
<Text size="xs" c="dimmed" truncate style={{ lineHeight: 1.3 }}>
{user.email}
@@ -449,15 +420,6 @@ export default function TeamDetailsSection({ teamId, onBack }: TeamDetailsSectio
>
{t('workspace.people.changePassword.action', 'Change password')}
</Menu.Item>
{isLockedUser(user) && (
<Menu.Item
leftSection={<LocalIcon icon="lock-open" width="1rem" height="1rem" />}
onClick={() => handleUnlockUser(user)}
disabled={processing}
>
{t('workspace.people.unlockAccount', 'Unlock Account')}
</Menu.Item>
)}
{team.name !== 'Internal' && team.name !== 'Default' && (
<Menu.Item
leftSection={<LocalIcon icon="person-remove" width="1rem" height="1rem" />}

Some files were not shown because too many files have changed in this diff Show More