Skip to content

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

Fix PDF permission inspection and annotation lifecycle regressions (#8566)

ConnorYohf690c13cad99
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java
index 74db35fb22..7436bbb824 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.controller.api.security;
import java.io.IOException;
+import java.nio.file.Files;
import java.security.SecureRandom;
import java.util.HexFormat;
@@ -8,10 +9,14 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;
@@ -20,9 +25,14 @@ import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.SPDF.model.api.security.AddPasswordRequest;
import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
+import stirling.software.SPDF.model.api.security.RemovePasswordRequest;
+import stirling.software.SPDF.service.PdfPasswordRoles;
+import stirling.software.SPDF.service.PdfPermissionSecurityHandler;
+import stirling.software.SPDF.service.PdfSessionPermissions;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.SecurityApi;
import stirling.software.common.enumeration.ResourceWeight;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.tool.ToolArity;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
@@ -31,9 +41,16 @@ import stirling.software.common.model.tool.ToolIOWhen;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.jpdfium.doc.PdfSecurity;
+import stirling.software.jpdfium.exception.JPDFiumException;
+/**
+ * Owns password and permission changes, plus preparation and restoration for protected tool inputs.
+ * Documents and credentials live only for the request.
+ */
@SecurityApi
@RequiredArgsConstructor
public class PasswordController {
@@ -42,6 +59,7 @@ public class PasswordController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
+ private final ApplicationProperties applicationProperties;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -50,34 +68,73 @@ public class PasswordController {
@StandardPdfResponse
@ToolIO(
accepts = {ToolFormat.PDF, ToolFormat.PDF_ENCRYPTED},
- produces = ToolFormat.PDF)
+ produces = ToolFormat.PDF,
+ cases =
+ @ToolIOCase(
+ when = @ToolIOWhen(param = "password", matches = ""),
+ produces = ToolFormat.ANY,
+ arity = ToolArity.SISO))
@Operation(
summary = "Remove password from a PDF file",
description =
"This endpoint removes the password from a protected PDF file while preserving"
+ " its document permissions. Users need to provide the existing"
- + " password.")
- public ResponseEntity<Resource> removePassword(@ModelAttribute PDFPasswordRequest request)
+ + " password. Optional ownerPassword, sourcePassword or retainedOpeningPassword"
+ + " enable selective removal: nonempty password and ownerPassword select"
+ + " which passwords to remove; blank selections retain them. removeAll explicitly removes all protection, subject to the owner-password policy. Source and"
+ + " retained credentials never select removal.")
+ public ResponseEntity<Resource> removePassword(@ModelAttribute RemovePasswordRequest request)
throws IOException {
MultipartFile fileInput = request.getFileInput();
String password = request.getPassword();
- try (PDDocument document = pdfDocumentFactory.load(fileInput, password)) {
- document.setAllSecurityToBeRemoved(true);
- if (document.isEncrypted()) {
- // Owner-password access reports all permissions, so read the stored flags.
- AccessPermission permissions =
- new AccessPermission(document.getEncryption().getPermissions());
- if (!permissions.isOwnerPermission()) {
- // An empty owner password would grant unrestricted access on opening.
- byte[] ownerPasswordBytes = new byte[32];
- SECURE_RANDOM.nextBytes(ownerPasswordBytes);
- StandardProtectionPolicy protection =
- new StandardProtectionPolicy(
- HexFormat.of().formatHex(ownerPasswordBytes), "", permissions);
- protection.setEncryptionKeyLength(256);
- document.setAllSecurityToBeRemoved(false);
- document.protect(protection);
+ boolean selective =
+ request.getOwnerPassword() != null
+ || request.getSourcePassword() != null
+ || request.getRetainedOpeningPassword() != null;
+ String credential = password;
+ if (selective) {
+ credential = request.getOwnerPassword();
+ if (credential == null || credential.isEmpty()) {
+ credential = request.getSourcePassword();
+ if (credential == null) credential = password;
+ }
+ if (credential == null) credential = "";
+ }
+ if (request.isRemoveAll()) {
+ credential =
+ request.getSourcePassword() == null ? password : request.getSourcePassword();
+ if (credential == null) credential = "";
+ }
+ try (PDDocument document =
+ request.isRemoveAll()
+ ? pdfDocumentFactory.load(fileInput, credential, true)
+ : pdfDocumentFactory.load(fileInput, credential)) {
+ if (request.isRemoveAll()) {
+ PdfSessionPermissions.requireOwner(
+ document, applicationProperties.getSecurity().isHonorOwnerPasswords());
+ document.setAllSecurityToBeRemoved(true);
+ } else if (selective) {
+ removeSelectedPasswords(document, request, credential);
+ } else {
+ document.setAllSecurityToBeRemoved(true);
+ if (document.isEncrypted()) {
+ // Owner-password access reports all permissions, so read the stored flags.
+ AccessPermission permissions =
+ new AccessPermission(document.getEncryption().getPermissions());
+ if (!permissions.isOwnerPermission()) {
+ // An empty owner password would grant unrestricted access on opening.
+ byte[] ownerPasswordBytes = new byte[32];
+ SECURE_RANDOM.nextBytes(ownerPasswordBytes);
+ StandardProtectionPolicy protection =
+ new StandardProtectionPolicy(
+ HexFormat.of().formatHex(ownerPasswordBytes),
+ "",
+ permissions);
+ protection.setEncryptionKeyLength(256);
+ document.setAllSecurityToBeRemoved(false);
+ document.protect(protection);
+ }
}
}
return WebResponseUtils.pdfDocToWebResponse(
@@ -95,18 +152,81 @@ public class PasswordController {
}
}
+ private void removeSelectedPasswords(
+ PDDocument document, RemovePasswordRequest request, String credential)
+ throws IOException {
+ String openingPassword = request.getPassword() == null ? "" : request.getPassword();
+ String ownerPassword = request.getOwnerPassword() == null ? "" : request.getOwnerPassword();
+ String retainedOpeningPassword =
+ request.getRetainedOpeningPassword() == null
+ ? ""
+ : request.getRetainedOpeningPassword();
+ boolean removeOpening = !openingPassword.isEmpty();
+ boolean removeOwner = !ownerPassword.isEmpty();
+ if (!removeOpening && !removeOwner) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Enter a password to remove");
+ }
+ PdfSessionPermissions.requireOwner(document, false);
+ boolean openingSet =
+ document.isEncrypted() && !PdfPasswordRoles.isOpeningPassword(document, "");
+ boolean ownerSet = PdfPasswordRoles.hasSeparateOwnerPassword(document, credential);
+ if (removeOpening
+ && (!openingSet
+ || !PdfPasswordRoles.isOpeningPassword(document, openingPassword))) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "The opening password is incorrect or is not set");
+ }
+ if (removeOwner && (!ownerSet || !PdfSessionPermissions.isOwnerAuthenticated(document))) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "The permissions password is incorrect or is not set");
+ }
+ if ((!openingSet || removeOpening) && (!ownerSet || removeOwner)) {
+ document.setAllSecurityToBeRemoved(true);
+ } else if (removeOpening) {
+ // Replacing U also changes the owner-password derivation. Verification is needed
+ // to retain that credential even when enforcement is disabled by server policy.
+ if (!PdfSessionPermissions.isOwnerAuthenticated(document)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Verify the permissions password to retain it while removing the opening password");
+ }
+ var protection =
+ new StandardProtectionPolicy(
+ credential,
+ "",
+ new AccessPermission(document.getEncryption().getPermissions()));
+ protection.setEncryptionKeyLength(document.getEncryption().getLength());
+ protection.setPreferAES(document.getEncryption().getVersion() >= 4);
+ document.protect(protection);
+ } else {
+ if (!PdfPasswordRoles.isOpeningPassword(document, retainedOpeningPassword)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Open the PDF with its opening password before removing only the permissions password");
+ }
+ var protection =
+ new StandardProtectionPolicy(
+ "", retainedOpeningPassword, new AccessPermission());
+ protection.setEncryptionKeyLength(document.getEncryption().getLength());
+ protection.setPreferAES(document.getEncryption().getVersion() >= 4);
+ document.protect(protection);
+ }
+ }
+
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/add-password",
resourceWeight = ResourceWeight.MEDIUM_WEIGHT)
@StandardPdfResponse
@ToolIO(
+ accepts = {ToolFormat.PDF, ToolFormat.PDF_ENCRYPTED},
produces = ToolFormat.PDF_ENCRYPTED,
cases =
@ToolIOCase(
when = {
@ToolIOWhen(param = "password", matches = ""),
- @ToolIOWhen(param = "ownerPassword", matches = "")
+ @ToolIOWhen(param = "ownerPassword", matches = ""),
+ @ToolIOWhen(param = "preserveExisting", matches = "false")
},
produces = ToolFormat.PDF,
arity = ToolArity.SISO))
@@ -114,56 +234,204 @@ public class PasswordController {
summary = "Add password to a PDF file",
description =
"This endpoint adds password protection to a PDF file. Users can specify a set"
- + " of permissions that should be applied to the file.")
+ + " of permissions that should be applied to the file. sourcePassword authenticates an existing protected source; preserveExisting changes permissions while retaining existing credentials. Omitting these options preserves the existing add-password behaviour.")
public ResponseEntity<Resource> addPassword(@ModelAttribute AddPasswordRequest request)
throws IOException {
- MultipartFile fileInput = request.getFileInput();
- String ownerPassword = request.getOwnerPassword();
- String password = request.getPassword();
- int keyLength = request.getKeyLength();
- boolean preventAssembly = Boolean.TRUE.equals(request.getPreventAssembly());
- boolean preventExtractContent = Boolean.TRUE.equals(request.getPreventExtractContent());
- boolean preventExtractForAccessibility =
- Boolean.TRUE.equals(request.getPreventExtractForAccessibility());
- boolean preventFillInForm = Boolean.TRUE.equals(request.getPreventFillInForm());
- boolean preventModify = Boolean.TRUE.equals(request.getPreventModify());
- boolean preventModifyAnnotations =
- Boolean.TRUE.equals(request.getPreventModifyAnnotations());
- boolean preventPrinting = Boolean.TRUE.equals(request.getPreventPrinting());
- boolean preventPrintingFaithful = Boolean.TRUE.equals(request.getPreventPrintingFaithful());
-
- try (PDDocument document = pdfDocumentFactory.load(fileInput)) {
- AccessPermission ap = new AccessPermission();
- ap.setCanAssembleDocument(!preventAssembly);
- ap.setCanExtractContent(!preventExtractContent);
- ap.setCanExtractForAccessibility(!preventExtractForAccessibility);
- ap.setCanFillInForm(!preventFillInForm);
- ap.setCanModify(!preventModify);
- ap.setCanModifyAnnotations(!preventModifyAnnotations);
- ap.setCanPrint(!preventPrinting);
- ap.setCanPrintFaithful(!preventPrintingFaithful);
- StandardProtectionPolicy spp =
- new StandardProtectionPolicy(ownerPassword, password, ap);
-
- if ((ownerPassword != null && !ownerPassword.isEmpty())
- || (password != null && !password.isEmpty())) {
- spp.setEncryptionKeyLength(keyLength);
+ boolean explicitProtection =
+ request.getSourcePassword() != null || request.isPreserveExisting();
+ try (PDDocument document =
+ pdfDocumentFactory.load(
+ request.getFileInput(),
+ request.getSourcePassword() == null ? "" : request.getSourcePassword(),
+ true)) {
+ if (explicitProtection || document.isEncrypted()) {
+ PdfSessionPermissions.requireOwner(
+ document, applicationProperties.getSecurity().isHonorOwnerPasswords());
}
- spp.setPermissions(ap);
- document.protect(spp);
-
- if ((ownerPassword == null || ownerPassword.isEmpty())
- && (password == null || password.isEmpty()))
- return WebResponseUtils.pdfDocToWebResponse(
- document,
- GeneralUtils.generateFilename(
- fileInput.getOriginalFilename(), "_permissions.pdf"),
- tempFileManager);
- return WebResponseUtils.pdfDocToWebResponse(
+ var permissions = requestedPermissions(request);
+ if (request.isPreserveExisting() && document.isEncrypted()) {
+ String credential =
+ request.getSourcePassword() == null ? "" : request.getSourcePassword();
+ if (request.getOwnerPassword() == null || request.getOwnerPassword().isEmpty()) {
+ if (!permissions.isOwnerPermission()
+ && !PdfPasswordRoles.hasSeparateOwnerPassword(document, credential)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Choose a separate permissions password to restrict actions");
+ }
+ PdfPermissionSecurityHandler.changePermissions(
+ document, credential, permissions);
+ return WebResponseUtils.pdfDocToWebResponse(
+ document,
+ GeneralUtils.generateFilename(
+ request.getFileInput().getOriginalFilename(),
+ "_permissions.pdf"),
+ tempFileManager);
+ }
+ String reader = request.getPassword() == null ? "" : request.getPassword();
+ if (!PdfPasswordRoles.isOpeningPassword(document, reader)) {
+ if (!PdfPasswordRoles.isOpeningPassword(document, credential)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Open the PDF with its opening password before replacing the permissions password");
+ }
+ reader = credential;
+ }
+ request.setPassword(reader);
+ request.setKeyLength(document.getEncryption().getLength());
+ }
+ return applyProtection(document, request, permissions, explicitProtection);
+ }
+ }
+
+ private ResponseEntity<Resource> applyProtection(
+ PDDocument document,
+ AddPasswordRequest request,
+ AccessPermission permissions,
+ boolean validate)
+ throws IOException {
+ String owner = request.getOwnerPassword() == null ? "" : request.getOwnerPassword();
+ String reader = request.getPassword() == null ? "" : request.getPassword();
+ if (validate) {
+ if (!permissions.isOwnerPermission() && (owner.isEmpty() || owner.equals(reader))) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Restrictions require a nonempty permissions password different from the opening password");
+ }
+ if (owner.isEmpty() && reader.isEmpty()) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "Enter a password for the new protection");
+ }
+ if (request.getKeyLength() != 40
+ && request.getKeyLength() != 128
+ && request.getKeyLength() != 256) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "Unsupported encryption key length");
+ }
+ }
+ var protection = new StandardProtectionPolicy(owner, reader, permissions);
+ if (!owner.isEmpty() || !reader.isEmpty())
+ protection.setEncryptionKeyLength(request.getKeyLength());
+ if (validate
+ && document.isEncrypted()
+ && request.getKeyLength() == document.getEncryption().getLength()) {
+ protection.setPreferAES(document.getEncryption().getVersion() >= 4);
+ }
+ document.protect(protection);
+ String suffix =
+ owner.isEmpty() && reader.isEmpty() ? "_permissions.pdf" : "_passworded.pdf";
+ String filename =
+ GeneralUtils.generateFilename(request.getFileInput().getOriginalFilename(), suffix);
+ if (!validate || permissions.isOwnerPermission()) {
+ return WebResponseUtils.pdfDocToWebResponse(document, filename, tempFileManager);
+ }
+ var output = tempFileManager.createManagedTempFile(".pdf");
+ try {
+ document.save(output.getFile());
+ // PDF password encoding/truncation can collapse distinct credentials into the same
+ // role.
+ try (var stream = Files.newInputStream(output.getPath());
+ var result = pdfDocumentFactory.load(stream, reader, true)) {
+ if (PdfSessionPermissions.isOwnerAuthenticated(result)) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "The opening and permissions passwords must remain distinct after PDF encoding");
+ }
+ }
+ return WebResponseUtils.pdfFileToWebResponse(output, filename);
+ } catch (IOException | RuntimeException e) {
+ output.close();
+ throw e;
+ }
+ }
+
+ private AccessPermission requestedPermissions(AddPasswordRequest request) {
+ var permissions = new AccessPermission();
+ permissions.setCanAssembleDocument(!Boolean.TRUE.equals(request.getPreventAssembly()));
+ permissions.setCanExtractContent(!Boolean.TRUE.equals(request.getPreventExtractContent()));
+ permissions.setCanExtractForAccessibility(
+ !Boolean.TRUE.equals(request.getPreventExtractForAccessibility()));
+ permissions.setCanFillInForm(!Boolean.TRUE.equals(request.getPreventFillInForm()));
+ permissions.setCanModify(!Boolean.TRUE.equals(request.getPreventModify()));
+ permissions.setCanModifyAnnotations(
+ !Boolean.TRUE.equals(request.getPreventModifyAnnotations()));
+ permissions.setCanPrint(!Boolean.TRUE.equals(request.getPreventPrinting()));
+ permissions.setCanPrintFaithful(!Boolean.TRUE.equals(request.getPreventPrintingFaithful()));
+ return permissions;
+ }
+
+ /**
+ * Working bytes may only be used transiently for the authorised operation, never as an export.
+ */
+ @Operation(hidden = true)
+ @PostMapping(value = "/prepare-pdf-session", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public ResponseEntity<Resource> prepare(
+ @ModelAttribute PDFPasswordRequest request, @RequestParam String endpoint)
+ throws IOException {
+ try (PDDocument document =
+ pdfDocumentFactory.load(request.getFileInput(), request.getPassword(), true)) {
+ PdfSessionPermissions.requireOperation(
document,
- GeneralUtils.generateFilename(
- fileInput.getOriginalFilename(), "_passworded.pdf"),
- tempFileManager);
+ endpoint,
+ applicationProperties.getSecurity().isHonorOwnerPasswords());
+ document.setAllSecurityToBeRemoved(true);
+ return WebResponseUtils.pdfDocToWebResponse(
+ document, request.getFileInput().getOriginalFilename(), tempFileManager);
+ }
+ }
+
+ /**
+ * Restore the source's encryption, including an unknown second password, before returning a
+ * processed PDF.
+ */
+ @Operation(hidden = true)
+ @PostMapping(value = "/restore-pdf-protection", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public ResponseEntity<Resource> restore(
+ @RequestParam MultipartFile fileInput,
+ @RequestParam MultipartFile sourceFile,
+ @RequestParam String password)
+ throws IOException {
+ int sourcePermissions;
+ int sourceKeyLength;
+ int sourceRevision;
+ try (PDDocument source = pdfDocumentFactory.load(sourceFile, password, true)) {
+ if (!source.isEncrypted())
+ throw new IOException("The protection source is not encrypted");
+ if (!source.getSignatureDictionaries().isEmpty())
+ throw new IOException("Protection restoration does not support signed source PDFs");
+ // Effective owner access is unrestricted even when the encryption dictionary is not.
+ sourcePermissions = source.getEncryption().getPermissions();
+ sourceKeyLength = source.getEncryption().getLength();
+ sourceRevision = source.getEncryption().getRevision();
+ }
+
+ TempFile output = tempFileManager.createManagedTempFile(".pdf");
+ boolean transferred = false;
+ try (TempFile input = new TempFile(tempFileManager, ".pdf");
+ TempFile source = new TempFile(tempFileManager, ".pdf")) {
+ fileInput.transferTo(input.getFile());
+ sourceFile.transferTo(source.getFile());
+ try {
+ PdfSecurity.copyEncryption(
+ input.getPath(), output.getPath(), source.getPath(), password);
+ } catch (JPDFiumException e) {
+ throw new IOException("Unable to restore PDF protection", e);
+ }
+ try (var stream = Files.newInputStream(output.getPath());
+ PDDocument protectedDocument =
+ pdfDocumentFactory.load(stream, password, true)) {
+ if (!protectedDocument.isEncrypted()
+ || protectedDocument.getEncryption().getPermissions() != sourcePermissions
+ || protectedDocument.getEncryption().getLength() != sourceKeyLength
+ || protectedDocument.getEncryption().getRevision() != sourceRevision)
+ throw new IOException("Output protection verification failed");
+ }
+ var response =
+ WebResponseUtils.pdfFileToWebResponse(output, fileInput.getOriginalFilename());
+ transferred = true;
+ return response;
+ } finally {
+ if (!transferred) output.close();
}
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java
deleted file mode 100644
index 210b30b745..0000000000
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java
+++ /dev/null
@@ -1,422 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.io.IOException;
-import java.nio.file.Files;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
-import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
-import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.server.ResponseStatusException;
-
-import io.swagger.v3.oas.annotations.Operation;
-
-import lombok.RequiredArgsConstructor;
-
-import stirling.software.SPDF.model.api.security.AddPasswordRequest;
-import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
-import stirling.software.SPDF.service.PdfPasswordRoles;
-import stirling.software.SPDF.service.PdfPermissionSecurityHandler;
-import stirling.software.SPDF.service.PdfSessionPermissions;
-import stirling.software.common.annotations.api.SecurityApi;
-import stirling.software.common.model.ApplicationProperties;
-import stirling.software.common.service.CustomPDFDocumentFactory;
-import stirling.software.common.util.TempFile;
-import stirling.software.common.util.TempFileManager;
-import stirling.software.common.util.WebResponseUtils;
-import stirling.software.jpdfium.doc.PdfSecurity;
-import stirling.software.jpdfium.exception.JPDFiumException;
-
-/** Stateless helpers for interactive unlocking. No endpoint retains credentials or documents. */
-@SecurityApi
-@RequiredArgsConstructor
-public class PdfSessionSecurityController {
- private final CustomPDFDocumentFactory pdfDocumentFactory;
- private final TempFileManager tempFileManager;
- private final ApplicationProperties applicationProperties;
-
- /**
- * Passwords are never returned; permissions describe the authenticated access to the original
- * bytes.
- */
- public record SecurityInfo(
- boolean encrypted,
- boolean signed,
- boolean ownerAuthenticated,
- int permissions,
- int encryptionKeyLength,
- int encryptionRevision,
- boolean canModify,
- boolean canAssemble,
- int pageCount,
- boolean canExtract,
- boolean canPrint,
- boolean canPrintFaithful,
- String credentialFingerprint,
- boolean requiresOpeningPassword,
- boolean openingAuthenticated,
- boolean hasOwnerPassword,
- boolean honorOwnerPasswords) {}
-
- /** Authenticate without saving, changing metadata, or removing encryption. */
- @Operation(hidden = true)
- @PostMapping(value = "/inspect-pdf-security", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public SecurityInfo inspect(@ModelAttribute PDFPasswordRequest request) throws IOException {
- String password = request.getPassword() == null ? "" : request.getPassword();
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), password, true)) {
- AccessPermission permission = document.getCurrentAccessPermission();
- return new SecurityInfo(
- document.isEncrypted(),
- !document.getSignatureDictionaries().isEmpty(),
- PdfSessionPermissions.isOwnerAuthenticated(document),
- document.isEncrypted()
- ? document.getEncryption().getPermissions()
- : permission.getPermissionBytes(),
- document.isEncrypted() ? document.getEncryption().getLength() : 0,
- document.isEncrypted() ? document.getEncryption().getRevision() : 0,
- permission.canModify(),
- permission.canAssembleDocument(),
- document.getNumberOfPages(),
- permission.canExtractContent(),
- permission.canPrint(),
- permission.canPrintFaithful(),
- PdfSessionPermissions.credentialFingerprint(document),
- document.isEncrypted() && requiresOpeningPassword(request.getFileInput()),
- PdfPasswordRoles.isOpeningPassword(document, password),
- PdfPasswordRoles.hasSeparateOwnerPassword(document, password),
- applicationProperties.getSecurity().isHonorOwnerPasswords());
- }
- }
-
- private boolean requiresOpeningPassword(MultipartFile file) throws IOException {
- try (PDDocument ignored = pdfDocumentFactory.load(file, "", true)) {
- return false;
- } catch (InvalidPasswordException e) {
- return true;
- }
- }
-
- /**
- * Changes permissions without replacing the opening credential, including when it is unknown.
- */
- @Operation(hidden = true)
- @PostMapping(value = "/change-pdf-permissions", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> changePermissions(
- @ModelAttribute AddPasswordRequest request,
- @RequestParam(defaultValue = "") String sourcePassword)
- throws IOException {
- try (PDDocument source =
- pdfDocumentFactory.load(request.getFileInput(), sourcePassword, true)) {
- PdfSessionPermissions.requireOwner(
- source, applicationProperties.getSecurity().isHonorOwnerPasswords());
- if (source.isEncrypted()) {
- if (request.getOwnerPassword() == null || request.getOwnerPassword().isEmpty()) {
- if (!requestedPermissions(request).isOwnerPermission()
- && !PdfPasswordRoles.hasSeparateOwnerPassword(source, sourcePassword)) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Choose a separate permissions password to restrict actions");
- }
- PdfPermissionSecurityHandler.changePermissions(
- source, sourcePassword, requestedPermissions(request));
- return WebResponseUtils.pdfDocToWebResponse(
- source, "permissions_updated.pdf", tempFileManager);
- }
- String reader = request.getPassword() == null ? "" : request.getPassword();
- if (!PdfPasswordRoles.isOpeningPassword(source, reader)) {
- if (!PdfPasswordRoles.isOpeningPassword(source, sourcePassword)) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Open the PDF with its opening password before replacing the permissions password");
- }
- reader = sourcePassword;
- }
- request.setPassword(reader);
- request.setKeyLength(source.getEncryption().getLength());
- }
- }
- return setProtection(request, sourcePassword);
- }
-
- /** Nonempty inputs select passwords for removal; session credentials never select removal. */
- @Operation(hidden = true)
- @PostMapping(value = "/remove-pdf-passwords", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> removePasswords(
- @ModelAttribute PDFPasswordRequest request,
- @RequestParam(defaultValue = "") String ownerPassword,
- @RequestParam(defaultValue = "") String sourcePassword,
- @RequestParam(defaultValue = "") String retainedOpeningPassword)
- throws IOException {
- String openingPassword = request.getPassword() == null ? "" : request.getPassword();
- boolean removeOpening = !openingPassword.isEmpty();
- boolean removeOwner = !ownerPassword.isEmpty();
- if (!removeOpening && !removeOwner) {
- throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Enter a password to remove");
- }
- String credential = removeOwner ? ownerPassword : sourcePassword;
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), credential, true)) {
- PdfSessionPermissions.requireOwner(document, false);
- boolean openingSet =
- document.isEncrypted() && requiresOpeningPassword(request.getFileInput());
- boolean ownerSet = PdfPasswordRoles.hasSeparateOwnerPassword(document, credential);
- if (removeOpening
- && (!openingSet
- || !PdfPasswordRoles.isOpeningPassword(document, openingPassword))) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST, "The opening password is incorrect or is not set");
- }
- if (removeOwner
- && (!ownerSet || !PdfSessionPermissions.isOwnerAuthenticated(document))) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "The permissions password is incorrect or is not set");
- }
- if ((!openingSet || removeOpening) && (!ownerSet || removeOwner)) {
- document.setAllSecurityToBeRemoved(true);
- } else if (removeOpening) {
- // Replacing U also changes the owner-password derivation. Verification is needed
- // to retain that credential even when enforcement is disabled by server policy.
- if (!PdfSessionPermissions.isOwnerAuthenticated(document)) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Verify the permissions password to retain it while removing the opening password");
- }
- var protection =
- new StandardProtectionPolicy(
- credential,
- "",
- new AccessPermission(document.getEncryption().getPermissions()));
- protection.setEncryptionKeyLength(document.getEncryption().getLength());
- protection.setPreferAES(document.getEncryption().getVersion() >= 4);
- document.protect(protection);
- } else {
- if (!PdfPasswordRoles.isOpeningPassword(document, retainedOpeningPassword)) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Open the PDF with its opening password before removing only the permissions password");
- }
- var protection =
- new StandardProtectionPolicy(
- "", retainedOpeningPassword, new AccessPermission());
- protection.setEncryptionKeyLength(document.getEncryption().getLength());
- protection.setPreferAES(document.getEncryption().getVersion() >= 4);
- document.protect(protection);
- }
- return WebResponseUtils.pdfDocToWebResponse(
- document, "password_removed.pdf", tempFileManager);
- }
- }
-
- /**
- * Working bytes may only be used transiently for the authorised operation, never as an export.
- */
- @Operation(hidden = true)
- @PostMapping(value = "/prepare-pdf-session", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> prepare(
- @ModelAttribute PDFPasswordRequest request, @RequestParam String endpoint)
- throws IOException {
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), request.getPassword(), true)) {
- PdfSessionPermissions.requireOperation(
- document,
- endpoint,
- applicationProperties.getSecurity().isHonorOwnerPasswords());
- document.setAllSecurityToBeRemoved(true);
- return WebResponseUtils.pdfDocToWebResponse(
- document, request.getFileInput().getOriginalFilename(), tempFileManager);
- }
- }
-
- /**
- * Retains restrictions and a verified permissions password, or an explicitly chosen
- * replacement.
- */
- @Operation(hidden = true)
- @PostMapping(
- value = "/remove-pdf-opening-password",
- consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> removeOpeningPassword(
- @ModelAttribute PDFPasswordRequest request,
- @RequestParam(defaultValue = "") String newOwnerPassword)
- throws IOException {
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), request.getPassword(), true)) {
- PdfSessionPermissions.requireOwner(
- document, applicationProperties.getSecurity().isHonorOwnerPasswords());
- if (document.isEncrypted()) {
- String owner =
- PdfSessionPermissions.isOwnerAuthenticated(document)
- ? request.getPassword()
- : newOwnerPassword;
- if (owner.isEmpty()) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Choose a new permissions password to retain restrictions");
- }
- var permissions = new AccessPermission(document.getEncryption().getPermissions());
- var protection = new StandardProtectionPolicy(owner, "", permissions);
- protection.setEncryptionKeyLength(document.getEncryption().getLength());
- protection.setPreferAES(document.getEncryption().getVersion() >= 4);
- document.protect(protection);
- }
- return WebResponseUtils.pdfDocToWebResponse(
- document, "opening_password_removed.pdf", tempFileManager);
- }
- }
-
- /**
- * Replaces protection deliberately; source authentication is separate from the new credentials.
- */
- @Operation(hidden = true)
- @PostMapping(value = "/set-pdf-protection", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> setProtection(
- @ModelAttribute AddPasswordRequest request,
- @RequestParam(defaultValue = "") String sourcePassword)
- throws IOException {
- var permissions = requestedPermissions(request);
- String owner = request.getOwnerPassword() == null ? "" : request.getOwnerPassword();
- String reader = request.getPassword() == null ? "" : request.getPassword();
- if (!permissions.isOwnerPermission() && (owner.isEmpty() || owner.equals(reader))) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "Restrictions require a nonempty permissions password different from the opening password");
- }
- if (owner.isEmpty() && reader.isEmpty()) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST, "Enter a password for the new protection");
- }
- if (request.getKeyLength() != 40
- && request.getKeyLength() != 128
- && request.getKeyLength() != 256) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST, "Unsupported encryption key length");
- }
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), sourcePassword, true)) {
- PdfSessionPermissions.requireOwner(
- document, applicationProperties.getSecurity().isHonorOwnerPasswords());
- var protection = new StandardProtectionPolicy(owner, reader, permissions);
- protection.setEncryptionKeyLength(request.getKeyLength());
- if (document.isEncrypted()
- && request.getKeyLength() == document.getEncryption().getLength()) {
- protection.setPreferAES(document.getEncryption().getVersion() >= 4);
- }
- document.protect(protection);
- var output = tempFileManager.createManagedTempFile(".pdf");
- try {
- document.save(output.getFile());
- // PDF password encoding/truncation can make different strings authenticate as
- // the same credential. Check the actual result before presenting restrictions.
- if (!permissions.isOwnerPermission()) {
- try (var stream = Files.newInputStream(output.getFile().toPath());
- var result = pdfDocumentFactory.load(stream, reader, true)) {
- if (PdfSessionPermissions.isOwnerAuthenticated(result)) {
- throw new ResponseStatusException(
- HttpStatus.BAD_REQUEST,
- "The opening and permissions passwords must remain distinct after PDF encoding");
- }
- }
- }
- return WebResponseUtils.pdfFileToWebResponse(output, "protected.pdf");
- } catch (IOException | RuntimeException e) {
- output.close();
- throw e;
- }
- }
- }
-
- private AccessPermission requestedPermissions(AddPasswordRequest request) {
- var permissions = new AccessPermission();
- permissions.setCanAssembleDocument(!Boolean.TRUE.equals(request.getPreventAssembly()));
- permissions.setCanExtractContent(!Boolean.TRUE.equals(request.getPreventExtractContent()));
- permissions.setCanExtractForAccessibility(
- !Boolean.TRUE.equals(request.getPreventExtractForAccessibility()));
- permissions.setCanFillInForm(!Boolean.TRUE.equals(request.getPreventFillInForm()));
- permissions.setCanModify(!Boolean.TRUE.equals(request.getPreventModify()));
- permissions.setCanModifyAnnotations(
- !Boolean.TRUE.equals(request.getPreventModifyAnnotations()));
- permissions.setCanPrint(!Boolean.TRUE.equals(request.getPreventPrinting()));
- permissions.setCanPrintFaithful(!Boolean.TRUE.equals(request.getPreventPrintingFaithful()));
- return permissions;
- }
-
- /**
- * Restore the source's encryption, including an unknown second password, before returning a
- * processed PDF.
- */
- @Operation(hidden = true)
- @PostMapping(value = "/restore-pdf-protection", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> restore(
- @RequestParam MultipartFile fileInput,
- @RequestParam MultipartFile sourceFile,
- @RequestParam String password)
- throws IOException {
- int sourcePermissions;
- int sourceKeyLength;
- int sourceRevision;
- try (PDDocument source = pdfDocumentFactory.load(sourceFile, password, true)) {
- if (!source.isEncrypted())
- throw new IOException("The protection source is not encrypted");
- if (!source.getSignatureDictionaries().isEmpty())
- throw new IOException("Protection restoration does not support signed source PDFs");
- // Effective owner access is unrestricted even when the encryption dictionary is not.
- sourcePermissions = source.getEncryption().getPermissions();
- sourceKeyLength = source.getEncryption().getLength();
- sourceRevision = source.getEncryption().getRevision();
- }
-
- TempFile output = tempFileManager.createManagedTempFile(".pdf");
- boolean transferred = false;
- try (TempFile input = new TempFile(tempFileManager, ".pdf");
- TempFile source = new TempFile(tempFileManager, ".pdf")) {
- fileInput.transferTo(input.getFile());
- sourceFile.transferTo(source.getFile());
- try {
- PdfSecurity.copyEncryption(
- input.getPath(), output.getPath(), source.getPath(), password);
- } catch (JPDFiumException e) {
- throw new IOException("Unable to restore PDF protection", e);
- }
- try (var stream = Files.newInputStream(output.getPath());
- PDDocument protectedDocument =
- pdfDocumentFactory.load(stream, password, true)) {
- if (!protectedDocument.isEncrypted()
- || protectedDocument.getEncryption().getPermissions() != sourcePermissions
- || protectedDocument.getEncryption().getLength() != sourceKeyLength
- || protectedDocument.getEncryption().getRevision() != sourceRevision)
- throw new IOException("Output protection verification failed");
- }
- var response =
- WebResponseUtils.pdfFileToWebResponse(output, fileInput.getOriginalFilename());
- transferred = true;
- return response;
- } finally {
- if (!transferred) output.close();
- }
- }
-
- /** Creates an explicitly unprotected copy subject to the server's owner-password policy. */
- @Operation(hidden = true)
- @PostMapping(value = "/remove-pdf-protection", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public ResponseEntity<Resource> removeProtection(@ModelAttribute PDFPasswordRequest request)
- throws IOException {
- try (PDDocument document =
- pdfDocumentFactory.load(request.getFileInput(), request.getPassword(), true)) {
- PdfSessionPermissions.requireOwner(
- document, applicationProperties.getSecurity().isHonorOwnerPasswords());
- document.setAllSecurityToBeRemoved(true);
- return WebResponseUtils.pdfDocToWebResponse(
- document, "unprotected.pdf", tempFileManager);
- }
- }
-}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
index 2227803372..07008869c6 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/AddPasswordRequest.java
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
+import lombok.ToString;
import stirling.software.common.model.api.PDFFile;
@@ -16,6 +17,7 @@ public class AddPasswordRequest extends PDFFile {
"The owner password to be added to the PDF file (Restricts what can be done"
+ " with the document once it is opened)",
format = "password")
+ @ToString.Exclude
private String ownerPassword;
@Schema(
@@ -23,8 +25,22 @@ public class AddPasswordRequest extends PDFFile {
"The password to be added to the PDF file (Restricts the opening of the"
+ " document itself.)",
format = "password")
+ @ToString.Exclude
private String password;
+ @Schema(
+ description =
+ "Credential for authenticating an existing protected source, separate from the new passwords. Omit to retain legacy add-password behaviour.",
+ format = "password")
+ @ToString.Exclude
+ private String sourcePassword;
+
+ @Schema(
+ description =
+ "Change permissions while retaining existing passwords and encryption. A supplied ownerPassword replaces the permissions password.",
+ defaultValue = "false")
+ private boolean preserveExisting;
+
@Schema(
description = "The length of the encryption key",
type = "integer",
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/PDFPasswordRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/PDFPasswordRequest.java
index cea62b079a..fd5bd7377a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/security/PDFPasswordRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/PDFPasswordRequest.java
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
+import lombok.ToString;
import stirling.software.common.model.api.PDFFile;
@@ -15,5 +16,6 @@ public class PDFPasswordRequest extends PDFFile {
description = "The password of the PDF file",
format = "password",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
+ @ToString.Exclude
private String password;
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/security/RemovePasswordRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/security/RemovePasswordRequest.java
new file mode 100644
index 0000000000..c85f86d62b
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/security/RemovePasswordRequest.java
@@ -0,0 +1,47 @@
+package stirling.software.SPDF.model.api.security;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+/**
+ * Omitting all selective fields preserves password-only behaviour. Supplying any selective field,
+ * even empty, makes nonempty password/ownerPassword select removal; blank fields retain that role.
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class RemovePasswordRequest extends PDFPasswordRequest {
+ @Schema(
+ description =
+ "Explicitly remove all passwords and restrictions, subject to the server owner-password policy. The password or sourcePassword authenticates the source; selective removal fields do not apply.",
+ defaultValue = "false")
+ private boolean removeAll;
+
+ @Schema(
+ description =
+ "Permissions password to remove. Supplying this field enables selective removal;"
+ + " leave blank to retain the permissions password.",
+ format = "password")
+ @ToString.Exclude
+ private String ownerPassword;
+
+ @Schema(
+ description =
+ "Credential for opening the source, without selecting it for removal. Supplying"
+ + " this field enables selective removal; password then selects the"
+ + " opening password to remove and ownerPassword selects the permissions"
+ + " password to remove. Blank selection fields keep their passwords.",
+ format = "password")
+ @ToString.Exclude
+ private String sourcePassword;
+
+ @Schema(
+ description =
+ "Opening password to retain when removing only the permissions password."
+ + " Supplying this field enables selective removal.",
+ format = "password")
+ @ToString.Exclude
+ private String retainedOpeningPassword;
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfSessionPermissions.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfSessionPermissions.java
index 8b329ac994..a44c13f35f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/PdfSessionPermissions.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/PdfSessionPermissions.java
@@ -1,12 +1,7 @@
package stirling.software.SPDF.service;
import java.io.IOException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.HexFormat;
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;
import org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler;
@@ -17,29 +12,6 @@ import org.springframework.web.server.ResponseStatusException;
public final class PdfSessionPermissions {
private PdfSessionPermissions() {}
- /** Identifies the stored credential entries without returning them or either password. */
- public static String credentialFingerprint(PDDocument document) throws IOException {
- if (!document.isEncrypted()) return "";
- try {
- var digest = MessageDigest.getInstance("SHA-256");
- var encryption = document.getEncryption().getCOSObject();
- for (var key : new COSName[] {COSName.O, COSName.U, COSName.OE, COSName.UE}) {
- if (encryption.getDictionaryObject(key) instanceof COSString value) {
- byte[] bytes = value.getBytes();
- digest.update((byte) bytes.length);
- digest.update(bytes);
- } else digest.update((byte) 0);
- }
- var ids = document.getDocument().getDocumentID();
- if (ids != null && ids.size() > 0 && ids.getObject(0) instanceof COSString id) {
- digest.update(id.getBytes());
- }
- return HexFormat.of().formatHex(digest.digest());
- } catch (NoSuchAlgorithmException e) {
- throw new IOException("PDF credential verification is unavailable", e);
- }
- }
-
/** Requires a freshly loaded document whose access permission has not been mutated. */
public static boolean isOwnerAuthenticated(PDDocument document) throws IOException {
if (!document.isEncrypted()) return false;
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java
index 3c18d0863d..f81c6cbca7 100644
--- a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java
@@ -37,6 +37,15 @@ import stirling.software.common.service.ToolIOParameterDefaults;
*/
class ToolIODeclarationCoverageTest {
+ @Test
+ void selectiveRemovalMayRetainAnOpeningPassword() {
+ var removal = spec("/api/v1/security/remove-password");
+ assertEquals(
+ ToolFormat.ANY,
+ removal.resolveOutput(Map.of("password", "", "ownerPassword", "owner")).format());
+ assertEquals(ToolFormat.PDF, removal.resolveOutput(Map.of("password", "reader")).format());
+ }
+
/** The namespaces whose endpoints act on documents. */
private static final List<String> TOOL_NAMESPACES =
List.of(
@@ -64,14 +73,8 @@ class ToolIODeclarationCoverageTest {
"/api/v1/general/pdf-text-editor",
// Interactive credential helpers, hidden from pipeline discovery; restoration
// requires the original protected document as well as the working result.
- "/api/v1/security/inspect-pdf-security",
"/api/v1/security/restore-pdf-protection",
"/api/v1/security/prepare-pdf-session",
- "/api/v1/security/remove-pdf-opening-password",
- "/api/v1/security/remove-pdf-passwords",
- "/api/v1/security/remove-pdf-protection",
- "/api/v1/security/set-pdf-protection",
- "/api/v1/security/change-pdf-permissions",
// Signing sessions, certificate checks and hardware token enumeration; the
// signing tool itself is /api/v1/security/cert-sign, which is declared.
"/api/v1/security/cert-sign/sessions",
@@ -279,23 +282,17 @@ class ToolIODeclarationCoverageTest {
}
@Test
- void onlyRemovePasswordAcceptsAnEncryptedDocument() {
- assertTrue(
- spec("/api/v1/security/remove-password").acceptsFormat(ToolFormat.PDF_ENCRYPTED));
+ void passwordToolsAcceptEncryptedSources() {
List<String> accepting =
DECLARED.entrySet().stream()
.filter(e -> e.getValue().acceptsFormat(ToolFormat.PDF_ENCRYPTED))
.map(Map.Entry::getKey)
- .filter(path -> !path.equals("/api/v1/security/remove-password"))
.filter(path -> !spec(path).accepts().contains(ToolFormat.ANY))
.sorted()
.toList();
- assertTrue(
- accepting.isEmpty(),
- () ->
- "Only remove-password should accept an encrypted PDF. If one of these"
- + " genuinely handles encryption, say so in its @ToolIO:\n "
- + String.join("\n ", accepting));
+ assertEquals(
+ List.of("/api/v1/security/add-password", "/api/v1/security/remove-password"),
+ accepting);
}
private static ToolIOSpec spec(String path) {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordControllerTest.java
index a0427b2a8c..58d28ad35a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordControllerTest.java
@@ -3,9 +3,12 @@ package stirling.software.SPDF.controller.api.security;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -40,10 +43,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.model.api.security.AddPasswordRequest;
-import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
+import stirling.software.SPDF.model.api.security.RemovePasswordRequest;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.PdfMetadataService;
import stirling.software.common.util.TempFile;
@@ -131,7 +136,7 @@ class PasswordControllerTest {
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("password");
@@ -155,7 +160,7 @@ class PasswordControllerTest {
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("pass");
@@ -178,7 +183,7 @@ class PasswordControllerTest {
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("wrong");
@@ -198,7 +203,7 @@ class PasswordControllerTest {
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("pass");
@@ -218,7 +223,7 @@ class PasswordControllerTest {
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("");
@@ -236,7 +241,7 @@ class PasswordControllerTest {
new MockMultipartFile(
"fileInput", null, MediaType.APPLICATION_PDF_VALUE, simplePdfBytes);
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile);
request.setPassword("pass");
@@ -259,7 +264,8 @@ class PasswordControllerTest {
controller =
new PasswordController(
new CustomPDFDocumentFactory(mock(PdfMetadataService.class)),
- tempFileManager);
+ tempFileManager,
+ new stirling.software.common.model.ApplicationProperties());
}
@ParameterizedTest
@@ -328,7 +334,7 @@ class PasswordControllerTest {
}
private byte[] removePassword(byte[] pdfBytes, String password) throws IOException {
- PDFPasswordRequest request = new PDFPasswordRequest();
+ RemovePasswordRequest request = new RemovePasswordRequest();
request.setFileInput(pdfFile(pdfBytes));
request.setPassword(password);
return drainBody(controller.removePassword(request));
@@ -355,6 +361,210 @@ class PasswordControllerTest {
}
}
+ @Nested
+ class MultipartRemovalContract {
+ private MockMvc mvc;
+ private byte[] protectedBytes;
+
+ @BeforeEach
+ void useRealController() throws Exception {
+ var controller =
+ new PasswordController(
+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class)),
+ tempFileManager,
+ new stirling.software.common.model.ApplicationProperties());
+ mvc = MockMvcBuilders.standaloneSetup(controller).build();
+ try (var document = Loader.loadPDF(simplePdfBytes);
+ var output = new ByteArrayOutputStream()) {
+ var permissions = new AccessPermission();
+ permissions.setCanPrint(false);
+ var protection = new StandardProtectionPolicy("owner", "reader", permissions);
+ protection.setEncryptionKeyLength(256);
+ document.protect(protection);
+ document.save(output);
+ protectedBytes = output.toByteArray();
+ }
+ }
+
+ @Test
+ void passwordOnlyRetainsLegacyBehaviour() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("password", "reader"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ try (var document = Loader.loadPDF(output)) {
+ assertTrue(document.isEncrypted());
+ assertFalse(document.getCurrentAccessPermission().canPrint());
+ }
+ }
+
+ @Test
+ void sourceCredentialRemovesOpeningPasswordAndRetainsOwner() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("password", "reader")
+ .param("sourcePassword", "owner"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ try (var reader = Loader.loadPDF(output);
+ var owner = Loader.loadPDF(output, "owner")) {
+ assertFalse(reader.getCurrentAccessPermission().canPrint());
+ assertFalse(owner.getCurrentAccessPermission().isReadOnly());
+ }
+ }
+
+ @Test
+ void ownerSelectionRetainsOpeningPassword() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("ownerPassword", "owner")
+ .param("retainedOpeningPassword", "reader"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ assertThrows(
+ org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException.class,
+ () -> Loader.loadPDF(output));
+ try (var reader = Loader.loadPDF(output, "reader")) {
+ assertTrue(reader.getCurrentAccessPermission().canPrint());
+ }
+ }
+
+ @Test
+ void emptySelectiveFieldsCannotFallBackToLegacyRemoval() throws Exception {
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("password", "")
+ .param("ownerPassword", "")
+ .param("sourcePassword", "owner"))
+ .andExpect(status().isBadRequest());
+ }
+
+ @Test
+ void explicitRemovalClearsAllProtectionUsingSourceCredential() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("sourcePassword", "owner")
+ .param("removeAll", "true"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ try (var result = Loader.loadPDF(output)) {
+ assertFalse(result.isEncrypted());
+ }
+ }
+
+ @Test
+ void explicitRemovalHonorsOwnerPasswordPolicy() throws Exception {
+ mvc.perform(
+ multipart("/api/v1/security/remove-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("password", "reader")
+ .param("removeAll", "true"))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ void permissionUpdateRetainsBothCredentialsThroughAddPassword() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/add-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("sourcePassword", "owner")
+ .param("preserveExisting", "true")
+ .param("preventModify", "true"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ try (var reader = Loader.loadPDF(output, "reader");
+ var owner = Loader.loadPDF(output, "owner")) {
+ assertFalse(reader.getCurrentAccessPermission().canModify());
+ assertTrue(owner.getCurrentAccessPermission().isOwnerPermission());
+ }
+ }
+
+ @Test
+ void replacementAuthenticatesSourceSeparatelyFromNewPasswords() throws Exception {
+ byte[] output =
+ mvc.perform(
+ multipart("/api/v1/security/add-password")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "test.pdf",
+ "application/pdf",
+ protectedBytes))
+ .param("sourcePassword", "owner")
+ .param("password", "new-reader")
+ .param("ownerPassword", "new-owner")
+ .param("preventPrinting", "true"))
+ .andExpect(status().isOk())
+ .andReturn()
+ .getResponse()
+ .getContentAsByteArray();
+ try (var reader = Loader.loadPDF(output, "new-reader");
+ var owner = Loader.loadPDF(output, "new-owner")) {
+ assertFalse(reader.getCurrentAccessPermission().canPrint());
+ assertTrue(owner.getCurrentAccessPermission().isOwnerPermission());
+ }
+ assertThrows(
+ org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException.class,
+ () -> Loader.loadPDF(output, "reader"));
+ }
+ }
+
@Nested
@DisplayName("Add Password Tests")
class AddPasswordTests {
@@ -375,7 +585,7 @@ class PasswordControllerTest {
request.setPassword("user123");
request.setKeyLength(128);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -400,7 +610,7 @@ class PasswordControllerTest {
request.setPassword("");
request.setKeyLength(256);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -426,7 +636,7 @@ class PasswordControllerTest {
request.setPreventPrinting(true);
request.setPreventModify(true);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -449,7 +659,7 @@ class PasswordControllerTest {
request.setPassword(null);
request.setKeyLength(128);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -480,7 +690,7 @@ class PasswordControllerTest {
request.setPreventPrinting(true);
request.setPreventPrintingFaithful(true);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -505,7 +715,7 @@ class PasswordControllerTest {
request.setKeyLength(128);
// All permission flags left null
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -528,7 +738,7 @@ class PasswordControllerTest {
request.setPassword("user");
request.setKeyLength(40);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
@@ -551,7 +761,7 @@ class PasswordControllerTest {
request.setPassword("user123");
request.setKeyLength(128);
- when(pdfDocumentFactory.load(any(MultipartFile.class)))
+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(""), eq(true)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = passwordController.addPassword(request);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordProtectionControllerTest.java
similarity index 68%
rename from app/core/src/test/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityControllerTest.java
rename to app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordProtectionControllerTest.java
index f7381c3538..243d94ec24 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PasswordProtectionControllerTest.java
@@ -22,12 +22,17 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import stirling.software.SPDF.model.api.security.AddPasswordRequest;
import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
+import stirling.software.SPDF.model.api.security.RemovePasswordRequest;
+import stirling.software.SPDF.service.PdfPasswordRoles;
+import stirling.software.SPDF.service.PdfSessionPermissions;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
@@ -35,11 +40,11 @@ import stirling.software.common.util.TempFileManager;
import stirling.software.jpdfium.doc.PdfSecurity;
import stirling.software.jpdfium.exception.JPDFiumException;
-class PdfSessionSecurityControllerTest {
+class PasswordProtectionControllerTest {
private static final String USER = " reader password ";
private static final String OWNER = " owner password ";
@TempDir Path directory;
- private PdfSessionSecurityController controller;
+ private PasswordController controller;
private CustomPDFDocumentFactory factory;
private ApplicationProperties properties;
@@ -58,6 +63,12 @@ class PdfSessionSecurityControllerTest {
Loader.loadPDF(
inv.<InputStream>getArgument(0).readAllBytes(),
inv.getArgument(1)));
+ when(factory.load(any(MultipartFile.class), anyString()))
+ .thenAnswer(
+ inv ->
+ Loader.loadPDF(
+ inv.<MultipartFile>getArgument(0).getBytes(),
+ inv.getArgument(1)));
var tempFiles = mock(TempFileManager.class);
when(tempFiles.createTempFile(anyString()))
.thenAnswer(
@@ -74,7 +85,44 @@ class PdfSessionSecurityControllerTest {
.when(tempFiles)
.deleteTempFile(any(java.io.File.class));
properties = new ApplicationProperties();
- controller = new PdfSessionSecurityController(factory, tempFiles, properties);
+ controller = new PasswordController(factory, tempFiles, properties);
+ }
+
+ private ResponseEntity<Resource> changePermissions(AddPasswordRequest request, String password)
+ throws IOException {
+ request.setSourcePassword(password);
+ request.setPreserveExisting(true);
+ return controller.addPassword(request);
+ }
+
+ private ResponseEntity<Resource> setProtection(AddPasswordRequest request, String password)
+ throws IOException {
+ request.setSourcePassword(password);
+ request.setPreserveExisting(false);
+ return controller.addPassword(request);
+ }
+
+ private ResponseEntity<Resource> removeProtection(PDFPasswordRequest input) throws IOException {
+ var request = new RemovePasswordRequest();
+ request.setFileInput(input.getFileInput());
+ request.setPassword(input.getPassword());
+ request.setRemoveAll(true);
+ return controller.removePassword(request);
+ }
+
+ private ResponseEntity<Resource> removePasswords(
+ PDFPasswordRequest input,
+ String ownerPassword,
+ String sourcePassword,
+ String retainedOpeningPassword)
+ throws IOException {
+ var request = new RemovePasswordRequest();
+ request.setFileInput(input.getFileInput());
+ request.setPassword(input.getPassword());
+ request.setOwnerPassword(ownerPassword);
+ request.setSourcePassword(sourcePassword);
+ request.setRetainedOpeningPassword(retainedOpeningPassword);
+ return controller.removePassword(request);
}
private byte[] pdf(boolean encrypted, int bits) throws IOException {
@@ -106,21 +154,56 @@ class PdfSessionSecurityControllerTest {
}
@Test
- void honorsOwnerPasswordsByDefaultAndReportsPolicyWithoutChangingAuthentication()
- throws Exception {
+ void legacyAddPasswordRequiresOwnerForRestrictedSources() throws Exception {
+ var request = new AddPasswordRequest();
+ request.setFileInput(upload(pdf(true, 256, true, "", OWNER, 1)));
+ request.setPassword("replacement-reader");
+ request.setOwnerPassword("replacement-owner");
+ request.setKeyLength(256);
+
+ var denied =
+ assertThrows(ResponseStatusException.class, () -> controller.addPassword(request));
+ assertEquals(403, denied.getStatusCode().value());
+
+ request.setSourcePassword("incorrect");
+ assertThrows(InvalidPasswordException.class, () -> controller.addPassword(request));
+
+ request.setSourcePassword(OWNER);
+ try (var body = controller.addPassword(request).getBody().getInputStream();
+ var output = Loader.loadPDF(body.readAllBytes(), "replacement-reader")) {
+ assertTrue(output.isEncrypted());
+ assertTrue(output.getCurrentAccessPermission().canExtractContent());
+ }
+ }
+
+ @Test
+ void legacyAddPasswordRespectsDisabledOwnerPolicy() throws Exception {
+ properties.getSecurity().setHonorOwnerPasswords(false);
+ var request = new AddPasswordRequest();
+ request.setFileInput(upload(pdf(true, 256, true, "", OWNER, 1)));
+ request.setPassword("replacement-reader");
+ request.setOwnerPassword("replacement-owner");
+ request.setKeyLength(256);
+
+ try (var body = controller.addPassword(request).getBody().getInputStream();
+ var output = Loader.loadPDF(body.readAllBytes(), "replacement-reader")) {
+ assertTrue(output.isEncrypted());
+ assertTrue(output.getCurrentAccessPermission().canExtractContent());
+ }
+ }
+
+ @Test
+ void honorsOwnerPasswordsByDefaultAndAllowsConfiguredBypass() throws Exception {
var original = pdf(true, 256);
- var info = controller.inspect(request(original, USER));
- assertTrue(info.honorOwnerPasswords());
- assertFalse(info.ownerAuthenticated());
+ assertTrue(properties.getSecurity().isHonorOwnerPasswords());
assertThrows(
- ResponseStatusException.class,
- () -> controller.removeProtection(request(original, USER)));
+ ResponseStatusException.class, () -> removeProtection(request(original, USER)));
properties.getSecurity().setHonorOwnerPasswords(false);
- var bypass = controller.inspect(request(original, USER));
- assertFalse(bypass.honorOwnerPasswords());
- assertFalse(bypass.ownerAuthenticated());
- assertEquals(info.permissions(), bypass.permissions());
- assertEquals(info.credentialFingerprint(), bypass.credentialFingerprint());
+ try (var stream = removeProtection(request(original, USER)).getBody().getInputStream();
+ var output = Loader.loadPDF(stream.readAllBytes())) {
+ assertFalse(output.isEncrypted());
+ }
+ assertFalse(inspect(request(original, USER)).ownerAuthenticated());
}
@ParameterizedTest
@@ -128,16 +211,15 @@ class PdfSessionSecurityControllerTest {
void bypassesRestrictionsButStillRequiresOpeningPassword(int bits) throws Exception {
properties.getSecurity().setHonorOwnerPasswords(false);
var original = pdf(true, bits);
- assertThrows(
- InvalidPasswordException.class, () -> controller.inspect(request(original, "")));
+ assertThrows(InvalidPasswordException.class, () -> inspect(request(original, "")));
assertThrows(
InvalidPasswordException.class,
() ->
controller.prepare(
request(original, "wrong"), "/api/v1/general/split-pages"));
assertThrows(
- InvalidPasswordException.class,
- () -> controller.removeProtection(request(original, "")));
+ stirling.software.common.util.ExceptionUtils.PdfPasswordException.class,
+ () -> removeProtection(request(original, "")));
try (var stream =
controller
.prepare(request(original, USER), "/api/v1/general/split-pages")
@@ -146,15 +228,11 @@ class PdfSessionSecurityControllerTest {
var working = Loader.loadPDF(stream.readAllBytes())) {
assertFalse(working.isEncrypted());
}
- try (var stream =
- controller
- .removeProtection(request(original, USER))
- .getBody()
- .getInputStream();
+ try (var stream = removeProtection(request(original, USER)).getBody().getInputStream();
var copy = Loader.loadPDF(stream.readAllBytes())) {
assertFalse(copy.isEncrypted());
}
- assertTrue(controller.inspect(request(original, USER)).encrypted());
+ assertTrue(inspect(request(original, USER)).encrypted());
}
@Test
@@ -165,32 +243,43 @@ class PdfSessionSecurityControllerTest {
update.setFileInput(upload(original));
update.setPassword(USER);
update.setPreventModify(true);
- try (var stream = controller.changePermissions(update, USER).getBody().getInputStream()) {
+ try (var stream = changePermissions(update, USER).getBody().getInputStream()) {
byte[] bytes = stream.readAllBytes();
- assertFalse(controller.inspect(request(bytes, USER)).ownerAuthenticated());
- assertTrue(controller.inspect(request(bytes, OWNER)).ownerAuthenticated());
+ assertFalse(inspect(request(bytes, USER)).ownerAuthenticated());
+ assertTrue(inspect(request(bytes, OWNER)).ownerAuthenticated());
}
update.setOwnerPassword("replacement-owner");
- try (var stream = controller.changePermissions(update, USER).getBody().getInputStream()) {
+ try (var stream = changePermissions(update, USER).getBody().getInputStream()) {
byte[] bytes = stream.readAllBytes();
- assertFalse(controller.inspect(request(bytes, USER)).canModify());
- assertFalse(controller.inspect(request(bytes, USER)).ownerAuthenticated());
- assertTrue(
- controller.inspect(request(bytes, "replacement-owner")).ownerAuthenticated());
- }
- assertThrows(
- ResponseStatusException.class,
- () -> controller.removeOpeningPassword(request(original, USER), ""));
- try (var stream =
- controller
- .removeOpeningPassword(request(original, USER), "replacement-owner")
- .getBody()
- .getInputStream()) {
- byte[] bytes = stream.readAllBytes();
- assertFalse(controller.inspect(request(bytes, "")).requiresOpeningPassword());
- assertFalse(controller.inspect(request(bytes, "")).canPrint());
- assertTrue(
- controller.inspect(request(bytes, "replacement-owner")).ownerAuthenticated());
+ assertFalse(inspect(request(bytes, USER)).canModify());
+ assertFalse(inspect(request(bytes, USER)).ownerAuthenticated());
+ assertTrue(inspect(request(bytes, "replacement-owner")).ownerAuthenticated());
+ }
+ }
+
+ private record Protection(
+ boolean encrypted,
+ boolean ownerAuthenticated,
+ boolean canModify,
+ boolean canAssemble,
+ boolean canExtract,
+ boolean canPrint,
+ boolean requiresOpeningPassword,
+ boolean hasOwnerPassword) {}
+
+ private Protection inspect(PDFPasswordRequest request) throws IOException {
+ String password = request.getPassword() == null ? "" : request.getPassword();
+ try (var document = Loader.loadPDF(request.getFileInput().getBytes(), password)) {
+ var permission = document.getCurrentAccessPermission();
+ return new Protection(
+ document.isEncrypted(),
+ PdfSessionPermissions.isOwnerAuthenticated(document),
+ permission.canModify(),
+ permission.canAssembleDocument(),
+ permission.canExtractContent(),
+ permission.canPrint(),
+ document.isEncrypted() && !PdfPasswordRoles.isOpeningPassword(document, ""),
+ PdfPasswordRoles.hasSeparateOwnerPassword(document, password));
}
}
@@ -219,34 +308,18 @@ class PdfSessionSecurityControllerTest {
return request;
}
- @Test
- void distinguishesOpeningPasswordsFromPermissionsPasswords() throws Exception {
- assertTrue(controller.inspect(request(pdf(true, 256), OWNER)).requiresOpeningPassword());
- var ownerOnly = protectedPdf("", OWNER, 256, new AccessPermission());
- assertFalse(controller.inspect(request(ownerOnly, OWNER)).requiresOpeningPassword());
- assertFalse(controller.inspect(request(pdf(false, 256), "")).requiresOpeningPassword());
- assertFalse(controller.inspect(request(pdf(false, 256), "")).hasOwnerPassword());
- assertTrue(controller.inspect(request(pdf(true, 256), USER)).openingAuthenticated());
- assertFalse(controller.inspect(request(pdf(true, 256), OWNER)).openingAuthenticated());
- assertTrue(controller.inspect(request(pdf(true, 256), USER)).hasOwnerPassword());
- assertFalse(
- controller
- .inspect(request(protectedPdf(USER, "", 256, new AccessPermission()), USER))
- .hasOwnerPassword());
- }
-
@Test
void changingPermissionsRetainsTheVerifiedOwnerForAnOwnerOnlyPdf() throws Exception {
var update = new AddPasswordRequest();
update.setFileInput(upload(protectedPdf("", OWNER, 256, new AccessPermission())));
update.setPreventModify(true);
- try (var stream = controller.changePermissions(update, OWNER).getBody().getInputStream()) {
+ try (var stream = changePermissions(update, OWNER).getBody().getInputStream()) {
var bytes = stream.readAllBytes();
- var reader = controller.inspect(request(bytes, ""));
+ var reader = inspect(request(bytes, ""));
assertTrue(reader.encrypted());
assertFalse(reader.canModify());
assertFalse(reader.requiresOpeningPassword());
- assertTrue(controller.inspect(request(bytes, OWNER)).ownerAuthenticated());
+ assertTrue(inspect(request(bytes, OWNER)).ownerAuthenticated());
}
}
@@ -257,9 +330,8 @@ class PdfSessionSecurityControllerTest {
update.setFileInput(upload(pdf(true, bits)));
update.setPreventModify(true);
update.setPassword("must-not-replace-the-opening-password");
- assertThrows(
- ResponseStatusException.class, () -> controller.changePermissions(update, USER));
- try (var stream = controller.changePermissions(update, OWNER).getBody().getInputStream()) {
+ assertThrows(ResponseStatusException.class, () -> changePermissions(update, USER));
+ try (var stream = changePermissions(update, OWNER).getBody().getInputStream()) {
var bytes = stream.readAllBytes();
assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(bytes));
try (var output = Loader.loadPDF(bytes, USER)) {
@@ -267,8 +339,8 @@ class PdfSessionSecurityControllerTest {
bits == 40 ? 1 : bits == 128 ? 4 : 5, output.getEncryption().getVersion());
assertEquals(bits, output.getEncryption().getLength());
}
- assertFalse(controller.inspect(request(bytes, USER)).canModify());
- assertTrue(controller.inspect(request(bytes, OWNER)).ownerAuthenticated());
+ assertFalse(inspect(request(bytes, USER)).canModify());
+ assertTrue(inspect(request(bytes, OWNER)).ownerAuthenticated());
}
}
@@ -280,43 +352,40 @@ class PdfSessionSecurityControllerTest {
byte[] original = pdf(true, bits);
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, ""), "", OWNER, USER));
+ () -> removePasswords(request(original, ""), "", OWNER, USER));
try (var stream =
- controller
- .removePasswords(request(original, USER), "", OWNER, USER)
+ removePasswords(request(original, USER), "", OWNER, USER)
.getBody()
.getInputStream()) {
byte[] result = stream.readAllBytes();
- var reader = controller.inspect(request(result, ""));
+ var reader = inspect(request(result, ""));
assertFalse(reader.requiresOpeningPassword());
assertTrue(reader.hasOwnerPassword());
assertFalse(reader.ownerAuthenticated());
assertFalse(reader.canPrint());
- assertTrue(controller.inspect(request(result, OWNER)).ownerAuthenticated());
+ assertTrue(inspect(request(result, OWNER)).ownerAuthenticated());
}
try (var stream =
- controller
- .removePasswords(request(original, ""), OWNER, USER, USER)
+ removePasswords(request(original, ""), OWNER, USER, USER)
.getBody()
.getInputStream()) {
byte[] result = stream.readAllBytes();
assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(result));
assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(result, OWNER));
- var reader = controller.inspect(request(result, USER));
+ var reader = inspect(request(result, USER));
assertTrue(reader.requiresOpeningPassword());
assertFalse(reader.hasOwnerPassword());
assertTrue(reader.canPrint());
}
try (var stream =
- controller
- .removePasswords(request(original, USER), OWNER, USER, USER)
+ removePasswords(request(original, USER), OWNER, USER, USER)
.getBody()
.getInputStream();
var result = Loader.loadPDF(stream.readAllBytes())) {
assertFalse(result.isEncrypted());
}
- assertTrue(controller.inspect(request(original, USER)).requiresOpeningPassword());
- assertTrue(controller.inspect(request(original, OWNER)).hasOwnerPassword());
+ assertTrue(inspect(request(original, USER)).requiresOpeningPassword());
+ assertTrue(inspect(request(original, OWNER)).hasOwnerPassword());
}
@ParameterizedTest
@@ -327,19 +396,19 @@ class PdfSessionSecurityControllerTest {
byte[] original = pdf(true, 256);
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, OWNER), OWNER, USER, USER));
+ () -> removePasswords(request(original, OWNER), OWNER, USER, USER));
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, USER), USER, USER, USER));
+ () -> removePasswords(request(original, USER), USER, USER, USER));
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, USER), "", USER, USER));
+ () -> removePasswords(request(original, USER), "", USER, USER));
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, ""), OWNER, OWNER, ""));
+ () -> removePasswords(request(original, ""), OWNER, OWNER, ""));
assertThrows(
ResponseStatusException.class,
- () -> controller.removePasswords(request(original, "wrong"), OWNER, USER, USER));
+ () -> removePasswords(request(original, "wrong"), OWNER, USER, USER));
}
@ParameterizedTest
@@ -347,8 +416,7 @@ class PdfSessionSecurityControllerTest {
void removalSupportsFilesWithOnlyOnePassword(int bits) throws Exception {
byte[] openingOnly = protectedPdf(USER, "", bits, new AccessPermission());
try (var stream =
- controller
- .removePasswords(request(openingOnly, USER), "", USER, USER)
+ removePasswords(request(openingOnly, USER), "", USER, USER)
.getBody()
.getInputStream();
var result = Loader.loadPDF(stream.readAllBytes())) {
@@ -356,8 +424,7 @@ class PdfSessionSecurityControllerTest {
}
byte[] ownerOnly = protectedPdf("", OWNER, bits, new AccessPermission());
try (var stream =
- controller
- .removePasswords(request(ownerOnly, ""), OWNER, "", "")
+ removePasswords(request(ownerOnly, ""), OWNER, "", "")
.getBody()
.getInputStream();
var result = Loader.loadPDF(stream.readAllBytes())) {
@@ -377,8 +444,7 @@ class PdfSessionSecurityControllerTest {
update.setFileInput(upload(original));
update.setPreventModify(true);
for (String credential : new String[] {USER, OWNER}) {
- try (var stream =
- controller.changePermissions(update, credential).getBody().getInputStream()) {
+ try (var stream = changePermissions(update, credential).getBody().getInputStream()) {
byte[] result = stream.readAllBytes();
try (var reader = Loader.loadPDF(result, USER);
var owner = Loader.loadPDF(result, OWNER)) {
@@ -387,8 +453,8 @@ class PdfSessionSecurityControllerTest {
assertFalse(reader.getCurrentAccessPermission().canModify());
assertTrue(reader.getCurrentAccessPermission().canPrint());
}
- assertFalse(controller.inspect(request(result, USER)).ownerAuthenticated());
- assertTrue(controller.inspect(request(result, OWNER)).ownerAuthenticated());
+ assertFalse(inspect(request(result, USER)).ownerAuthenticated());
+ assertTrue(inspect(request(result, OWNER)).ownerAuthenticated());
}
}
}
@@ -397,29 +463,11 @@ class PdfSessionSecurityControllerTest {
@CsvSource({"40", "128", "256"})
void unrestrictedUserPasswordDoesNotAuthenticateTheOwner(int bits) throws Exception {
byte[] original = protectedPdf(USER, OWNER, bits, new AccessPermission());
- assertFalse(controller.inspect(request(original, USER)).ownerAuthenticated());
- assertTrue(controller.inspect(request(original, OWNER)).ownerAuthenticated());
+ assertFalse(inspect(request(original, USER)).ownerAuthenticated());
+ assertTrue(inspect(request(original, OWNER)).ownerAuthenticated());
assertThrows(
ResponseStatusException.class,
- () -> controller.removeOpeningPassword(request(original, USER), ""));
- }
-
- @ParameterizedTest
- @CsvSource({"40", "128", "256"})
- void omittedOpeningPasswordCanInspectOwnerOnlyDocuments(int bits) throws Exception {
- var info =
- controller.inspect(
- request(protectedPdf("", OWNER, bits, new AccessPermission()), null));
- assertFalse(info.requiresOpeningPassword());
- assertFalse(info.ownerAuthenticated());
- assertTrue(info.hasOwnerPassword());
- }
-
- @Test
- void unicodeOwnerCredentialsUseTheLibrarysAuthenticationResult() throws Exception {
- byte[] original = protectedPdf("reader", "秘密 café", 256, new AccessPermission());
- assertTrue(controller.inspect(request(original, "秘密 café")).ownerAuthenticated());
- assertFalse(controller.inspect(request(original, "reader")).ownerAuthenticated());
+ () -> removePasswords(request(original, USER), "", USER, ""));
}
@ParameterizedTest
@@ -429,7 +477,7 @@ class PdfSessionSecurityControllerTest {
permissions.setCanAssembleDocument(false);
permissions.setCanExtractContent(false);
byte[] original = protectedPdf("", OWNER, bits, permissions);
- var info = controller.inspect(request(original, ""));
+ var info = inspect(request(original, ""));
assertTrue(info.encrypted());
assertFalse(info.ownerAuthenticated());
assertFalse(info.canAssemble());
@@ -445,7 +493,7 @@ class PdfSessionSecurityControllerTest {
var working = Loader.loadPDF(stream.readAllBytes())) {
assertFalse(working.isEncrypted());
}
- assertTrue(controller.inspect(request(original, "")).encrypted());
+ assertTrue(inspect(request(original, "")).encrypted());
}
@Test
@@ -473,53 +521,16 @@ class PdfSessionSecurityControllerTest {
}
}
- @Test
- void removingTheOpeningPasswordRetainsKnownOwnerAccessAndStoredRestrictions() throws Exception {
- byte[] original = pdf(true, 256);
- try (var stream =
- controller
- .removeOpeningPassword(request(original, OWNER), "")
- .getBody()
- .getInputStream()) {
- byte[] result = stream.readAllBytes();
- var viewer = controller.inspect(request(result, ""));
- assertTrue(viewer.encrypted());
- assertFalse(viewer.ownerAuthenticated());
- assertFalse(viewer.canPrint());
- assertFalse(viewer.canExtract());
- assertTrue(controller.inspect(request(result, OWNER)).ownerAuthenticated());
- }
- }
-
@Test
void removingAllProtectionRequiresOwnerAndLeavesTheOriginalIntact() throws Exception {
byte[] original = pdf(true, 256);
assertThrows(
- ResponseStatusException.class,
- () -> controller.removeProtection(request(original, USER)));
- try (var stream =
- controller
- .removeProtection(request(original, OWNER))
- .getBody()
- .getInputStream();
+ ResponseStatusException.class, () -> removeProtection(request(original, USER)));
+ try (var stream = removeProtection(request(original, OWNER)).getBody().getInputStream();
var result = Loader.loadPDF(stream.readAllBytes())) {
assertFalse(result.isEncrypted());
}
- assertTrue(controller.inspect(request(original, USER)).encrypted());
- }
-
- @Test
- void credentialFingerprintIdentifiesStoredCredentialsRegardlessOfAuthenticationRole()
- throws Exception {
- byte[] original = pdf(true, 256);
- var reader = controller.inspect(request(original, USER));
- var owner = controller.inspect(request(original, OWNER));
- assertEquals(64, reader.credentialFingerprint().length());
- assertEquals(reader.credentialFingerprint(), owner.credentialFingerprint());
- byte[] changed = protectedPdf(USER, "different owner", 256, new AccessPermission());
- assertNotEquals(
- reader.credentialFingerprint(),
- controller.inspect(request(changed, USER)).credentialFingerprint());
+ assertTrue(inspect(request(original, USER)).encrypted());
}
@Test
@@ -529,17 +540,17 @@ class PdfSessionSecurityControllerTest {
change.setOwnerPassword("new-owner");
change.setPassword("new-reader");
change.setPreventPrinting(true);
- assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, USER));
- try (var stream = controller.setProtection(change, OWNER).getBody().getInputStream()) {
+ assertThrows(ResponseStatusException.class, () -> setProtection(change, USER));
+ try (var stream = setProtection(change, OWNER).getBody().getInputStream()) {
byte[] result = stream.readAllBytes();
- assertFalse(controller.inspect(request(result, "new-reader")).canPrint());
- assertTrue(controller.inspect(request(result, "new-owner")).ownerAuthenticated());
+ assertFalse(inspect(request(result, "new-reader")).canPrint());
+ assertTrue(inspect(request(result, "new-owner")).ownerAuthenticated());
assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(result, USER));
}
change.setOwnerPassword("");
- assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, OWNER));
+ assertThrows(ResponseStatusException.class, () -> setProtection(change, OWNER));
change.setOwnerPassword("new-reader");
- assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, OWNER));
+ assertThrows(ResponseStatusException.class, () -> setProtection(change, OWNER));
}
@Test
@@ -550,35 +561,12 @@ class PdfSessionSecurityControllerTest {
change.setPassword("a".repeat(32) + "reader");
change.setOwnerPassword("a".repeat(32) + "owner");
change.setPreventPrinting(true);
- assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, ""));
+ assertThrows(ResponseStatusException.class, () -> setProtection(change, ""));
try (var remaining = Files.list(directory)) {
assertEquals(0, remaining.count());
}
}
- @Test
- void inspectAuthenticatesWithoutModifyingTheOriginal() throws Exception {
- byte[] original = pdf(true, 256);
- var request = new PDFPasswordRequest();
- request.setFileInput(upload(original));
- request.setPassword(USER);
- var info = controller.inspect(request);
- assertTrue(info.encrypted());
- assertFalse(info.ownerAuthenticated());
- assertFalse(info.signed());
- assertEquals(1, info.pageCount());
- assertEquals(0, info.permissions() & 4);
- assertArrayEquals(original, request.getFileInput().getBytes());
- request.setPassword(OWNER);
- var ownerInfo = controller.inspect(request);
- assertTrue(ownerInfo.ownerAuthenticated());
- assertEquals(info.permissions(), ownerInfo.permissions());
- assertEquals(256, ownerInfo.encryptionKeyLength());
- assertEquals(6, ownerInfo.encryptionRevision());
- request.setPassword("incorrect");
- assertThrows(InvalidPasswordException.class, () -> controller.inspect(request));
- }
-
@ParameterizedTest
@CsvSource({
"40,false,false",
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
index e730009970..55639f3863 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/security/AddPasswordRequestTest.java
@@ -71,7 +71,7 @@ class AddPasswordRequestTest {
}
@Nested
- @DisplayName("equals/hashCode/toString")
+ @DisplayName("equals/hashCode")
class EqualityContract {
@Test
@@ -102,13 +102,5 @@ class AddPasswordRequestTest {
AddPasswordRequest a = new AddPasswordRequest();
assertThat(a).isNotEqualTo(null).isNotEqualTo("string");
}
-
- @Test
- @DisplayName("toString contains class name and a field value")
- void toStringContent() {
- AddPasswordRequest a = new AddPasswordRequest();
- a.setPassword("secret");
- assertThat(a.toString()).contains("AddPasswordRequest").contains("secret");
- }
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/security/PDFPasswordRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/security/PDFPasswordRequestTest.java
index f64cc50b5e..b99fca5bbe 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/security/PDFPasswordRequestTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/security/PDFPasswordRequestTest.java
@@ -43,12 +43,4 @@ class PDFPasswordRequestTest {
assertThat(a).isNotEqualTo(b).isNotEqualTo(null).isNotEqualTo("string");
}
-
- @Test
- @DisplayName("toString contains class name and value")
- void toStringContent() {
- PDFPasswordRequest a = new PDFPasswordRequest();
- a.setPassword("secret");
- assertThat(a.toString()).contains("PDFPasswordRequest").contains("secret");
- }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/security/PasswordRequestLoggingTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/security/PasswordRequestLoggingTest.java
new file mode 100644
index 0000000000..77e4238b39
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/security/PasswordRequestLoggingTest.java
@@ -0,0 +1,52 @@
+package stirling.software.SPDF.model.api.security;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class PasswordRequestLoggingTest {
+ @Test
+ void addPasswordRetainsOptionsWithoutLoggingCredentials() {
+ var request = new AddPasswordRequest();
+ request.setPassword("opening-secret");
+ request.setOwnerPassword("owner-secret");
+ request.setSourcePassword("source-secret");
+ request.setKeyLength(256);
+ request.setPreserveExisting(true);
+
+ assertThat(request.toString())
+ .contains("keyLength=256", "preserveExisting=true")
+ .doesNotContain("opening-secret", "owner-secret", "source-secret");
+ assertThat(request.getPassword()).isEqualTo("opening-secret");
+ assertThat(request.getOwnerPassword()).isEqualTo("owner-secret");
+ assertThat(request.getSourcePassword()).isEqualTo("source-secret");
+ }
+
+ @Test
+ void prepareDoesNotLogItsPassword() {
+ var request = new PDFPasswordRequest();
+ request.setPassword("prepare-secret");
+
+ assertThat(request.toString()).doesNotContain("prepare-secret");
+ assertThat(request.getPassword()).isEqualTo("prepare-secret");
+ }
+
+ @Test
+ void removePasswordDoesNotLogInheritedOrSelectiveCredentials() {
+ var request = new RemovePasswordRequest();
+ request.setPassword("opening-secret");
+ request.setOwnerPassword("owner-secret");
+ request.setSourcePassword("source-secret");
+ request.setRetainedOpeningPassword("retained-secret");
+ request.setRemoveAll(true);
+
+ assertThat(request.toString())
+ .contains("removeAll=true")
+ .doesNotContain(
+ "opening-secret", "owner-secret", "source-secret", "retained-secret");
+ assertThat(request.getPassword()).isEqualTo("opening-secret");
+ assertThat(request.getOwnerPassword()).isEqualTo("owner-secret");
+ assertThat(request.getSourcePassword()).isEqualTo("source-secret");
+ assertThat(request.getRetainedOpeningPassword()).isEqualTo("retained-secret");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java
index 03c349174d..4e4d84ef66 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AuditService.java
@@ -48,6 +48,7 @@ import stirling.software.proprietary.audit.Audited;
import stirling.software.proprietary.config.AuditConfigurationProperties;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.service.JwtServiceInterface;
+import stirling.software.proprietary.util.SecretMasker;
/**
* Service for audit event creation, data collection, and persistence. Combines persistence logic
@@ -546,8 +547,11 @@ public class AuditService {
.forEach(
i -> {
if (vals[i] != null) {
- // Convert objects to safe string representation
- data.put("arg_" + names[i], safeToString(vals[i], 500));
+ data.put(
+ "arg_" + names[i],
+ safeToString(
+ SecretMasker.maskValue(names[i], vals[i]),
+ 500));
} else {
data.put("arg_" + names[i], null);
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/util/SecretMasker.java b/app/proprietary/src/main/java/stirling/software/proprietary/util/SecretMasker.java
index f7ce2569f2..1be2700fdc 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/util/SecretMasker.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/util/SecretMasker.java
@@ -20,9 +20,9 @@ public final class SecretMasker {
private static final Pattern SENSITIVE =
RegexPatternUtils.getInstance()
.getPattern(
- // secret[_-]?access[_-]?key precedes plain secret so camelCase keys
- // like secretAccessKey (no word boundary after "secret") still match.
- "(?i)\\b(password|token|secret[_-]?access[_-]?key|signing[_-]?secret|secret|api[_-]?key|authorization|auth|jwt|cred|cert)\\b");
+ // Password names also occur inside camelCase fields and arg_ audit
+ // keys.
+ "(?i)password|\\b(token|secret[_-]?access[_-]?key|signing[_-]?secret|secret|api[_-]?key|authorization|auth|jwt|cred|cert)\\b");
private SecretMasker() {}
@@ -33,7 +33,7 @@ public final class SecretMasker {
.filter(e -> e.getValue() != null)
.collect(
Collectors.toMap(
- Map.Entry::getKey, e -> deepMaskValue(e.getKey(), e.getValue())));
+ Map.Entry::getKey, e -> maskValue(e.getKey(), e.getValue())));
}
private static Object deepMask(Object value) {
@@ -43,7 +43,10 @@ public final class SecretMasker {
.collect(
Collectors.toMap(
Map.Entry::getKey,
- e -> deepMaskValue((String) e.getKey(), e.getValue())));
+ e ->
+ maskValue(
+ e.getKey() instanceof String key ? key : null,
+ e.getValue())));
} else if (value instanceof List<?> list) {
return list.stream().map(SecretMasker::deepMask).toList();
} else {
@@ -51,7 +54,11 @@ public final class SecretMasker {
}
}
- private static Object deepMaskValue(String key, Object value) {
+ /**
+ * Redacts named secrets and nested maps/lists before callers stringify them; input is
+ * unchanged.
+ */
+ public static Object maskValue(String key, Object value) {
if (key != null && SENSITIVE.matcher(key).find()) {
return REDACTED;
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java
index da4a48079a..ab0c1a8d19 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/audit/ControllerAuditAspectTest.java
@@ -26,6 +26,8 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -35,8 +37,13 @@ import org.springframework.web.bind.annotation.PostMapping;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.config.AuditConfigurationProperties;
+import stirling.software.proprietary.config.CustomAuditEventRepository;
+import stirling.software.proprietary.model.security.PersistentAuditEvent;
+import stirling.software.proprietary.repository.PersistentAuditEventRepository;
import stirling.software.proprietary.service.AuditService;
+import tools.jackson.databind.json.JsonMapper;
+
@ExtendWith(MockitoExtension.class)
class ControllerAuditAspectTest {
@@ -68,6 +75,52 @@ class ControllerAuditAspectTest {
return jp;
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void verboseAuditPersistsOutcomesWithoutPasswordArguments(boolean fail) throws Throwable {
+ var properties = new ApplicationProperties();
+ properties.getPremium().getEnterpriseFeatures().getAudit().setEnabled(true);
+ properties.getPremium().getEnterpriseFeatures().getAudit().setLevel(3);
+ var config = new AuditConfigurationProperties(properties);
+ var persisted = mock(PersistentAuditEventRepository.class);
+ var writer = new CustomAuditEventRepository(persisted, JsonMapper.builder().build());
+ var service = new AuditService(writer, config, true, null, null);
+ var realAspect = new ControllerAuditAspect(service, config);
+ var jp = mock(ProceedingJoinPoint.class);
+ var sig = mock(MethodSignature.class);
+ when(jp.getSignature()).thenReturn(sig);
+ when(sig.getMethod())
+ .thenReturn(
+ SampleController.class.getMethod(
+ "passwordEndpoint", String.class, Map.class));
+ when(sig.getParameterNames()).thenReturn(new String[] {"password", "request"});
+ when(jp.getTarget()).thenReturn(new SampleController());
+ var request =
+ Map.of(
+ "ownerPassword",
+ "owner-secret",
+ "keyLength",
+ 256,
+ "nested",
+ Map.of("sourcePassword", "source-secret"));
+ when(jp.getArgs()).thenReturn(new Object[] {"restore-secret", request});
+ if (fail) {
+ when(jp.proceed()).thenThrow(new IllegalArgumentException("Invalid PDF"));
+ assertThatThrownBy(() -> realAspect.auditPostMethod(jp))
+ .isInstanceOf(IllegalArgumentException.class);
+ } else {
+ when(jp.proceed()).thenReturn("done");
+ assertThat(realAspect.auditPostMethod(jp)).isEqualTo("done");
+ }
+
+ var captor = ArgumentCaptor.forClass(PersistentAuditEvent.class);
+ verify(persisted).save(captor.capture());
+ assertThat(captor.getValue().getData())
+ .contains(fail ? "failure" : "success", "keyLength=256")
+ .doesNotContain("restore-secret", "owner-secret", "source-secret");
+ assertThat(request.get("ownerPassword")).isEqualTo("owner-secret");
+ }
+
@Nested
@DisplayName("fast path")
class FastPath {
@@ -303,6 +356,11 @@ class ControllerAuditAspectTest {
/** Sample controller whose methods carry the web-mapping annotations the aspect inspects. */
public static class SampleController {
+ @PostMapping("/api/v1/security/restore-pdf-protection")
+ public String passwordEndpoint(String password, Map<String, Object> request) {
+ return "done";
+ }
+
@GetMapping("/api/v1/sample")
public String getEndpoint() {
return "get";
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/util/SecretMaskerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/util/SecretMaskerTest.java
index 86d30cebe9..25dfd3603f 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/util/SecretMaskerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/util/SecretMaskerTest.java
@@ -9,6 +9,8 @@ import java.util.Map;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Unit tests for {@link SecretMasker}.
@@ -20,6 +22,35 @@ import org.junit.jupiter.api.Test;
*/
class SecretMaskerTest {
+ @Test
+ void masksNestedArgumentsWithoutRequiringStringMapKeys() {
+ var input = Map.of(1, Map.of("sourcePassword", "private-value"));
+
+ assertEquals(
+ Map.of(1, Map.of("sourcePassword", SecretMasker.REDACTED)),
+ SecretMasker.maskValue("request", input));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "password",
+ "arg_password",
+ "ownerPassword",
+ "sourcePassword",
+ "retainedOpeningPassword",
+ "arg_sourcePassword"
+ })
+ void masksPasswordFieldsIncludingAuditPrefixes(String field) {
+ var input = Map.<String, Object>of(field, "private-value", "keyLength", 256);
+
+ var masked = SecretMasker.mask(input);
+
+ assertEquals(SecretMasker.REDACTED, masked.get(field));
+ assertEquals(256, masked.get("keyLength"));
+ assertEquals("private-value", input.get(field));
+ }
+
@Nested
@DisplayName("mask(Map<String,Object>) method")
class MaskMethod {
diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.py
index 4e81fc1460..fa7ce7a29c 100644
--- a/engine/src/stirling/models/tool_io.py
+++ b/engine/src/stirling/models/tool_io.py
@@ -261,7 +261,7 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
accepts=[ToolFormat.PDF], produces=ToolFormat.JSON, arity=ToolArity.SISO
),
ToolEndpoint.ADD_PASSWORD: ToolIOSpec(
- accepts=[ToolFormat.PDF],
+ accepts=[ToolFormat.PDF, ToolFormat.PDF_ENCRYPTED],
produces=ToolFormat.PDF_ENCRYPTED,
arity=ToolArity.SISO,
cases=[
@@ -269,6 +269,7 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
when=[
ToolIOWhen(param="password", matches=[""], default=""),
ToolIOWhen(param="ownerPassword", matches=[""], default=""),
+ ToolIOWhen(param="preserveExisting", matches=["false"], default="false"),
],
produces=ToolFormat.PDF,
arity=ToolArity.SISO,
@@ -281,7 +282,16 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {
ToolEndpoint.REDACT_EXECUTE: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.REMOVE_CERT_SIGN: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.REMOVE_PASSWORD: ToolIOSpec(
- accepts=[ToolFormat.PDF, ToolFormat.PDF_ENCRYPTED], produces=ToolFormat.PDF, arity=ToolArity.SISO
+ accepts=[ToolFormat.PDF, ToolFormat.PDF_ENCRYPTED],
+ produces=ToolFormat.PDF,
+ arity=ToolArity.SISO,
+ cases=[
+ ToolIOCase(
+ when=[ToolIOWhen(param="password", matches=[""], default="")],
+ produces=ToolFormat.ANY,
+ arity=ToolArity.SISO,
+ )
+ ],
),
ToolEndpoint.SANITIZE_PDF: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
ToolEndpoint.TIMESTAMP_PDF: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index ecfec2dfe0..a251c552b7 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -120,7 +120,7 @@ class KeyLength(IntEnum):
class AddPasswordParams(ApiModel):
"""
- This endpoint adds password protection to a PDF file. Users can specify a set of permissions that should be applied to the file. Input:PDF Output:PDF_ENCRYPTED Type:SISO
+ This endpoint adds password protection to a PDF file. Users can specify a set of permissions that should be applied to the file. sourcePassword authenticates an existing protected source; preserveExisting changes permissions while retaining existing credentials. Omitting these options preserves the existing add-password behaviour. Input:PDF/PDF_ENCRYPTED Output:PDF_ENCRYPTED Type:SISO
"""
key_length: KeyLength = Field(KeyLength.integer_256, description="The length of the encryption key")
@@ -131,6 +131,10 @@ class AddPasswordParams(ApiModel):
password: SecretStr | None = Field(
None, description="The password to be added to the PDF file (Restricts the opening of the document itself.)"
)
+ preserve_existing: bool = Field(
+ False,
+ description="Change permissions while retaining existing passwords and encryption. A supplied ownerPassword replaces the permissions password.",
+ )
prevent_assembly: bool = Field(False, description="Whether document assembly is prevented")
prevent_extract_content: bool = Field(False, description="Whether content extraction is prevented")
prevent_extract_for_accessibility: bool = Field(
@@ -141,6 +145,10 @@ class AddPasswordParams(ApiModel):
prevent_modify_annotations: bool = Field(False, description="Whether modification of annotations is prevented")
prevent_printing: bool = Field(False, description="Whether printing of the document is prevented")
prevent_printing_faithful: bool = Field(False, description="Whether faithful printing is prevented")
+ source_password: SecretStr | None = Field(
+ None,
+ description="Credential for authenticating an existing protected source, separate from the new passwords. Omit to retain legacy add-password behaviour.",
+ )
class Alphabet(StrEnum):
@@ -1350,10 +1358,26 @@ class RemovePagesParams(ApiModel):
class RemovePasswordParams(ApiModel):
"""
- This endpoint removes the password from a protected PDF file while preserving its document permissions. Users need to provide the existing password. Input:PDF/PDF_ENCRYPTED Output:PDF Type:SISO
+ This endpoint removes the password from a protected PDF file while preserving its document permissions. Users need to provide the existing password. Optional ownerPassword, sourcePassword or retainedOpeningPassword enable selective removal: nonempty password and ownerPassword select which passwords to remove; blank selections retain them. removeAll explicitly removes all protection, subject to the owner-password policy. Source and retained credentials never select removal. Input:PDF/PDF_ENCRYPTED Output:PDF Type:SISO
"""
+ owner_password: SecretStr | None = Field(
+ None,
+ description="Permissions password to remove. Supplying this field enables selective removal; leave blank to retain the permissions password.",
+ )
password: SecretStr | None = Field(None, description="The password of the PDF file")
+ remove_all: bool = Field(
+ False,
+ description="Explicitly remove all passwords and restrictions, subject to the server owner-password policy. The password or sourcePassword authenticates the source; selective removal fields do not apply.",
+ )
+ retained_opening_password: SecretStr | None = Field(
+ None,
+ description="Opening password to retain when removing only the permissions password. Supplying this field enables selective removal.",
+ )
+ source_password: SecretStr | None = Field(
+ None,
+ description="Credential for opening the source, without selecting it for removal. Supplying this field enables selective removal; password then selects the opening password to remove and ownerPassword selects the permissions password to remove. Blank selection fields keep their passwords.",
+ )
class RenameAttachmentParams(ApiModel):
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 736e610b3c..148dc50864 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4492,6 +4492,7 @@ allowed = "Allowed"
annotations = "Annotations"
authoriseAction = "This PDF requires permission to use {{action}}."
changeOwnerPassword = "Change permissions password"
+checkingPermissions = "Checking PDF permissions..."
chooseOwnerPassword = "Choose a different password"
continue = "Continue"
copyFailed = "Unable to create the copy. Your PDF is unchanged."
@@ -4500,6 +4501,7 @@ editing = "Editing"
enterPassword = "Enter password"
ignoredByServer = "Permissions are ignored by this server's settings. The PDF's protection is unchanged."
incorrectPassword = "Incorrect password"
+inspectionFailed = "Unable to check this PDF's permissions. Try again."
lowQualityPrintUnsupported = "This PDF allows low-quality printing only, which this viewer does not support."
lowResolutionOnly = "Low resolution only"
manageProtection = "Manage protection"
@@ -4508,8 +4510,6 @@ mixedProtection = "These PDFs have separate protection settings. Process them in
newOwnerPassword = "New permissions password"
notRequired = "Not required"
openingPassword = "Password to open"
-openingPasswordRemoved = "Opening password removed. Restrictions retained."
-openingRequired = "Enter the password used to open this PDF."
openPdf = "Open PDF"
ownerPassword = "Permissions password"
ownerRequired = "Enter the permissions password to continue."
@@ -11466,16 +11466,9 @@ title = "Page Selection"
[removePassword]
appliesTo = "Set on {{count}} of {{total}} PDFs"
-batchRemoved = "Entered passwords removed where set. Blank fields kept unchanged."
-bothRemoved = "Both passwords and restrictions removed."
-checkingProtection = "Checking protection…"
keepBlank = "Leave a field blank to keep that password."
notSet = "Not set"
-openingOnlyRemoved = "Opening password removed."
openWithReaderFirst = "Reopen this PDF using its opening password before removing only the permissions password."
-ownerOnlyRemoved = "Permissions password and restrictions removed."
-ownerRemoved = "Permissions password and restrictions removed. Opening password kept."
-protectionUnavailable = "Unable to check protection"
selectiveHelp = "Enter the current password for each protection you want to remove. A blank field keeps that password. Removing the permissions password also removes action restrictions."
selectPasswords = "Passwords to remove"
submit = "Remove Password"
@@ -13699,6 +13692,7 @@ validUntrusted = "Valid, signer not verified"
[viewer]
cannotPreviewFile = "Cannot Preview File"
+copyRestricted = "Copying is disabled by this PDF's permissions."
copyText = "Copy"
coverPageView = "Show Cover Page Separately"
disableColorFilter = "Disable Color Filter"
@@ -13806,6 +13800,7 @@ page = "Page"
thread = "Thread"
[viewer.error]
+loadError = "Failed to load PDF"
noFileProvided = "Error: No file provided to viewer"
[viewer.formBar]
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
index 0a904bb921..9cf2af3d99 100644
--- a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
@@ -791,6 +791,12 @@ export default function PageTracks() {
);
const undo = useCallback(() => dispatch({ type: "undo" }), [dispatch]);
+ const inspectionLifetime = useRef(new AbortController());
+ useEffect(() => {
+ const cancellation = new AbortController();
+ inspectionLifetime.current = cancellation;
+ return () => cancellation.abort();
+ }, []);
const redo = useCallback(() => dispatch({ type: "redo" }), [dispatch]);
const saveNow = useCallback(() => {
void save();
@@ -804,6 +810,7 @@ export default function PageTracks() {
const lookup = {
getStub: fileSelectors.getStirlingFileStub,
getFile: fileSelectors.getFile,
+ signal: inspectionLifetime.current.signal,
};
const trackIds = workspace.order.filter(
(id) => (workspace.tracks[id]?.pages.length ?? 0) > 0,
@@ -830,6 +837,7 @@ export default function PageTracks() {
}
return files;
} catch (error) {
+ if (lookup.signal.aborted) return null;
alertExportFailure(error, t);
return null;
}
@@ -841,6 +849,7 @@ export default function PageTracks() {
const lookup = {
getStub: fileSelectors.getStirlingFileStub,
getFile: fileSelectors.getFile,
+ signal: inspectionLifetime.current.signal,
};
setDownloadingSelection(true);
try {
@@ -862,6 +871,7 @@ export default function PageTracks() {
await downloadFileWithPolicy({ data: file, filename: file.name });
}
} catch (error) {
+ if (lookup.signal.aborted) return;
alertExportFailure(error, t);
} finally {
setDownloadingSelection(false);
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
index aa8e45d9b2..64f23459f4 100644
--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
@@ -19,7 +19,7 @@ import {
clearPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
import { convertImageToPdf } from "@app/utils/imageToPdfUtils";
const exportPDFMultiFile = vi.hoisted(() => vi.fn());
@@ -129,8 +129,6 @@ describe("buildTrackFile with images and protected PDFs", () => {
signed: false,
ownerAuthenticated: false,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
};
rememberPdfAccess(protectedPdf, access);
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
index 78fd3fc5a7..6d4d18de82 100644
--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
@@ -23,6 +23,8 @@ import {
export interface TrackFileLookup {
getStub: (id: FileId) => StirlingFileStub | undefined;
getFile: (id: FileId) => File | undefined;
+ /** The initiating view owns cancellation; document closure also cancels inspection. */
+ signal?: AbortSignal;
}
export interface BuiltTrackFile {
@@ -102,6 +104,7 @@ export async function buildTrackFile(
await prepareUnlockedFile(
createStirlingFile(file, id as FileId),
"/api/v1/general/rearrange-pages",
+ lookup.signal,
),
),
);
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts
index 4f81d6ccf6..82bf9da3d9 100644
--- a/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts
@@ -1,4 +1,4 @@
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { alert } from "@app/components/toast";
import { useFileActions, useFileState } from "@app/contexts/FileContext";
@@ -84,6 +84,8 @@ export function useTrackSave(
const onMaterializedRef = useRef(options.onMaterialized);
onMaterializedRef.current = options.onMaterialized;
const [saving, setSaving] = useState(false);
+ const inspectionCancellation = useRef<AbortController | null>(null);
+ useEffect(() => () => inspectionCancellation.current?.abort(), []);
const [progress, setProgress] = useState<TrackSaveProgress | null>(null);
const save = useCallback(
@@ -110,6 +112,8 @@ export function useTrackSave(
selectors.getStirlingFileStub,
);
+ const cancellation = new AbortController();
+ inspectionCancellation.current = cancellation;
try {
assertFilesNotBlocked(policyIds);
// Build every output first: a track can hold pages belonging to another
@@ -122,6 +126,7 @@ export function useTrackSave(
const output = await buildTrackFile(track, {
getStub: selectors.getStirlingFileStub,
getFile: selectors.getFile,
+ signal: cancellation.signal,
});
if (!output) continue;
built.push({
@@ -213,6 +218,7 @@ export function useTrackSave(
return versioned;
} catch (error) {
+ if (cancellation.signal.aborted) return null;
if (error instanceof PolicyBlockedError) {
alert({
alertType: "warning",
@@ -232,6 +238,8 @@ export function useTrackSave(
}
return null;
} finally {
+ if (inspectionCancellation.current === cancellation)
+ inspectionCancellation.current = null;
setSaving(false);
setProgress(null);
}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
index 3e71cb03c4..4d2fed0bae 100644
--- a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
@@ -3,7 +3,7 @@ import { useFileState } from "@app/contexts/FileContext";
import { FileId } from "@app/types/file";
import { PageSize, TrackSource } from "@app/components/pageTracks/types";
import { ProcessedFilePage } from "@app/types/fileContext";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import { isPdfFile } from "@app/utils/fileUtils";
import { isPageImage } from "@app/components/pageTracks/trackFileKind";
import {
diff --git a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
index b7d58db127..4fa8e1efbc 100644
--- a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
+++ b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
@@ -13,6 +13,8 @@ interface EncryptedPdfUnlockModalProps {
password: string;
errorMessage?: string | null;
isProcessing: boolean;
+ /** Pending access is displayed separately from a confirmed password challenge. */
+ inspection?: { error?: string; retry: () => void };
remainingCount?: number;
confirmLabel?: string;
sessionUnlock?: boolean;
@@ -34,6 +36,7 @@ const EncryptedPdfUnlockModal = ({
password,
errorMessage,
isProcessing,
+ inspection,
remainingCount = 0,
confirmLabel,
sessionUnlock = false,
@@ -100,7 +103,24 @@ const EncryptedPdfUnlockModal = ({
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
data-testid={testIdPrefix ? `${testIdPrefix}-modal` : undefined}
>
- <Stack gap="md">
+ {inspection && (
+ <Stack gap="md">
+ <ProtectedPdfFileCard fileName={fileName} />
+ <Text role={inspection.error ? "alert" : "status"}>
+ {inspection.error ??
+ t(
+ "encryptedPdfUnlock.checkingPermissions",
+ "Checking PDF permissions...",
+ )}
+ </Text>
+ {inspection.error && (
+ <Button onClick={inspection.retry}>
+ {t("common.retry", "Retry")}
+ </Button>
+ )}
+ </Stack>
+ )}
+ <Stack gap="md" display={inspection ? "none" : undefined}>
<ProtectedPdfFileCard fileName={fileName} />
{(preservationReason || actionLabel) && (
<Text size="sm">
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
index a5eea78a6a..8e3aa45220 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
@@ -1,5 +1,6 @@
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { pdfAllows } from "@app/services/pdfSessionUnlock";
+import { pdfAllows } from "@app/services/pdfPermissions";
+
import { PdfPermissionFlag } from "@embedpdf/models";
import React, {
useCallback,
diff --git a/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx b/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
index 36d92c38b6..990f944103 100644
--- a/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
+++ b/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
@@ -4,7 +4,7 @@ import { StirlingFile } from "@app/types/fileContext";
import i18n from "@app/i18n";
import { useViewScopedFileStubs } from "@app/hooks/tools/shared/useViewScopedFiles";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
export interface FilesToolStepProps {
selectedFiles: StirlingFile[];
diff --git a/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx b/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx
index fd7ef6a7dd..f3c2bf6f5e 100644
--- a/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx
+++ b/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx
@@ -1,7 +1,7 @@
import { Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
/** Reports protection changes only for outputs whose security was verified. */
export function PdfProtectionResult({
@@ -9,11 +9,12 @@ export function PdfProtectionResult({
summary,
}: {
files: File[];
- summary?: string;
+ summary?: string | null;
}) {
const { t } = useTranslation();
usePdfAccess(undefined);
if (
+ summary === null ||
!files.length ||
!files.every((file) => {
const access = getPdfAccess(file);
diff --git a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
index dd1bff02e3..dae0aadc36 100644
--- a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
+++ b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
@@ -71,7 +71,7 @@ export interface ExecuteButtonConfig {
}
export interface ReviewStepConfig<TParams = unknown> {
- protectionSummary?: string;
+ protectionSummary?: string | null;
isVisible: boolean;
operation: ToolOperationHook<TParams>;
title: string;
diff --git a/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx b/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx
index 1696b50d52..cf6fac2abb 100644
--- a/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx
+++ b/frontend/editor/src/core/components/viewer/DocumentReadyWrapper.tsx
@@ -1,5 +1,11 @@
import React from "react";
-import { useActiveDocument } from "@embedpdf/plugin-document-manager/react";
+import {
+ useActiveDocument,
+ useDocumentManagerCapability,
+} from "@embedpdf/plugin-document-manager/react";
+import { Center, Stack, Text } from "@mantine/core";
+import { Button } from "@app/ui/Button";
+import { useTranslation } from "react-i18next";
interface DocumentReadyWrapperProps {
children: (documentId: string) => React.ReactNode;
@@ -11,6 +17,30 @@ export function DocumentReadyWrapper({
fallback = null,
}: DocumentReadyWrapperProps) {
const { activeDocumentId, activeDocument } = useActiveDocument();
+ const { provides: manager } = useDocumentManagerCapability();
+ const { t } = useTranslation();
+ if (activeDocumentId && activeDocument?.status === "error") {
+ return (
+ <Center h="100%">
+ <Stack align="center">
+ <Text role="alert">
+ {activeDocument.error ||
+ t("viewer.error.loadError", "Failed to load PDF")}
+ </Text>
+ <Button
+ onClick={() => {
+ void manager
+ ?.retryDocument(activeDocumentId)
+ .toPromise()
+ .catch(() => {});
+ }}
+ >
+ {t("common.retry", "Retry")}
+ </Button>
+ </Stack>
+ </Center>
+ );
+ }
if (
!activeDocumentId ||
activeDocument?.status !== "loaded" ||
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index 13e1096dd8..eb2642ecd9 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -47,6 +47,7 @@ import type {
SignatureOverlayAPI,
} from "@app/components/viewer/viewerTypes";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
+import { rememberPlainPdfExport } from "@app/services/pdfAccessService";
import {
isStirlingFile,
getFormFillFileId,
@@ -1117,6 +1118,7 @@ const EmbedPdfViewerContent = ({
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const filename = currentFile.name || "document.pdf";
const file = new File([blob], filename, { type: "application/pdf" });
+ rememberPlainPdfExport(currentFile, file);
// Step 3: Create StirlingFiles and stubs for version history
// Only consume the current file, not all active files
@@ -1213,6 +1215,7 @@ const EmbedPdfViewerContent = ({
const file = new File([filledBlob], filename, {
type: "application/pdf",
});
+ rememberPlainPdfExport(currentFile, file);
// Get current file info for creating the updated version
const currentFileId = currentFileStableId;
@@ -1297,6 +1300,7 @@ const EmbedPdfViewerContent = ({
const file = new File([modifiedBlob], filename, {
type: "application/pdf",
});
+ rememberPlainPdfExport(currentFile, file);
const currentFileId = currentFileStableId;
if (!currentFileId) throw new Error("Current file ID not found");
@@ -1355,6 +1359,7 @@ const EmbedPdfViewerContent = ({
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const filename = currentFile.name || "document.pdf";
const file = new File([blob], filename, { type: "application/pdf" });
+ rememberPlainPdfExport(currentFile, file);
// Create StirlingFiles and stubs for version history
const currentFileId = currentFileStableId;
diff --git a/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx b/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx
index 3311d71293..5bc7e4a1f9 100644
--- a/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx
@@ -31,6 +31,7 @@ export function InitialDocumentLoadBridge({
};
}, [fileKey, onFailed]);
useEffect(() => {
+ if (activeDocument?.status === "loading") completedRef.current = false;
if (!fileKey || completedRef.current) return;
if (activeDocument?.status === "loaded") {
completedRef.current = true;
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 20cd12198f..a5ed3a7e74 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -13,6 +13,10 @@ import { EmbedPDF, useDocumentState } from "@embedpdf/core/react";
import { useLocalPdfiumEngine } from "@app/hooks/useLocalPdfiumEngine";
import { PrivateContent } from "@app/components/shared/PrivateContent";
import { useAppConfig } from "@app/contexts/AppConfigContext";
+import {
+ bindPdfViewerSource,
+ withPdfViewerAccess,
+} from "@app/components/viewer/pdfViewerAccess";
import { useSignaturePreviewHistory } from "@app/hooks/signing/useSignaturePreviewHistory";
// Import the essential plugins
@@ -105,13 +109,11 @@ import { AnnotationMenuEvents } from "@app/components/viewer/AnnotationMenuEvent
import { DocumentSwapBridge } from "@app/components/viewer/DocumentSwapBridge";
import { PdfPasswordBridge } from "@app/components/viewer/PdfPasswordBridge";
import { isStirlingFile } from "@app/types/fileContext";
-import {
- hasPdfPermissionOverride,
- pdfAllows,
-} from "@app/services/pdfSessionUnlock";
+import { pdfAllows, canPrintPdf } from "@app/services/pdfPermissions";
+
import { PdfPermissionFlag } from "@embedpdf/models";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { canPrintPdf } from "@app/services/pdfPermissions";
+
import {
DocumentRestoreBridge,
type DocumentRestoreEvent,
@@ -927,9 +929,13 @@ export function LocalEmbedPDF({
}: LocalEmbedPDFProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
- const pdfAccess = usePdfAccess(file ?? fileId);
- const annotationsReadOnly = !pdfAccess || pdfAccess.encrypted;
- const showAnnotations = enableAnnotations || annotationsReadOnly;
+ const [urlSource, setUrlSource] = useState<File | null>(null);
+ const pdfAccess = usePdfAccess(file ?? urlSource ?? fileId);
+ const permissionOverride =
+ pdfAccess?.ownerAuthenticated === true ||
+ (pdfAccess?.honorOwnerPasswords ?? config?.honorOwnerPasswords) === false;
+ const annotationsReadOnly =
+ !pdfAccess || pdfAccess.encrypted || !enableAnnotations;
const [pdfUrl, setPdfUrl] = useState<string | null>(() => url ?? null);
const [, setAnnotations] = useState<
Array<{ id: string; pageIndex: number; rect: Rect }>
@@ -1115,16 +1121,16 @@ export function LocalEmbedPDF({
// Reads bytes on the main thread for the worker, and lands bytes plus URL in
// one commit so the registry rebuilds once per replacement.
useEffect(() => {
+ const sourceKey = file ? fileStableKey : (url ?? null);
if (
- fileStableKey &&
- openedPermissionOverrideRef.current ===
- hasPdfPermissionOverride(pdfAccess) &&
- (openedContentKeyRef.current === fileStableKey ||
- shouldSkipBytes?.(fileStableKey))
+ sourceKey &&
+ openedPermissionOverrideRef.current === permissionOverride &&
+ (openedContentKeyRef.current === sourceKey ||
+ (file && shouldSkipBytes?.(sourceKey)))
) {
// The live document already shows this save; swapping the bytes would
// reopen it and lose the scroll position for no visual gain.
- openedContentKeyRef.current = fileStableKey;
+ openedContentKeyRef.current = sourceKey;
return;
}
let cancelled = false;
@@ -1139,11 +1145,10 @@ export function LocalEmbedPDF({
if (
!contentKey ||
(openedContentKeyRef.current === contentKey &&
- openedPermissionOverrideRef.current ===
- hasPdfPermissionOverride(pdfAccess))
+ openedPermissionOverrideRef.current === permissionOverride)
)
return;
- openedPermissionOverrideRef.current = hasPdfPermissionOverride(pdfAccess);
+ openedPermissionOverrideRef.current = permissionOverride;
openedContentKeyRef.current = contentKey;
if (!initialDocumentOpenedRef.current) {
initialDocumentOpenedRef.current = true;
@@ -1152,7 +1157,8 @@ export function LocalEmbedPDF({
name,
fileKey: contentKey,
password: pdfAccess?.password,
- honorOwnerPasswords: pdfAccess?.honorOwnerPasswords,
+ honorOwnerPasswords:
+ pdfAccess?.honorOwnerPasswords ?? config?.honorOwnerPasswords,
});
return;
}
@@ -1161,7 +1167,8 @@ export function LocalEmbedPDF({
name,
fileKey: contentKey,
password: pdfAccess?.password,
- honorOwnerPasswords: pdfAccess?.honorOwnerPasswords,
+ honorOwnerPasswords:
+ pdfAccess?.honorOwnerPasswords ?? config?.honorOwnerPasswords,
});
};
const fail = (source: string) => (err: unknown) => {
@@ -1178,6 +1185,7 @@ export function LocalEmbedPDF({
.arrayBuffer()
.then((buf) => {
if (cancelled) return;
+ bindPdfViewerSource(buf, file);
objectUrl = URL.createObjectURL(file);
const previous = publishedObjectUrlRef.current;
publishedObjectUrlRef.current = objectUrl;
@@ -1191,9 +1199,20 @@ export function LocalEmbedPDF({
} else if (url) {
setPdfUrl(url);
fetch(url)
- .then((r) => r.arrayBuffer())
- .then((buf) => {
- if (!cancelled) openDocument(buf, exportFileName, url);
+ .then((r) => {
+ if (!r.ok) throw new Error("Unable to read PDF");
+ return r.blob();
+ })
+ .then(async (blob) => {
+ const source = new File([blob], exportFileName, {
+ type: "application/pdf",
+ });
+ const buf = await source.arrayBuffer();
+ if (!cancelled) {
+ bindPdfViewerSource(buf, source);
+ setUrlSource(source);
+ openDocument(buf, exportFileName, url);
+ }
})
.catch(fail("url"));
} else {
@@ -1216,8 +1235,7 @@ export function LocalEmbedPDF({
url,
shouldSkipBytes,
exportFileName,
- pdfAccess?.ownerAuthenticated,
- pdfAccess?.honorOwnerPasswords,
+ permissionOverride,
onDocumentLoadFailed,
]);
@@ -1288,30 +1306,20 @@ export function LocalEmbedPDF({
// The registry is built from the viewer's first source; later bytes arrive
// through DocumentSwapBridge, so no replacement may change that identity.
- const urlDocumentSource = file ? null : pdfUrl;
- const urlPluginsSource = useMemo(() => {
- if (file || !urlDocumentSource) return null;
- return { url: urlDocumentSource, name: exportFileName };
- }, [!!file, urlDocumentSource, exportFileName]);
-
// Create plugins configuration
const plugins = useMemo(() => {
- const initialSource = initialDocument ?? urlPluginsSource;
- if (!initialSource) return [];
- const initialDocuments: InitialDocumentOptions[] =
- "buffer" in initialSource
- ? [
- {
- buffer: initialSource.buffer,
- name: initialSource.name,
- password: initialSource.password,
- permissions: {
- enforceDocumentPermissions:
- initialSource.honorOwnerPasswords !== false,
- },
- },
- ]
- : [{ url: initialSource.url, name: initialSource.name }];
+ if (!initialDocument) return [];
+ const initialDocuments: InitialDocumentOptions[] = [
+ {
+ buffer: initialDocument.buffer,
+ name: initialDocument.name,
+ password: initialDocument.password,
+ permissions: {
+ enforceDocumentPermissions:
+ initialDocument.honorOwnerPasswords !== false,
+ },
+ },
+ ];
// Calculate 3.5rem in pixels dynamically based on root font size
const rootFontSize = parseFloat(
@@ -1333,7 +1341,8 @@ export function LocalEmbedPDF({
createPluginRegistration(ScrollPluginPackage),
createPluginRegistration(RenderPluginPackage, {
withForms: !enableFormFill,
- withAnnotations: !showAnnotations,
+ // The overlay owns appearances in every mode, so access changes never rebuild the registry.
+ withAnnotations: false,
}),
// Register interaction manager (required for zoom and selection features)
@@ -1403,14 +1412,22 @@ export function LocalEmbedPDF({
createPluginRegistration(PrintPluginPackage),
];
- }, [initialDocument, urlPluginsSource, showAnnotations]);
+ }, [initialDocument]);
const fontFallbackConfig = useFontFallbackConfig();
- const { engine, isLoading, error } = useLocalPdfiumEngine({
+ const {
+ engine: workerEngine,
+ isLoading,
+ error,
+ } = useLocalPdfiumEngine({
wasmUrl: pdfiumWasmUrl,
fontFallback: fontFallbackConfig,
});
+ const engine = useMemo(
+ () => (workerEngine ? withPdfViewerAccess(workerEngine) : null),
+ [workerEngine],
+ );
useEffect(() => {
const key = fileStableKey ?? url;
@@ -1472,7 +1489,7 @@ export function LocalEmbedPDF({
}
const hasInput = Boolean(file || url);
- const isInputReady = Boolean(initialDocument || (!file && pdfUrl));
+ const isInputReady = Boolean(initialDocument);
// Checked before the loading screen: a rejected engine import leaves `engine`
// null, so the loader would otherwise hide the error forever.
@@ -1600,7 +1617,7 @@ export function LocalEmbedPDF({
pdfRenderMode,
enableFormFill,
formEditingActive,
- enableAnnotations: showAnnotations,
+ enableAnnotations: true,
annotationsReadOnly,
canCopy: pdfAllows(pdfAccess, PdfPermissionFlag.CopyContents),
enableRedaction,
@@ -1728,7 +1745,7 @@ export function LocalEmbedPDF({
pageOptions={pageOptions}
/>
<DocumentComments
- enabled={showAnnotations}
+ enabled
readOnly={annotationsReadOnly}
documentId={documentId}
fileName={exportFileName}
diff --git a/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx b/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx
index f0b90843af..d204b98f38 100644
--- a/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/PanAPIBridge.tsx
@@ -58,7 +58,7 @@ function PanAPIBridgeInner({ documentId }: { documentId: string }) {
return () => {
registerBridge("pan", null);
};
- }, [isPanning, registerBridge, triggerImmediatePanUpdate]);
+ }, [documentId, isPanning, registerBridge, triggerImmediatePanUpdate]);
useEffect(() => {
return () => {
diff --git a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx
index 621e958260..c34b4474af 100644
--- a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx
+++ b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx
@@ -15,7 +15,7 @@ import {
clearPdfAccess,
rememberPdfAccess,
type PdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
vi.mock("react-i18next", () => {
const t = (key: string, fallback?: string) => fallback ?? key;
@@ -23,7 +23,7 @@ vi.mock("react-i18next", () => {
});
const mock = vi.hoisted(() => ({ probe: vi.fn(), unlock: vi.fn() }));
-vi.mock("@app/utils/thumbnailUtils", () => ({
+vi.mock("@app/utils/pdfEncryptionProbe", () => ({
looksEncryptedFromTrailer: mock.probe,
}));
vi.mock("@app/contexts/FileContext", () => ({
@@ -54,8 +54,6 @@ const access: PdfAccess = {
signed: false,
ownerAuthenticated: false,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
};
const passwordError = {
diff --git a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx
index 20c8e21b3f..fe67d2dad3 100644
--- a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx
+++ b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx
@@ -12,8 +12,8 @@ import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockMo
import ToolLoadingFallback from "@app/components/tools/ToolLoadingFallback";
import { useFileActions } from "@app/contexts/FileContext";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
-import { looksEncryptedFromTrailer } from "@app/utils/thumbnailUtils";
+import { getPdfAccess } from "@app/services/pdfAccessService";
+import { looksEncryptedFromTrailer } from "@app/utils/pdfEncryptionProbe";
import { handlePasswordError } from "@app/utils/toolErrorHandler";
interface PreviewState {
diff --git a/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx b/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx
index 6dbfd3d1e9..86e267375b 100644
--- a/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx
+++ b/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx
@@ -12,7 +12,7 @@ import { useToolWorkflowActions } from "@app/contexts/ToolWorkflowContext";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
import type { StirlingFile } from "@app/types/fileContext";
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
-import { hasPdfPermissionOverride } from "@app/services/pdfSessionUnlock";
+import { hasPdfPermissionOverride } from "@app/services/pdfPermissions";
/** Persistent document settings; authentication is requested only when an action needs it. */
export function PdfProtectionStatus({ file }: { file: StirlingFile }) {
@@ -78,7 +78,7 @@ export function PdfProtectionStatus({ file }: { file: StirlingFile }) {
<Group gap={6} role="status">
<Icon name="lock" size={14} />
<Text size="xs">
- {access.ownerAuthenticated && access.hasOwnerPassword !== false
+ {access.ownerAuthenticated
? t(
"encryptedPdfUnlock.permissionsUnlocked",
"Permissions unlocked for this session",
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx
index eec118c6de..b20a4288fa 100644
--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx
@@ -140,17 +140,22 @@ describe("TextSelectionMenu", () => {
]);
});
- test("does not copy when document permissions deny extraction", () => {
+ test("explains why copying is disabled when document permissions deny extraction", async () => {
render(
<TestWrapper>
<TextSelectionMenu {...defaultProps} canCopy={false} />
</TestWrapper>,
);
const copy = screen.getByRole("button", { name: "Copy" });
- expect(copy).toBeDisabled();
+ expect(copy).toHaveAttribute("aria-disabled", "true");
+ expect(copy.querySelector("button")).toBeDisabled();
fireEvent.click(copy);
expect(mockViewerCopy).not.toHaveBeenCalled();
expect(mockCopyToClipboard).not.toHaveBeenCalled();
+ fireEvent.focus(copy);
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "Copying is disabled by this PDF's permissions.",
+ );
});
test("confirms a copy only after the clipboard write succeeds", async () => {
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
index 468c87f2df..d96f98bd64 100644
--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
@@ -368,16 +368,38 @@ function TextSelectionMenuInner({
onMouseDown={(e) => e.preventDefault()}
>
<div className="embedpdf-text-selection-menu">
- <Tooltip label={t("viewer.copyText", "Copy")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleCopy}
- disabled={!canCopy}
- aria-label={t("viewer.copyText", "Copy")}
+ <Tooltip
+ label={
+ canCopy
+ ? t("viewer.copyText", "Copy")
+ : t(
+ "viewer.copyRestricted",
+ "Copying is disabled by this PDF's permissions.",
+ )
+ }
+ withArrow
+ multiline
+ w={canCopy ? undefined : 260}
+ events={{ hover: true, focus: true, touch: false }}
+ >
+ <span
+ style={{ display: "inline-flex" }}
+ tabIndex={canCopy ? undefined : 0}
+ role={canCopy ? undefined : "button"}
+ aria-label={canCopy ? undefined : t("viewer.copyText", "Copy")}
+ aria-disabled={canCopy ? undefined : true}
>
- <Icon name="copy" size={20} />
- </button>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleCopy}
+ disabled={!canCopy}
+ aria-label={t("viewer.copyText", "Copy")}
+ aria-hidden={!canCopy || undefined}
+ >
+ <Icon name="copy" size={20} />
+ </button>
+ </span>
</Tooltip>
{!readOnly && (
diff --git a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
index 453e79ddd8..0a05483afd 100644
--- a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
+++ b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
@@ -249,6 +249,21 @@ describe("form save document completion", () => {
await rejected;
});
+ it("reports readiness after retrying a failed initial load", () => {
+ const props = { fileKey: "B", onReady: vi.fn(), onFailed: vi.fn() };
+ mocks.active = { status: "error", error: "inspection failed" };
+ const view = render(<InitialDocumentLoadBridge {...props} />);
+ expect(props.onFailed).toHaveBeenCalledOnce();
+ mocks.active = { status: "loading", error: null };
+ view.rerender(<InitialDocumentLoadBridge {...props} />);
+ expect(props.onReady).not.toHaveBeenCalled();
+ mocks.active = { status: "loaded", error: null };
+ view.rerender(<InitialDocumentLoadBridge {...props} />);
+ view.rerender(<InitialDocumentLoadBridge {...props} />);
+ expect(props.onReady).toHaveBeenCalledExactlyOnceWith("B");
+ expect(props.onFailed).toHaveBeenCalledOnce();
+ });
+
it("rejects an initial load when only the inner viewer unmounts", async () => {
const { result } = renderHook(useDocumentLoadWaiter);
const saved = result.current.waitForDocument("B");
diff --git a/frontend/editor/src/core/components/viewer/pdfViewerAccess.test.ts b/frontend/editor/src/core/components/viewer/pdfViewerAccess.test.ts
new file mode 100644
index 0000000000..ec3b8c1407
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/pdfViewerAccess.test.ts
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ PdfErrorCode,
+ PdfTaskHelper,
+ type PdfDocumentObject,
+ type PdfEngine,
+} from "@embedpdf/models";
+import {
+ bindPdfViewerSource,
+ withPdfViewerAccess,
+} from "@app/components/viewer/pdfViewerAccess";
+import {
+ clearPdfAccess,
+ forgetPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+ rememberPlainPdfExport,
+ ensureLocalPdfAccess,
+} from "@app/services/pdfAccessService";
+
+import { createStirlingFile } from "@app/types/fileContext";
+
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ ensureLocalPdfAccess: vi.fn(),
+}));
+const document: PdfDocumentObject = {
+ id: "opened",
+ pageCount: 1,
+ pages: [],
+ isEncrypted: false,
+ isOwnerUnlocked: true,
+ permissions: -4,
+ normalizedRotation: false,
+};
+const protectedAccess = {
+ password: "",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 4,
+ pageCount: 1,
+};
+
+function viewer(file: File) {
+ const buffer = new ArrayBuffer(8);
+ bindPdfViewerSource(buffer, file);
+ const opened = PdfTaskHelper.create<PdfDocumentObject>();
+ const close = vi.fn(() => PdfTaskHelper.resolve(true));
+ const raw = {
+ openDocumentBuffer: vi.fn(() => opened),
+ closeDocument: close,
+ };
+ const engine = withPdfViewerAccess(raw as unknown as PdfEngine<Blob>);
+ return { engine, opened, close, raw, buffer };
+}
+
+beforeEach(() => {
+ clearPdfAccess();
+ vi.mocked(ensureLocalPdfAccess).mockReset();
+});
+
+describe("viewer permission readiness", () => {
+ it("publishes verified access before opening completes without an extra read", async () => {
+ const file = new File(["PDF"], "sample.pdf");
+ const read = vi.fn();
+ Object.defineProperty(file, "arrayBuffer", { value: read });
+ const { engine, opened, raw, buffer } = viewer(file);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ const ready = vi.fn(() =>
+ expect(getPdfAccess(file)?.encrypted).toBe(false),
+ );
+ task.wait(ready, () => {});
+ expect(ready).not.toHaveBeenCalled();
+ opened.resolve(document);
+ await task.toPromise();
+ expect(ready).toHaveBeenCalledOnce();
+ expect(raw.openDocumentBuffer).toHaveBeenCalledOnce();
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ it("does not publish unrestricted access while encrypted authentication is pending", async () => {
+ const file = new File(["protected"], "large.pdf");
+ Object.defineProperty(file, "size", { value: 125 * 1024 ** 2 });
+ let finish!: (value: typeof protectedAccess) => void;
+ vi.mocked(ensureLocalPdfAccess).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = (access) => resolve(rememberPdfAccess(file, access));
+ }),
+ );
+ const { engine, opened, buffer } = viewer(file);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ const ready = vi.fn();
+ task.wait(ready, () => {});
+ opened.resolve({
+ ...document,
+ isEncrypted: true,
+ isOwnerUnlocked: false,
+ permissions: 4,
+ });
+ expect(getPdfAccess(file)).toBeUndefined();
+ expect(ready).not.toHaveBeenCalled();
+ finish(protectedAccess);
+ await task.toPromise();
+ expect(getPdfAccess(file)).toMatchObject({
+ encrypted: true,
+ ownerAuthenticated: false,
+ });
+ });
+
+ it("rejects incomplete engine security metadata instead of granting access", async () => {
+ const file = new File(["PDF"], "sample.pdf");
+ const { engine, opened, close, buffer } = viewer(file);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ const rejected = expect(task.toPromise()).rejects.toBeDefined();
+ opened.resolve({
+ ...document,
+ isEncrypted: undefined,
+ } as unknown as PdfDocumentObject);
+ await rejected;
+ expect(getPdfAccess(file)).toBeUndefined();
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it("preserves PDFium password errors for the shared password prompt", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const { engine, opened, buffer } = viewer(file);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ const rejected = expect(task.toPromise()).rejects.toMatchObject({
+ reason: { code: PdfErrorCode.Password },
+ });
+ opened.reject({
+ code: PdfErrorCode.Password,
+ message: "Password required",
+ });
+ await rejected;
+ expect(getPdfAccess(file)).toBeUndefined();
+ });
+
+ it("keeps ordinary exports ready through new FileContext identities without granting access to unrelated bytes", async () => {
+ const source = new File(["original"], "sample.pdf");
+ const { engine, opened, buffer } = viewer(source);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ opened.resolve(document);
+ await task.toPromise();
+ const saved = new File(["saved"], "sample.pdf");
+ rememberPlainPdfExport(source, saved);
+ const assigned = createStirlingFile(saved);
+ expect(getPdfAccess(assigned.fileId)?.encrypted).toBe(false);
+ expect(getPdfAccess(new File(["saved"], "sample.pdf"))).toBeUndefined();
+ rememberPdfAccess(source, protectedAccess);
+ const protectedOutput = new File(["changed"], "sample.pdf");
+ rememberPlainPdfExport(source, protectedOutput);
+ expect(getPdfAccess(protectedOutput)).toBeUndefined();
+ });
+
+ it.each(["close", "logout"])(
+ "does not restore access after %s while PDFium is opening",
+ async (action) => {
+ const file = createStirlingFile(new File(["PDF"], "sample.pdf"));
+ const { engine, opened, close, buffer } = viewer(file);
+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });
+ const rejected = expect(task.toPromise()).rejects.toBeDefined();
+ if (action === "close") forgetPdfAccess([file.fileId]);
+ else clearPdfAccess();
+ opened.resolve(document);
+ await rejected;
+ expect(getPdfAccess(file)).toBeUndefined();
+ expect(close).toHaveBeenCalledOnce();
+ },
+ );
+});
diff --git a/frontend/editor/src/core/components/viewer/pdfViewerAccess.ts b/frontend/editor/src/core/components/viewer/pdfViewerAccess.ts
new file mode 100644
index 0000000000..5c8c60ed8e
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/pdfViewerAccess.ts
@@ -0,0 +1,121 @@
+import {
+ PdfErrorCode,
+ PdfTaskHelper,
+ TaskStage,
+ type PdfDocumentObject,
+ type PdfEngine,
+} from "@embedpdf/models";
+import {
+ pdfAccessLifetime,
+ rememberUnencryptedPdf,
+ ensureLocalPdfAccess,
+} from "@app/services/pdfAccessService";
+
+const sources = new WeakMap<ArrayBuffer, Blob>();
+
+/** Associate the viewer's existing byte read with its exact FileContext source before worker transfer. */
+export function bindPdfViewerSource(buffer: ArrayBuffer, source: Blob): void {
+ sources.set(buffer, source);
+}
+
+/** Resolve access before publishing a document; encrypted sources without cached access need local inspection. */
+export function withPdfViewerAccess(engine: PdfEngine<Blob>): PdfEngine<Blob> {
+ const open: PdfEngine<Blob>["openDocumentBuffer"] = (file, options) => {
+ const source = sources.get(file.content);
+ if (!source)
+ return PdfTaskHelper.reject({
+ code: PdfErrorCode.Security,
+ message: "Unable to identify the PDF being opened.",
+ });
+ const generation = pdfAccessLifetime(source);
+ const task = PdfTaskHelper.create<PdfDocumentObject>();
+ const cancellation = new AbortController();
+ const opening = engine.openDocumentBuffer(file, options);
+ const isCurrent = () =>
+ task.state.stage === TaskStage.Pending &&
+ generation === pdfAccessLifetime(source);
+ task.wait(
+ () => {},
+ (error) => {
+ if (error.type === "abort") {
+ cancellation.abort();
+ opening.abort(error.reason);
+ }
+ },
+ );
+ opening.wait(
+ (document) => {
+ const close = () => {
+ engine.closeDocument(document).wait(
+ () => {},
+ () => {},
+ );
+ };
+ if (!isCurrent()) {
+ close();
+ task.abort({
+ code: PdfErrorCode.Cancelled,
+ message: "PDF opening cancelled.",
+ });
+ return;
+ }
+ if (
+ typeof document.isEncrypted !== "boolean" ||
+ !Number.isInteger(document.permissions)
+ ) {
+ close();
+ task.reject({
+ code: PdfErrorCode.Security,
+ message: "Unable to verify PDF security.",
+ });
+ return;
+ }
+ if (!document.isEncrypted) {
+ rememberUnencryptedPdf(source, document.pageCount);
+ task.resolve(document);
+ return;
+ }
+ void ensureLocalPdfAccess(
+ source,
+ cancellation.signal,
+ options?.password,
+ ).then(
+ (access) => {
+ if (!isCurrent()) {
+ close();
+ task.abort({
+ code: PdfErrorCode.Cancelled,
+ message: "PDF opening cancelled.",
+ });
+ } else if (!access.encrypted) {
+ close();
+ task.reject({
+ code: PdfErrorCode.Security,
+ message: "Unable to verify PDF security.",
+ });
+ } else {
+ task.resolve(document);
+ }
+ },
+ () => {
+ close();
+ task.reject({
+ code: PdfErrorCode.Security,
+ message:
+ "Unable to verify PDF security. Try opening the file again.",
+ });
+ },
+ );
+ },
+ (error) => task.fail(error),
+ );
+ return task;
+ };
+ return new Proxy(engine, {
+ get(target, property) {
+ if (property === "openDocumentBuffer") return open;
+ const value = Reflect.get(target, property, target);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+}
diff --git a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx b/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
index 91beab4d39..30794ce0a2 100644
--- a/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
+++ b/frontend/editor/src/core/contexts/AppConfigContext.test.tsx
@@ -9,6 +9,11 @@ import { allowConsole, expectConsole } from "@app/tests/failOnConsole";
import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode } from "react";
+import {
+ getPdfAccess,
+ rememberPdfAccess,
+ clearPdfAccess,
+} from "@app/services/pdfAccessService";
// Mock apiClient
vi.mock("@app/services/apiClient");
@@ -33,6 +38,33 @@ describe("AppConfigContext", () => {
</TestQueryProvider>
);
+ it("applies server owner policy to cached access and enforces restrictions after provider teardown", async () => {
+ vi.mocked(apiClient.get).mockResolvedValue({
+ data: { honorOwnerPasswords: false },
+ });
+ const file = new File(["PDF"], "restricted.pdf");
+ rememberPdfAccess(file, {
+ password: "",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ pageCount: 1,
+ });
+ const { result, unmount } = renderHook(() => useAppConfig(), { wrapper });
+ try {
+ await waitFor(() =>
+ expect(result.current.config?.honorOwnerPasswords).toBe(false),
+ );
+ expect(getPdfAccess(file)?.honorOwnerPasswords).toBe(false);
+ unmount();
+ expect(getPdfAccess(file)?.honorOwnerPasswords).toBe(true);
+ } finally {
+ unmount();
+ clearPdfAccess();
+ }
+ });
+
it("should fetch and provide app config on non-auth pages", async () => {
const mockConfig = {
enableLogin: false,
diff --git a/frontend/editor/src/core/contexts/AppConfigContext.tsx b/frontend/editor/src/core/contexts/AppConfigContext.tsx
index c9c5a514a5..de96160718 100644
--- a/frontend/editor/src/core/contexts/AppConfigContext.tsx
+++ b/frontend/editor/src/core/contexts/AppConfigContext.tsx
@@ -3,6 +3,7 @@ import React, {
useContext,
useMemo,
useEffect,
+ useLayoutEffect,
useCallback,
useState,
ReactNode,
@@ -14,6 +15,7 @@ import i18n from "i18next";
import { CONFIG_STALE_TIME } from "@app/query/staleTime";
import type { AppConfig, AppConfigBootstrapMode } from "@app/types/appConfig";
import { useJwtConfigSync } from "@app/hooks/useJwtConfigSync";
+import { setPdfAccessPolicy } from "@app/services/pdfAccessService";
export interface AppConfigRetryOptions {
maxRetries?: number;
@@ -163,6 +165,12 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
refetch,
]);
+ useLayoutEffect(() => {
+ setPdfAccessPolicy(value.config?.honorOwnerPasswords !== false);
+ }, [value.config?.honorOwnerPasswords]);
+
+ useLayoutEffect(() => () => setPdfAccessPolicy(true), []);
+
return (
<AppConfigContext.Provider value={value}>
{children}
diff --git a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
index fd4f90efbf..665b90ceb7 100644
--- a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
@@ -18,10 +18,11 @@ import {
getPdfAccess,
rememberPdfAccess,
bindPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
import { fileStorage } from "@app/services/fileStorage";
import { generateProcessedFileMetadata } from "@app/contexts/file/fileActions";
+import { generateThumbnailPairWithMetadata } from "@app/utils/thumbnailUtils";
import {
createStirlingFile,
createNewStirlingFileStub,
@@ -35,12 +36,30 @@ import {
const observed = vi.hoisted(() => ({
isEncrypted: true,
+ requiresOpeningPassword: true as boolean | undefined,
heldBeforeEffects: false,
afterDispatch: undefined as (() => Promise<void>) | undefined,
+ thumbnailUrl: undefined as string | undefined,
}));
const id = "editor-encrypted" as FileId;
+const localInspection = vi.hoisted(() => vi.fn());
+
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ inspectLocalPdfAccess: async (
+ file: File,
+ password: string,
+ signal?: AbortSignal,
+ ) => ({
+ ...(await localInspection(file, password, signal)).data,
+ password,
+ }),
+}));
vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: vi.fn(),
+}));
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => null,
@@ -69,6 +88,7 @@ vi.mock("@app/components/shared/EncryptedPdfUnlockModal", () => ({
errorMessage,
password,
onPasswordChange,
+ inspection,
}: {
opened: boolean;
onSkip: () => void;
@@ -78,20 +98,34 @@ vi.mock("@app/components/shared/EncryptedPdfUnlockModal", () => ({
errorMessage?: string | null;
password: string;
onPasswordChange: (password: string) => void;
+ inspection?: { error?: string; retry: () => void };
}) =>
opened ? (
<>
<button onClick={onSkip}>Cancel opening</button>
- <input
- aria-label={ownerUnlock ? "Permissions password" : "PDF password"}
- value={password}
- onChange={(event) => onPasswordChange(event.target.value)}
- />
- <button onClick={onUnlock}>Unlock</button>
- {!ownerUnlock && onRemovePassword && (
- <button onClick={onRemovePassword}>Remove Password</button>
+ {inspection ? (
+ <>
+ <span role={inspection.error ? "alert" : "status"}>
+ {inspection.error ?? "Checking permissions"}
+ </span>
+ {inspection.error && (
+ <button onClick={inspection.retry}>Retry inspection</button>
+ )}
+ </>
+ ) : (
+ <>
+ <input
+ aria-label={ownerUnlock ? "Permissions password" : "PDF password"}
+ value={password}
+ onChange={(event) => onPasswordChange(event.target.value)}
+ />
+ <button onClick={onUnlock}>Unlock</button>
+ {!ownerUnlock && onRemovePassword && (
+ <button onClick={onRemovePassword}>Remove Password</button>
+ )}
+ {errorMessage && <span role="alert">{errorMessage}</span>}
+ </>
)}
- {errorMessage && <span role="alert">{errorMessage}</span>}
</>
) : null,
}));
@@ -117,7 +151,12 @@ vi.mock("@app/contexts/file/fileActions", async (importOriginal) => {
isLeaf: true,
originalFileId: id,
versionNumber: 1,
- processedFile: { pages: [], isEncrypted: observed.isEncrypted },
+ thumbnailUrl: observed.thumbnailUrl,
+ processedFile: {
+ pages: [],
+ isEncrypted: observed.isEncrypted,
+ requiresOpeningPassword: observed.requiresOpeningPassword,
+ },
};
filesRef.current.set(id, file);
dispatch({ type: "ADD_FILES", payload: { stirlingFileStubs: [stub] } });
@@ -139,17 +178,205 @@ function wrapper({ children }: { children: ReactNode }) {
beforeEach(() => {
vi.mocked(apiClient.post).mockReset();
+ localInspection.mockReset();
vi.mocked(generateProcessedFileMetadata).mockResolvedValue({
pages: [],
totalPages: 1,
isEncrypted: false,
});
observed.isEncrypted = true;
+ observed.requiresOpeningPassword = true;
observed.heldBeforeEffects = false;
observed.afterDispatch = undefined;
+ observed.thumbnailUrl = undefined;
setPendingUnlocks([]);
});
+describe("deferred opening inspection", () => {
+ it.each([false, true])(
+ "hydrates page geometry after admission without losing its thumbnail, closed: %s",
+ async (closed) => {
+ observed.requiresOpeningPassword = undefined;
+ observed.thumbnailUrl = "data:image/png;base64,existing";
+ localInspection.mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ pageCount: 1,
+ requiresOpeningPassword: false,
+ },
+ });
+ let finish!: (
+ metadata: Awaited<ReturnType<typeof generateThumbnailPairWithMetadata>>,
+ ) => void;
+ vi.mocked(generateThumbnailPairWithMetadata).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ const file = new File(["encrypted"], "rotated.pdf", {
+ type: "application/pdf",
+ });
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([file]);
+ });
+ await expect(loading).resolves.toEqual([file]);
+ expect(
+ result.current.selectors.getStirlingFileStub(id)?.thumbnailUrl,
+ ).toBe(observed.thumbnailUrl);
+ await waitFor(() => expect(finish).toBeDefined());
+ if (closed)
+ await act(() => result.current.actions.removeFiles([id], false));
+ const metadata = {
+ thumbnail: "data:image/png;base64,new",
+ pageCount: 1,
+ pageRotations: [90],
+ pageDimensions: [{ width: 600, height: 800 }],
+ isEncrypted: false,
+ };
+ await act(async () => finish({ unrotated: metadata, rotated: metadata }));
+ if (closed) expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ else
+ expect(result.current.selectors.getStirlingFileStub(id)).toMatchObject({
+ thumbnailUrl: observed.thumbnailUrl,
+ processedFile: {
+ isEncrypted: true,
+ requiresOpeningPassword: false,
+ pages: [{ rotation: 90, width: 600, height: 800 }],
+ },
+ });
+ },
+ );
+ it("cancels a pending check without admitting its late result", async () => {
+ observed.requiresOpeningPassword = undefined;
+ let finish!: (value: unknown) => void;
+ localInspection.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ const file = new File(["encrypted"], "pending.pdf");
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([file]);
+ });
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "Checking permissions",
+ );
+ const signal = localInspection.mock.calls[0][2] as AbortSignal;
+ await act(async () => fireEvent.click(screen.getByText("Cancel opening")));
+ expect(signal.aborted).toBe(true);
+ await expect(loading).resolves.toEqual([]);
+ await act(async () =>
+ finish({
+ data: {
+ encrypted: true,
+ pageCount: 1,
+ ownerAuthenticated: false,
+ permissions: 0,
+ signed: false,
+ },
+ }),
+ );
+ expect(getPdfAccess(file)).toBeUndefined();
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ });
+ it.each([1024, 150 * 1024 * 1024])(
+ "opens a %i-byte restriction-only PDF without asking for a password",
+ async (size) => {
+ observed.requiresOpeningPassword = undefined;
+ localInspection.mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ pageCount: 1,
+ requiresOpeningPassword: false,
+ },
+ });
+ const file = new File(["encrypted"], "restrictions.pdf");
+ Object.defineProperty(file, "size", { value: size });
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([file]);
+ });
+ await expect(loading).resolves.toEqual([file]);
+ expect(localInspection).toHaveBeenCalledExactlyOnceWith(
+ file,
+ "",
+ expect.any(AbortSignal),
+ );
+ expect(getPdfAccess(file)).toMatchObject({
+ encrypted: true,
+ ownerAuthenticated: false,
+ permissions: 0,
+ });
+ expect(screen.queryByLabelText("PDF password")).not.toBeInTheDocument();
+ },
+ );
+
+ it("keeps a timed-out inspection unresolved and supports retry", async () => {
+ observed.requiresOpeningPassword = undefined;
+ localInspection.mockRejectedValueOnce(
+ new DOMException("Inspection timed out", "TimeoutError"),
+ );
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ const file = new File(["encrypted"], "unknown.pdf");
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([file]);
+ });
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "encryptedPdfUnlock.inspectionFailed",
+ );
+ expect(screen.queryByText("Inspection timed out")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("PDF password")).not.toBeInTheDocument();
+ expect(getPdfAccess(file)).toBeUndefined();
+ localInspection.mockRejectedValueOnce(
+ Object.assign(new Error("Password required"), { code: 4 }),
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByText("Retry inspection")),
+ );
+ expect(screen.getByLabelText("PDF password")).toBeVisible();
+ await act(async () => fireEvent.click(screen.getByText("Cancel opening")));
+ await expect(loading).resolves.toEqual([]);
+ });
+
+ it("prompts directly when the opening-password requirement is already known", async () => {
+ const { result } = renderHook(() => useFileActions(), { wrapper });
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([
+ new File(["encrypted"], "known.pdf"),
+ ]);
+ });
+ expect(screen.getByLabelText("PDF password")).toBeVisible();
+ expect(localInspection).not.toHaveBeenCalled();
+ await act(async () => fireEvent.click(screen.getByText("Cancel opening")));
+ await expect(loading).resolves.toEqual([]);
+ });
+});
+
describe("protected tool replacements", () => {
beforeEach(() => {
observed.isEncrypted = false;
@@ -173,6 +400,7 @@ describe("protected tool replacements", () => {
const stub = createNewStirlingFileStub(output, output.fileId, undefined, {
pages: [],
isEncrypted: true,
+ requiresOpeningPassword: true,
});
let consuming!: ReturnType<typeof result.current.actions.consumeFiles>;
await act(async () => {
@@ -194,14 +422,12 @@ describe("protected tool replacements", () => {
await expect(consuming).resolves.toEqual([]);
return;
}
- vi.mocked(apiClient.post).mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
encrypted: true,
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
},
});
@@ -242,20 +468,19 @@ describe("protected tool replacements", () => {
createNewStirlingFileStub(file, file.fileId, undefined, {
pages: [],
isEncrypted: true,
+ requiresOpeningPassword: true,
}),
);
let consuming!: ReturnType<typeof result.current.actions.consumeFiles>;
await act(async () => {
consuming = result.current.actions.consumeFiles([id], outputs, stubs);
});
- vi.mocked(apiClient.post).mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
encrypted: true,
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
},
});
@@ -296,6 +521,68 @@ afterEach(() => {
});
describe("encrypted bytes opened by another editor", () => {
+ it.each([false, true])(
+ "requires owner authentication without cached access, cancelled: %s",
+ async (cancelled) => {
+ observed.isEncrypted = false;
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ await act(() =>
+ result.current.actions.addFiles([new File(["original"], "locked.pdf")]),
+ );
+ let permitted!: Promise<boolean>;
+ act(() => {
+ permitted = result.current.actions.requestPdfOwnerAccess(
+ id,
+ "Change permissions",
+ );
+ });
+ if (cancelled) {
+ await act(async () =>
+ fireEvent.click(screen.getByText("Cancel opening")),
+ );
+ await expect(permitted).resolves.toBe(false);
+ expect(result.current.selectors.getAllFileIds()).toEqual([id]);
+ expect(getPdfAccess(id)).toBeUndefined();
+ return;
+ }
+ localInspection.mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ pageCount: 1,
+ },
+ });
+ fireEvent.change(screen.getByLabelText("Permissions password"), {
+ target: { value: "reader" },
+ });
+ await act(async () => fireEvent.click(screen.getByText("Unlock")));
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "encryptedPdfUnlock.ownerRequired",
+ );
+ expect(getPdfAccess(id)).toBeUndefined();
+ localInspection.mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: 0,
+ pageCount: 1,
+ },
+ });
+ fireEvent.change(screen.getByLabelText("Permissions password"), {
+ target: { value: "owner" },
+ });
+ await act(async () => fireEvent.click(screen.getByText("Unlock")));
+ await expect(permitted).resolves.toBe(true);
+ expect(getPdfAccess(id)?.password).toBe("owner");
+ },
+ );
+
it.each([false, true])(
"removes the opening password while retaining owner protection: %s",
async (hasOwnerPassword) => {
@@ -317,15 +604,12 @@ describe("encrypted bytes opened by another editor", () => {
openingAuthenticated: true,
ownerAuthenticated: !hasOwnerPassword,
requiresOpeningPassword: true,
- hasOwnerPassword,
permissions: hasOwnerPassword ? 0 : -4,
- canModify: !hasOwnerPassword,
- canAssemble: !hasOwnerPassword,
pageCount: 1,
};
const post = vi.mocked(apiClient.post);
post.mockReset();
- post.mockResolvedValueOnce({ data: security });
+ localInspection.mockResolvedValueOnce({ data: security });
if (hasOwnerPassword) {
fireEvent.change(screen.getByLabelText("PDF password"), {
target: { value: "reader" },
@@ -334,10 +618,10 @@ describe("encrypted bytes opened by another editor", () => {
fireEvent.click(screen.getByText("Remove Password"));
});
expect(screen.getByLabelText("Permissions password")).toBeVisible();
- expect(post).toHaveBeenCalledTimes(1);
+ expect(post).not.toHaveBeenCalled();
expect(getPdfAccess(original)).toBeUndefined();
expect(result.current.selectors.getAllFileIds()).toEqual([]);
- post.mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
...security,
openingAuthenticated: false,
@@ -346,7 +630,7 @@ describe("encrypted bytes opened by another editor", () => {
});
}
post.mockResolvedValueOnce({ data: new Blob(["password removed"]) });
- post.mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
...security,
encrypted: hasOwnerPassword,
@@ -359,7 +643,9 @@ describe("encrypted bytes opened by another editor", () => {
screen.getByLabelText(
hasOwnerPassword ? "Permissions password" : "PDF password",
),
- { target: { value: hasOwnerPassword ? "owner" : "reader" } },
+ {
+ target: { value: hasOwnerPassword ? "owner" : "reader" },
+ },
);
await act(async () => {
fireEvent.click(
@@ -376,7 +662,7 @@ describe("encrypted bytes opened by another editor", () => {
permissions: security.permissions,
});
const request = post.mock.calls.find(
- ([url]) => url === "/api/v1/security/remove-pdf-passwords",
+ ([url]) => url === "/api/v1/security/remove-password",
)!;
const form = request[1] as FormData;
expect(form.get("password")).toBe("reader");
@@ -409,23 +695,20 @@ describe("encrypted bytes opened by another editor", () => {
openingAuthenticated: true,
ownerAuthenticated: false,
requiresOpeningPassword: true,
- hasOwnerPassword: true,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
honorOwnerPasswords: false,
};
const post = vi.mocked(apiClient.post);
post.mockReset();
- post.mockResolvedValueOnce({ data: security });
+ localInspection.mockResolvedValueOnce({ data: security });
fireEvent.change(screen.getByLabelText("PDF password"), {
target: { value: "reader" },
});
await act(async () => {
fireEvent.click(screen.getByText("Remove Password"));
});
- post.mockResolvedValueOnce({ data: security });
+ localInspection.mockResolvedValueOnce({ data: security });
fireEvent.change(screen.getByLabelText("Permissions password"), {
target: { value: "reader" },
});
@@ -435,11 +718,7 @@ describe("encrypted bytes opened by another editor", () => {
expect(screen.getByRole("alert")).toHaveTextContent(
"encryptedPdfUnlock.ownerRequired",
);
- expect(
- post.mock.calls.every(
- ([url]) => url === "/api/v1/security/inspect-pdf-security",
- ),
- ).toBe(true);
+ expect(post).not.toHaveBeenCalled();
await act(async () => {
fireEvent.click(screen.getByText("Cancel opening"));
await loading;
@@ -474,23 +753,20 @@ describe("encrypted bytes opened by another editor", () => {
signed: false,
ownerAuthenticated: true,
permissions: 0,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
- vi.mocked(apiClient.post)
- .mockResolvedValueOnce({ data: new Blob(["unprotected"]) })
- .mockResolvedValueOnce({
- data: {
- encrypted: false,
- signed: false,
- ownerAuthenticated: false,
- permissions: -4,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- });
+ vi.mocked(apiClient.post).mockResolvedValueOnce({
+ data: new Blob(["unprotected"]),
+ });
+ localInspection.mockResolvedValueOnce({
+ data: {
+ encrypted: false,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: -4,
+ pageCount: 1,
+ },
+ });
await act(async () =>
result.current.actions.createUnprotectedCopy(file.fileId),
);
@@ -526,8 +802,6 @@ describe("encrypted bytes opened by another editor", () => {
signed: false,
ownerAuthenticated: false,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
});
let pending!: Promise<boolean>;
@@ -578,14 +852,12 @@ describe("encrypted bytes opened by another editor", () => {
expect(result.current.selectors.getAllFileIds()).toEqual([]);
});
it("unlocks the original in place without adding a password-removal version", async () => {
- vi.mocked(apiClient.post).mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
encrypted: true,
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
},
});
@@ -617,9 +889,7 @@ describe("encrypted bytes opened by another editor", () => {
});
expect(getPdfAccess(id)?.password).toBe(" secret ");
expect(isAwaitingUnlock(id)).toBe(false);
- expect(vi.mocked(apiClient.post).mock.calls.at(-1)?.[0]).toBe(
- "/api/v1/security/inspect-pdf-security",
- );
+ expect(apiClient.post).not.toHaveBeenCalled();
await act(() => result.current.actions.removeFiles([id]));
expect(getPdfAccess(original)).toBeUndefined();
});
@@ -664,7 +934,7 @@ describe("encrypted bytes opened by another editor", () => {
});
it("a rejected password leaves the file pending until cancelled", async () => {
- vi.mocked(apiClient.post).mockRejectedValueOnce(new Error("bad password"));
+ localInspection.mockRejectedValueOnce(new Error("bad password"));
const { result } = renderHook(
() => ({ ...useFileActions(), selectors: useFileSelectors() }),
{ wrapper },
@@ -699,14 +969,12 @@ describe("preview session credentials", () => {
signed: false,
ownerAuthenticated: false,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
};
afterEach(cleanup);
it("unlocks without publishing or persisting a file, then forgets access on close", async () => {
- vi.mocked(apiClient.post).mockResolvedValueOnce({ data: previewSecurity });
+ localInspection.mockResolvedValueOnce({ data: previewSecurity });
const { result } = renderHook(
() => ({ ...useFileActions(), selectors: useFileSelectors() }),
{ wrapper },
@@ -733,7 +1001,7 @@ describe("preview session credentials", () => {
it("does not retain a password when authentication finishes after the preview closes", async () => {
let finish!: (response: { data: typeof previewSecurity }) => void;
- vi.mocked(apiClient.post).mockReturnValueOnce(
+ localInspection.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
}),
@@ -756,14 +1024,12 @@ describe("preview session credentials", () => {
});
it("preserves a preview credential after its bytes are admitted to FileContext", async () => {
- vi.mocked(apiClient.post).mockResolvedValueOnce({
+ localInspection.mockResolvedValueOnce({
data: {
encrypted: true,
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
},
});
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index b2d8f41b95..c458a9bc1e 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -16,6 +16,7 @@ import {
useReducer,
useCallback,
useEffect,
+ useEffectEvent,
useLayoutEffect,
useRef,
useMemo,
@@ -48,7 +49,9 @@ import {
undoConsumeFiles,
createFileActions,
createChildStub,
+ createProcessedFile,
generateProcessedFileMetadata,
+ hydrateMetadataFor,
} from "@app/contexts/file/fileActions";
import { FileLifecycleManager } from "@app/contexts/file/lifecycle";
import {
@@ -60,25 +63,25 @@ import {
IndexedDBProvider,
useIndexedDB,
} from "@app/contexts/IndexedDBContext";
-import { onRecordUnreadable } from "@app/services/fileStorage";
+import { fileStorage, onRecordUnreadable } from "@app/services/fileStorage";
import { useZipConfirmation } from "@app/hooks/useZipConfirmation";
import ZipWarningModal from "@app/components/shared/ZipWarningModal";
import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";
import { useTranslation } from "react-i18next";
-import { alert } from "@app/components/toast";
-import {
- hasPdfPermissionOverride,
- unlockPdfForSession,
-} from "@app/services/pdfSessionUnlock";
import {
+ inspectLocalPdfAccess,
bindPdfAccess,
clearPdfAccess,
forgetPdfAccess,
forgetPreviewPdfAccess,
getPdfAccess,
+ pdfAccessLifetime,
rememberPdfAccess,
type PdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
+import { alert } from "@app/components/toast";
+import { hasPdfPermissionOverride } from "@app/services/pdfPermissions";
+
import { reportFilesRemoved } from "@app/services/failureReporting";
import {
addPendingUnlocks,
@@ -87,6 +90,7 @@ import {
import { handlePasswordError } from "@app/utils/toolErrorHandler";
import apiClient from "@app/services/apiClient";
import { buildRemovePasswordFormData } from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";
+import { combineAbortSignals } from "@app/utils/combineAbortSignals";
// Inner provider component that has access to IndexedDB
function FileContextInner({
@@ -134,6 +138,11 @@ function FileContextInner({
useState<FileId | null>(null);
const [unlockPassword, setUnlockPassword] = useState("");
const [unlockError, setUnlockError] = useState<string | null>(null);
+ const [openingInspection, setOpeningInspection] = useState<{
+ fileId: FileId;
+ error?: string;
+ } | null>(null);
+ const [inspectionAttempt, setInspectionAttempt] = useState(0);
const [isUnlocking, setIsUnlocking] = useState(false);
const [openingPasswordToRemove, setOpeningPasswordToRemove] = useState<
string | null
@@ -371,10 +380,14 @@ function FileContextInner({
// for the rest of the session. Its own effect, so a change of prompt does not clear and re-set.
useEffect(() => () => setPendingUnlocks([]), []);
+ const protectionOperation = useRef<AbortController | null>(null);
useEffect(() => {
setUnlockPassword("");
setUnlockError(null);
setOpeningPasswordToRemove(null);
+ const cancellation = new AbortController();
+ protectionOperation.current = cancellation;
+ return () => cancellation.abort();
}, [activeEncryptedFileId]);
// Storage proved a file's bytes unreadable (WebKit losing a blob's backing
@@ -393,10 +406,12 @@ function FileContextInner({
);
const handleUnlockSkip = useCallback(() => {
+ protectionOperation.current?.abort();
if (activeEncryptedFileId) {
- ownerRequests.current.get(activeEncryptedFileId)?.resolve(false);
+ const ownerRequest = ownerRequests.current.get(activeEncryptedFileId);
+ ownerRequest?.resolve(false);
ownerRequests.current.delete(activeEncryptedFileId);
- if (getPdfAccess(activeEncryptedFileId)) {
+ if (ownerRequest || getPdfAccess(activeEncryptedFileId)) {
setActiveEncryptedFileId(null);
return;
}
@@ -623,8 +638,29 @@ function FileContextInner({
[dispatchWithUnlock, awaitAdmissions],
);
+ const pendingMetadataHydrations = useRef(new Set<FileId>());
+ useEffect(() => {
+ for (const fileId of pendingMetadataHydrations.current) {
+ const file = filesRef.current.get(fileId);
+ if (!file) pendingMetadataHydrations.current.delete(fileId);
+ else if (state.files.byId[fileId]) {
+ pendingMetadataHydrations.current.delete(fileId);
+ hydrateMetadataFor(
+ fileId,
+ createStirlingFile(file, fileId),
+ stateRef,
+ lifecycleManager,
+ );
+ }
+ }
+ }, [state.files, lifecycleManager]);
+
const runSessionUnlock = useCallback(
- async (fileId: FileId, password: string): Promise<void> => {
+ async (
+ fileId: FileId,
+ password: string,
+ signal?: AbortSignal,
+ ): Promise<void> => {
const file = filesRef.current.get(fileId);
const pending = pendingAdmissions.current.get(fileId);
const parentStub = pending?.stub ?? stateRef.current.files.byId[fileId];
@@ -638,11 +674,14 @@ function FileContextInner({
);
}
- const access = await unlockPdfForSession(file, password);
- if (filesRef.current.get(fileId) !== file) {
+ const access = await inspectLocalPdfAccess(file, password, signal);
+ if (signal?.aborted || filesRef.current.get(fileId) !== file) {
return;
}
- if (getPdfAccess(file)?.encrypted && !access.ownerAuthenticated) {
+ if (
+ (ownerRequests.current.has(fileId) || getPdfAccess(file)?.encrypted) &&
+ !access.ownerAuthenticated
+ ) {
throw new Error(
t(
"encryptedPdfUnlock.ownerRequired",
@@ -652,17 +691,24 @@ function FileContextInner({
}
rememberPdfAccess(file, access);
bindPdfAccess(file, fileId);
- const metadata = await generateProcessedFileMetadata(file);
- if (filesRef.current.get(fileId) !== file) return;
+ const metadata =
+ password === ""
+ ? createProcessedFile(access.pageCount)
+ : await generateProcessedFileMetadata(file);
+ if (signal?.aborted || filesRef.current.get(fileId) !== file) return;
const updates: Partial<StirlingFileStub> = {
processedFile: {
...metadata,
pages: metadata?.pages ?? [],
totalPages: access.pageCount,
isEncrypted: access.encrypted,
+ requiresOpeningPassword: access.requiresOpeningPassword,
},
- thumbnailUrl: metadata?.thumbnailUrl,
+ ...(metadata?.thumbnailUrl !== undefined
+ ? { thumbnailUrl: metadata.thumbnailUrl }
+ : {}),
};
+ if (password === "") pendingMetadataHydrations.current.add(fileId);
if (pending) {
pending.stub = { ...parentStub, ...updates };
if (pending.publishOnUnlock)
@@ -684,6 +730,61 @@ function FileContextInner({
[t],
);
+ const inspectOpening = useEffectEvent(
+ (fileId: FileId, controller: AbortController) => {
+ if (getPdfAccess(fileId) || ownerRequests.current.has(fileId)) return;
+ const pending = pendingAdmissions.current.get(fileId);
+ const stub = pending?.stub ?? stateRef.current.files.byId[fileId];
+ if (!stub || stub.processedFile?.requiresOpeningPassword === true) return;
+ protectionOperation.current = controller;
+ setOpeningInspection({ fileId });
+ // Only the file being opened is parsed; library admission never allocates a PDF heap.
+ void runSessionUnlock(fileId, "", controller.signal)
+ .then(() => {
+ if (!controller.signal.aborted) {
+ setOpeningInspection(null);
+ setActiveEncryptedFileId(null);
+ }
+ })
+ .catch((error: unknown) => {
+ if (controller.signal.aborted) return;
+ if (error instanceof Error && "code" in error && error.code === 4) {
+ const processedFile = {
+ ...stub.processedFile,
+ pages: stub.processedFile?.pages ?? [],
+ requiresOpeningPassword: true,
+ };
+ if (pending) pending.stub = { ...pending.stub, processedFile };
+ else
+ dispatch({
+ type: "UPDATE_FILE_RECORD",
+ payload: { id: fileId, updates: { processedFile } },
+ });
+ if (enablePersistence)
+ void fileStorage
+ .updateFileMetadata(fileId, { requiresOpeningPassword: true })
+ .catch(() => {});
+ setOpeningInspection(null);
+ } else {
+ setOpeningInspection({
+ fileId,
+ error: t(
+ "encryptedPdfUnlock.inspectionFailed",
+ "Unable to check this PDF's permissions. Try again.",
+ ),
+ });
+ }
+ });
+ },
+ );
+
+ useEffect(() => {
+ if (!activeEncryptedFileId) return;
+ const controller = new AbortController();
+ inspectOpening(activeEncryptedFileId, controller);
+ return () => controller.abort();
+ }, [activeEncryptedFileId, inspectionAttempt]);
+
const admitProtectionCopy = useCallback(
async (fileId: FileId, file: File, copy: File, copyAccess: PdfAccess) => {
const pending = pendingAdmissions.current.get(fileId);
@@ -751,9 +852,14 @@ function FileContextInner({
"The selected file is no longer available.",
),
);
+ const form = buildRemovePasswordFormData(
+ { password: access.password },
+ file,
+ );
+ form.set("removeAll", "true");
const response = await apiClient.post<Blob>(
- "/api/v1/security/remove-pdf-protection",
- buildRemovePasswordFormData({ password: access.password }, file),
+ "/api/v1/security/remove-password",
+ form,
{ responseType: "blob", suppressErrorToast: true },
);
if (filesRef.current.get(fileId) !== file) return;
@@ -762,7 +868,11 @@ function FileContextInner({
`${file.name.replace(/\.pdf$/i, "")}_unprotected.pdf`,
{ type: "application/pdf" },
);
- const copyAccess = await unlockPdfForSession(copy, "");
+ const copyAccess = await inspectLocalPdfAccess(
+ copy,
+ "",
+ pdfAccessLifetime(file),
+ );
if (copyAccess.encrypted)
throw new Error(
t(
@@ -785,18 +895,17 @@ function FileContextInner({
if (!file) return;
setIsUnlocking(true);
setUnlockError(null);
+ const { signal, dispose } = combineAbortSignals([
+ pdfAccessLifetime(file),
+ ...(protectionOperation.current
+ ? [protectionOperation.current.signal]
+ : []),
+ ]);
try {
- const access = await unlockPdfForSession(file, unlockPassword);
+ const access = await inspectLocalPdfAccess(file, unlockPassword, signal);
if (filesRef.current.get(fileId) !== file) return;
if (openingPasswordToRemove === null) {
- if (!access.requiresOpeningPassword || !access.openingAuthenticated)
- throw new Error(
- t(
- "encryptedPdfUnlock.openingRequired",
- "Enter the password used to open this PDF.",
- ),
- );
- if (access.hasOwnerPassword !== false && !access.ownerAuthenticated) {
+ if (!access.ownerAuthenticated) {
setOpeningPasswordToRemove(unlockPassword);
setUnlockPassword("");
return;
@@ -816,9 +925,9 @@ function FileContextInner({
// Authentication retains the owner password; ownerPassword would select it for removal.
form.set("sourcePassword", access.password);
const response = await apiClient.post<Blob>(
- "/api/v1/security/remove-pdf-passwords",
+ "/api/v1/security/remove-password",
form,
- { responseType: "blob", suppressErrorToast: true },
+ { responseType: "blob", suppressErrorToast: true, signal },
);
if (filesRef.current.get(fileId) !== file) return;
const copy = new File(
@@ -826,23 +935,11 @@ function FileContextInner({
`${file.name.replace(/\.pdf$/i, "")}_password_removed.pdf`,
{ type: "application/pdf" },
);
- const copyAccess = await unlockPdfForSession(copy, "");
- if (
- copyAccess.requiresOpeningPassword !== false ||
- (access.hasOwnerPassword !== false &&
- (!copyAccess.encrypted ||
- !copyAccess.hasOwnerPassword ||
- copyAccess.permissions !== access.permissions))
- )
- throw new Error(
- t(
- "encryptedPdfUnlock.securityChangeFailed",
- "Unable to change protection. Check the permissions password and the new security settings.",
- ),
- );
+ const copyAccess = await inspectLocalPdfAccess(copy, "", signal);
await admitProtectionCopy(fileId, file, copy, copyAccess);
setActiveEncryptedFileId(null);
} catch (error) {
+ if (signal.aborted) return;
setUnlockError(
await handlePasswordError(
error,
@@ -854,6 +951,7 @@ function FileContextInner({
),
);
} finally {
+ dispose();
setIsUnlocking(false);
}
}, [
@@ -1018,7 +1116,7 @@ function FileContextInner({
const unlockPreviewPdf = useCallback<FileContextActions["unlockPreviewPdf"]>(
async (file, password, signal) => {
if (signal.aborted) return;
- const access = await unlockPdfForSession(file, password);
+ const access = await inspectLocalPdfAccess(file, password, signal);
if (signal.aborted) return;
const storedAccess = rememberPdfAccess(file, access);
signal.addEventListener(
@@ -1249,7 +1347,9 @@ function FileContextInner({
}
ownerUnlock={
openingPasswordToRemove !== null ||
- (!!activeEncryptedFileId && !!getPdfAccess(activeEncryptedFileId))
+ (!!activeEncryptedFileId &&
+ (ownerRequests.current.has(activeEncryptedFileId) ||
+ !!getPdfAccess(activeEncryptedFileId)))
}
actionLabel={
activeEncryptedFileId
@@ -1259,6 +1359,14 @@ function FileContextInner({
opened={isUnlockModalOpen}
fileName={activeEncryptedStub?.name}
password={unlockPassword}
+ inspection={
+ openingInspection?.fileId === activeEncryptedFileId
+ ? {
+ error: openingInspection.error,
+ retry: () => setInspectionAttempt((attempt) => attempt + 1),
+ }
+ : undefined
+ }
errorMessage={unlockError}
isProcessing={isUnlocking}
remainingCount={encryptedQueue.length}
diff --git a/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts
index 4db47d63f3..6a2a2a8c83 100644
--- a/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts
+++ b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts
@@ -2,25 +2,29 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { FileContextState } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
+import { createNewStirlingFileStub } from "@app/types/fileContext";
+import { expectConsole } from "@app/tests/failOnConsole";
// A bulk import the user is not looking at (the onboarding Downloads sweep) must not
// parse every PDF a second time for a thumbnail, nor keep hundreds of Files in memory
// for the rest of the session. skipMetadataHydration is the option that promises both.
const storeStirlingFile = vi.hoisted(() => vi.fn());
+const getStirlingFile = vi.hoisted(() => vi.fn());
const generateThumbnailPairWithMetadata = vi.hoisted(() => vi.fn());
+const isPDFEncrypted = vi.hoisted(() => vi.fn());
vi.mock("@app/services/fileStorage", () => ({
- fileStorage: { storeStirlingFile, updateThumbnail: vi.fn() },
+ fileStorage: { storeStirlingFile, getStirlingFile, updateThumbnail: vi.fn() },
}));
vi.mock("@app/utils/thumbnailUtils", () => ({
generateThumbnailPairWithMetadata,
generateThumbnailForFile: vi.fn(),
}));
vi.mock("@app/services/fileAnalyzer", () => ({
- FileAnalyzer: { isPDFEncrypted: async () => false },
+ FileAnalyzer: { isPDFEncrypted },
}));
-import { addFiles } from "@app/contexts/file/fileActions";
+import { addFiles, addStirlingFileStubs } from "@app/contexts/file/fileActions";
function harness() {
const state = {
@@ -43,10 +47,228 @@ const pdf = (name: string) =>
beforeEach(() => {
storeStirlingFile.mockReset().mockResolvedValue(undefined);
+ getStirlingFile.mockReset();
generateThumbnailPairWithMetadata.mockReset();
+ isPDFEncrypted.mockReset().mockResolvedValue(false);
});
describe("addFiles with skipMetadataHydration", () => {
+ test.each(["import", "library"])(
+ "deduplicates against a concurrent %s before React commits",
+ async (source) => {
+ const h = harness();
+ const duplicate = pdf("duplicate.pdf");
+ let finish!: (encrypted: boolean) => void;
+ isPDFEncrypted.mockResolvedValueOnce(false).mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const importFiles = (files: File[]) =>
+ addFiles(
+ { files, skipMetadataHydration: true, skipUploadTracking: true },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ const importing = importFiles([pdf("first.pdf"), duplicate]);
+ await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
+ try {
+ if (source === "import") await importFiles([duplicate]);
+ else {
+ const stub = createNewStirlingFileStub(
+ duplicate,
+ "library-id" as FileId,
+ );
+ stub.processedFile = { pages: [], isEncrypted: true };
+ getStirlingFile.mockResolvedValue(duplicate);
+ await addStirlingFileStubs(
+ [stub],
+ {},
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ );
+ }
+ expect(h.stateRef.current.files.ids).toEqual([]);
+ } finally {
+ finish(false);
+ await importing;
+ }
+ expect(
+ [...h.filesRef.current.values()].filter(
+ (file) => file.name === duplicate.name,
+ ),
+ ).toHaveLength(1);
+ },
+ );
+
+ test.each([true, false])(
+ "waits for a pending library restore (success: %s) before deduplicating",
+ async (succeeds) => {
+ const h = harness();
+ const duplicate = pdf("duplicate.pdf");
+ const stub = createNewStirlingFileStub(duplicate, "library-id" as FileId);
+ stub.processedFile = { pages: [], isEncrypted: true };
+ let finish!: (file: File | undefined) => void;
+ getStirlingFile.mockImplementationOnce(
+ () =>
+ new Promise<File | undefined>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const restoring = addStirlingFileStubs(
+ [stub],
+ {},
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ );
+ await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
+ const importing = addFiles(
+ {
+ files: [duplicate],
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ try {
+ await vi.waitFor(() =>
+ expect(isPDFEncrypted).toHaveBeenCalledWith(duplicate),
+ );
+ await addFiles(
+ {
+ files: [pdf("other.pdf")],
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ expect(
+ [...h.filesRef.current.values()].map((file) => file.name),
+ ).toEqual(["other.pdf"]);
+ } finally {
+ if (!succeeds)
+ expectConsole.error(/No readable data for duplicate.pdf/);
+ finish(succeeds ? duplicate : undefined);
+ await restoring;
+ }
+ expect(await importing).toHaveLength(succeeds ? 0 : 1);
+ expect(
+ [...h.filesRef.current.values()].filter(
+ (file) => file.name === duplicate.name,
+ ),
+ ).toHaveLength(1);
+ },
+ );
+
+ test("still permits explicitly requested duplicates", async () => {
+ const h = harness();
+ const duplicate = pdf("duplicate.pdf");
+ await addFiles(
+ {
+ files: [duplicate, duplicate],
+ allowDuplicates: true,
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ expect(h.filesRef.current.size).toBe(2);
+ });
+
+ test("publishes the first rows before the last file's admission read finishes", async () => {
+ let finish!: (encrypted: boolean) => void;
+ isPDFEncrypted.mockImplementation((file: File) =>
+ file.name === "slow.pdf"
+ ? new Promise<boolean>((resolve) => {
+ finish = resolve;
+ })
+ : Promise.resolve(false),
+ );
+ const h = harness();
+ const importing = addFiles(
+ {
+ files: [pdf("first.pdf"), pdf("slow.pdf")],
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
+ try {
+ expect(h.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "ADD_FILES",
+ payload: {
+ stirlingFileStubs: [expect.objectContaining({ name: "first.pdf" })],
+ },
+ }),
+ );
+ } finally {
+ finish(false);
+ await importing;
+ }
+ });
+ test("a pending permission inspection does not block another import", async () => {
+ let finishInspection!: (encrypted: boolean) => void;
+ isPDFEncrypted.mockImplementation((file: File) =>
+ file.name === "slow.pdf"
+ ? new Promise<boolean>((resolve) => {
+ finishInspection = resolve;
+ })
+ : Promise.resolve(false),
+ );
+ const h = harness();
+ const importFile = (name: string) =>
+ addFiles(
+ {
+ files: [pdf(name)],
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ const slow = importFile("slow.pdf");
+ await vi.waitFor(() => expect(finishInspection).toBeTypeOf("function"));
+ try {
+ const fast = importFile("fast.pdf");
+ await vi.waitFor(() => expect(h.filesRef.current.size).toBe(1));
+ await fast;
+ expect([...h.filesRef.current.values()][0].name).toBe("fast.pdf");
+ } finally {
+ finishInspection(false);
+ await slow;
+ }
+ expect(h.filesRef.current.size).toBe(2);
+ });
+
test("writes the locked stub, parses nothing, and lets go of the bytes", async () => {
const h = harness();
await addFiles(
@@ -72,8 +294,6 @@ describe("addFiles with skipMetadataHydration", () => {
});
expect(h.dispatch).not.toHaveBeenCalled();
expect(h.filesRef.current.size).toBe(0);
- // No hydration was queued, so nothing can start parsing later either.
- await new Promise((resolve) => setTimeout(resolve, 10));
expect(generateThumbnailPairWithMetadata).not.toHaveBeenCalled();
});
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 24a215775a..defdf93d3a 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -2,7 +2,11 @@
* File actions - Unified file operations with single addFiles helper
*/
-import { bindPdfAccess, getPdfAccess } from "@app/services/pdfPasswordStore";
+import {
+ bindPdfAccess,
+ getPdfAccess,
+ pdfAccessLifetime,
+} from "@app/services/pdfAccessService";
import {
StirlingFileStub,
FileContextAction,
@@ -97,6 +101,10 @@ class SimpleMutex {
// Global mutex for addFiles operations
const addFilesMutex = new SimpleMutex();
+const libraryLoads = new Map<
+ FileId,
+ { promise: Promise<StirlingFile | undefined>; quickKey?: string }
+>();
/**
* Helper to create ProcessedFile metadata structure
@@ -319,17 +327,13 @@ export async function addFiles(
lifecycleManager: FileLifecycleManager,
enablePersistence: boolean = false,
): Promise<StirlingFile[]> {
- // Acquire mutex to prevent race conditions
- await addFilesMutex.lock();
+ let ownsImportLock = false;
try {
const stirlingFileStubs: StirlingFileStub[] = [];
const stirlingFiles: StirlingFile[] = [];
// Hydration tasks are scheduled per-file to update thumbnails/metadata without blocking add flow
- // Build quickKey lookup from existing files for deduplication
- const existingQuickKeys = buildQuickKeySet(stateRef.current.files.byId);
-
const { files = [], allowDuplicates = false } = options;
// ZIP pre-processing: Extract ZIP files with configurable behavior
@@ -404,14 +408,14 @@ export async function addFiles(
`📄 addFiles: After ZIP processing, ${filesToProcess.length} files to add`,
);
+ const importedQuickKeys = new Set<string>();
+
// Collect hydrations to schedule after dispatch so updateStirlingFileStub finds files in state.
const pendingHydrations: Array<() => Promise<void>> = [];
// Per-chunk persistence promises (kicked off as chunks flush, awaited before
// return). See flushChunk — we stream writes instead of one batch at the end.
const persistPromises: Array<Promise<unknown>> = [];
- // Dispatch stubs in chunks so rows (and thumbnail hydrations) stream in
- // rather than dumping the whole drop in one render.
const DISPATCH_CHUNK = 5;
let flushedStubs = 0;
let flushedHydrations = 0;
@@ -470,11 +474,40 @@ export async function addFiles(
let scannedCount = 0;
for (const file of filesToProcess) {
+ const isPdf =
+ file.type === "application/pdf" || /\.pdf$/i.test(file.name);
+ const isEncrypted = isPdf
+ ? await FileAnalyzer.isPDFEncrypted(file).catch(() => true)
+ : false;
const quickKey = createQuickKey(file);
+ // A failed library read must not discard a valid upload of the same file.
+ // Wait outside the lock so other imports can still publish.
+ while (true) {
+ await addFilesMutex.lock();
+ ownsImportLock = true;
+ const pendingLoads = allowDuplicates
+ ? []
+ : [...libraryLoads.values()]
+ .filter((pending) => pending.quickKey === quickKey)
+ .map((pending) => pending.promise);
+ if (pendingLoads.length === 0) break;
+ addFilesMutex.unlock();
+ ownsImportLock = false;
+ await Promise.all(pendingLoads);
+ }
+ const existingQuickKeys = buildQuickKeySet(stateRef.current.files.byId);
+ // Pending admission and React dispatches may not have reached state yet.
+ for (const current of filesRef.current.values())
+ existingQuickKeys.add(createQuickKey(current));
// Soft deduplication: Check if file already exists by metadata
- if (!allowDuplicates && existingQuickKeys.has(quickKey)) {
+ if (
+ !allowDuplicates &&
+ (existingQuickKeys.has(quickKey) || importedQuickKeys.has(quickKey))
+ ) {
reportBulkAddProgress(++scannedCount, filesToProcess.length);
+ addFilesMutex.unlock();
+ ownsImportLock = false;
continue;
}
@@ -496,25 +529,13 @@ export async function addFiles(
fileStub.folderId = options.folderId as StirlingFileStub["folderId"];
}
- // Early encryption detection for PDFs — set the flag before dispatch so the
- // viewer gate and modal queue pick it up immediately instead of after hydration
- if (file.type === "application/pdf" || /\.pdf$/i.test(file.name)) {
- try {
- fileStub.processedFile = {
- pages: [],
- isEncrypted: await FileAnalyzer.isPDFEncrypted(file),
- };
- bindPdfAccess(file, fileId);
- } catch (error) {
- fileStub.processedFile = { pages: [], isEncrypted: true };
- // Never block upload on analysis failure — but log so it's debuggable
- // if an unencrypted file later appears to "hang" during processing.
- console.warn(
- "[FileActions] Early encryption detection failed for",
- file.name,
- error,
- );
- }
+ if (isPdf) {
+ fileStub.processedFile = {
+ pages: [],
+ isEncrypted,
+ requiresOpeningPassword: getPdfAccess(file)?.requiresOpeningPassword,
+ };
+ bindPdfAccess(file, fileId);
}
Object.assign(fileStub, await sourceLinkForNewFile(file));
@@ -525,7 +546,7 @@ export async function addFiles(
}
if (!allowDuplicates) {
- existingQuickKeys.add(quickKey);
+ importedQuickKeys.add(quickKey);
}
stirlingFileStubs.push(fileStub);
@@ -548,9 +569,7 @@ export async function addFiles(
fileStub.processedFile?.isEncrypted &&
!getPdfAccess(targetFile)
) {
- // Pre-dispatch detection already flagged this PDF as encrypted; PDF.js
- // can't produce thumbnails/metadata without the password, so re-parsing
- // here would just duplicate work. Metadata is refreshed after unlock.
+ // Authentication owns the first parse; thumbnails follow verified access.
processedFileMetadata = fileStub.processedFile;
} else {
processedFileMetadata =
@@ -609,8 +628,10 @@ export async function addFiles(
if (!options.skipMetadataHydration) pendingHydrations.push(hydrate);
reportBulkAddProgress(++scannedCount, filesToProcess.length);
- if (stirlingFileStubs.length - flushedStubs >= DISPATCH_CHUNK) {
- const chunkWrites = flushChunk();
+ const chunkWrites = flushChunk();
+ addFilesMutex.unlock();
+ ownsImportLock = false;
+ if (stirlingFileStubs.length % DISPATCH_CHUNK === 0) {
// Yield a MACROTASK so React commits this chunk and runs its effects
// (incl. the policy-enforcement dispatch) before the next chunk scans.
// The per-file awaits above are only microtasks, which don't give React
@@ -622,9 +643,6 @@ export async function addFiles(
}
}
- // Flush the remainder (also the sole dispatch for small batches).
- flushChunk();
-
// Wait for the per-chunk writes (streamed in flushChunk) to commit, so
// addFiles only resolves once every file is durably stored.
if (enablePersistence && persistPromises.length > 0) {
@@ -639,7 +657,7 @@ export async function addFiles(
} finally {
clearBulkAddProgress();
// Always release mutex even if error occurs
- addFilesMutex.unlock();
+ if (ownsImportLock) addFilesMutex.unlock();
}
}
@@ -834,24 +852,29 @@ export async function undoConsumeFiles(
/** Regenerate page metadata and thumbnails for a file whose bytes are current.
* Queued, because parsing several PDFs at once is what the limit bounds. */
-function hydrateMetadataFor(
+export function hydrateMetadataFor(
fileId: FileId,
stirlingFile: StirlingFile,
stateRef: React.MutableRefObject<FileContextState>,
lifecycleManager: FileLifecycleManager,
): void {
if (!stirlingFile.type.startsWith("application/pdf")) return;
+ const lifetime = pdfAccessLifetime(stirlingFile);
scheduleMetadataHydration(async () => {
+ if (lifetime.aborted) return;
const processedFileMetadata =
await generateProcessedFileMetadata(stirlingFile);
- if (!processedFileMetadata) return;
+ if (!processedFileMetadata || lifetime.aborted) return;
+ const currentStub = stateRef.current.files.byId[fileId];
const updates: Partial<StirlingFileStub> = {
- processedFile: processedFileMetadata,
+ processedFile: {
+ ...currentStub?.processedFile,
+ ...processedFileMetadata,
+ },
};
// Update thumbnail only if current stub doesn't have one
- const currentStub = stateRef.current.files.byId[fileId];
if (!currentStub?.thumbnailUrl && processedFileMetadata.thumbnailUrl) {
updates.thumbnailUrl = processedFileMetadata.thumbnailUrl;
if (processedFileMetadata.thumbnailUrl.startsWith("blob:")) {
@@ -919,6 +942,7 @@ export async function addStirlingFileStubs(
lifecycleManager: FileLifecycleManager,
): Promise<StirlingFile[]> {
await addFilesMutex.lock();
+ let ownsImportLock = true;
try {
// Show loading indicator while preparing files from storage
@@ -934,6 +958,11 @@ export async function addStirlingFileStubs(
// Process and dispatch files one by one for progressive UI updates
for (const stub of stirlingFileStubs) {
+ const pendingLoad = libraryLoads.get(stub.id);
+ if (pendingLoad) {
+ loads.push(pendingLoad.promise);
+ continue;
+ }
// Dedup by stable fileId. Two distinct files in history can share
// name|size|lastModified (and therefore quickKey), so quickKey dedup
// here would silently drop a legitimately different file.
@@ -973,92 +1002,104 @@ export async function addStirlingFileStubs(
// Load and publish the File, ahead of any parsing. NOT queued: whether a
// file opens at all must not wait on other files' parses.
- loads.push(
- (async () => {
- // A storage read that never settles renders as a file that silently won't
- // open. Name it in the console rather than leaving the user guessing.
- const stall = setTimeout(
- () =>
- console.error(
- `[Hydration] ${stub.name} (${fileId}) has been loading for ${STALLED_LOAD_MS / 1000}s - the IndexedDB read has not settled`,
- ),
- STALLED_LOAD_MS,
- );
- // A record can be a cache of something outside the app, so settle it
- // BEFORE serving it, or an edit made out there stays invisible and a
- // file deleted out there still opens.
- const port = reconcilePort(stateRef, filesRef, lifecycleManager);
- const decision = await reconcileBeforeOpen(stub, port);
- if (decision.drop) {
- lifecycleManager.removeFiles([fileId], stateRef);
- clearTimeout(stall);
- return;
- }
- // Bytes the reconciler holds win over the stored copy.
- const stirlingFile = await (
- decision.file
- ? Promise.resolve(createStirlingFile(decision.file, fileId))
- : fileStorage.getStirlingFile(fileId)
- ).finally(() => clearTimeout(stall));
- if (!stirlingFile) {
- // A row with no bytes renders empty and its clicks look dead, so take it
- // back out. Storage keeps the record; fileStorage has said why.
+ const load = (async () => {
+ // A storage read that never settles renders as a file that silently won't
+ // open. Name it in the console rather than leaving the user guessing.
+ const stall = setTimeout(
+ () =>
console.error(
- `[Hydration] No readable data for ${stub.name} (${fileId}); removing it from the workbench`,
- );
- lifecycleManager.removeFiles([fileId], stateRef);
- return;
- }
+ `[Hydration] ${stub.name} (${fileId}) has been loading for ${STALLED_LOAD_MS / 1000}s - the IndexedDB read has not settled`,
+ ),
+ STALLED_LOAD_MS,
+ );
+ // A record can be a cache of something outside the app, so settle it
+ // BEFORE serving it, or an edit made out there stays invisible and a
+ // file deleted out there still opens.
+ const port = reconcilePort(stateRef, filesRef, lifecycleManager);
+ const decision = await reconcileBeforeOpen(stub, port);
+ if (decision.drop) {
+ lifecycleManager.removeFiles([fileId], stateRef);
+ clearTimeout(stall);
+ return;
+ }
+ // Bytes the reconciler holds win over the stored copy.
+ const stirlingFile = await (
+ decision.file
+ ? Promise.resolve(createStirlingFile(decision.file, fileId))
+ : fileStorage.getStirlingFile(fileId)
+ ).finally(() => clearTimeout(stall));
+ if (!stirlingFile) {
+ // A row with no bytes renders empty and its clicks look dead, so take it
+ // back out. Storage keeps the record; fileStorage has said why.
+ console.error(
+ `[Hydration] No readable data for ${stub.name} (${fileId}); removing it from the workbench`,
+ );
+ lifecycleManager.removeFiles([fileId], stateRef);
+ return;
+ }
- filesRef.current.set(fileId, stirlingFile);
- bindPdfAccess(stirlingFile, fileId);
- Object.assign(record, decision.updates);
- if (
- (stirlingFile.type === "application/pdf" ||
- /\.pdf$/i.test(stirlingFile.name)) &&
- (decision.contentReplaced || !getPdfAccess(stirlingFile))
- ) {
- record.processedFile = {
- pages: [],
- isEncrypted: await FileAnalyzer.isPDFEncrypted(stirlingFile),
- };
- }
- bindPdfAccess(stirlingFile, fileId);
- dispatch({
- type: "ADD_FILES",
- payload: { stirlingFileStubs: [record] },
- });
+ filesRef.current.set(fileId, stirlingFile);
+ bindPdfAccess(stirlingFile, fileId);
+ Object.assign(record, decision.updates);
+ if (
+ (stirlingFile.type === "application/pdf" ||
+ /\.pdf$/i.test(stirlingFile.name)) &&
+ (decision.contentReplaced ||
+ record.processedFile?.isEncrypted === undefined)
+ ) {
+ record.processedFile = {
+ pages: [],
+ isEncrypted: await FileAnalyzer.isPDFEncrypted(stirlingFile),
+ };
+ }
+ if (filesRef.current.get(fileId) !== stirlingFile) return;
+ bindPdfAccess(stirlingFile, fileId);
+ dispatch({
+ type: "ADD_FILES",
+ payload: { stirlingFileStubs: [record] },
+ });
- // Admission can defer the state record; source-link persistence still belongs to these loaded bytes.
- if (decision.updates && Object.keys(decision.updates).length > 0)
- lifecycleManager.updateStirlingFileStub(fileId, decision.updates);
-
- decision.afterPublish?.();
-
- const needsProcessing =
- // Bytes just changed underneath us, so whatever was cached is stale.
- decision.contentReplaced === true ||
- !stub.processedFile ||
- !stub.processedFile.pages ||
- stub.processedFile.pages.length === 0 ||
- stub.processedFile.totalPages !== stub.processedFile.pages.length;
- if (needsProcessing) {
- scheduleMetadataFor(stirlingFile);
- }
- return stirlingFile;
- })().catch((error) => {
+ // Admission can defer the state record; source-link persistence still belongs to these loaded bytes.
+ if (decision.updates && Object.keys(decision.updates).length > 0)
+ lifecycleManager.updateStirlingFileStub(fileId, decision.updates);
+
+ decision.afterPublish?.();
+
+ const needsProcessing =
+ // Bytes just changed underneath us, so whatever was cached is stale.
+ decision.contentReplaced === true ||
+ !stub.processedFile ||
+ !stub.processedFile.pages ||
+ stub.processedFile.pages.length === 0 ||
+ stub.processedFile.totalPages !== stub.processedFile.pages.length;
+ if (
+ needsProcessing &&
+ (!record.processedFile?.isEncrypted || getPdfAccess(stirlingFile))
+ ) {
+ scheduleMetadataFor(stirlingFile);
+ }
+ return stirlingFile;
+ })()
+ .catch((error) => {
console.error(`[Hydration] Failed to load ${fileId}:`, error);
return undefined;
- }),
- );
+ })
+ .finally(() => {
+ if (libraryLoads.get(fileId)?.promise === load)
+ libraryLoads.delete(fileId);
+ });
+ libraryLoads.set(fileId, { promise: load, quickKey: stub.quickKey });
+ loads.push(load);
}
+ addFilesMutex.unlock();
+ ownsImportLock = false;
const loadedFiles = await Promise.all(loads);
return loadedFiles.filter(
(file): file is StirlingFile => file !== undefined,
);
} finally {
- addFilesMutex.unlock();
+ if (ownsImportLock) addFilesMutex.unlock();
}
}
diff --git a/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts b/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
index d94fdc0afd..f73b66f4ab 100644
--- a/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
+++ b/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
@@ -13,12 +13,15 @@ import type { FileId } from "@app/types/file";
*/
const getStirlingFile = vi.hoisted(() => vi.fn());
+const generateThumbnailPairWithMetadata = vi.hoisted(() =>
+ vi.fn(() => new Promise(() => {})),
+);
vi.mock("@app/services/fileStorage", () => ({
fileStorage: { getStirlingFile },
}));
/** The stall under test: the page parse never settles. */
vi.mock("@app/utils/thumbnailUtils", () => ({
- generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+ generateThumbnailPairWithMetadata,
}));
const stub = (id: string): StirlingFileStub =>
@@ -30,8 +33,9 @@ const stub = (id: string): StirlingFileStub =>
lastModified: 0,
}) as StirlingFileStub;
-async function harness(ids: string[]) {
+async function harness(ids: string[], encrypted = false) {
vi.resetModules();
+ generateThumbnailPairWithMetadata.mockClear();
getStirlingFile.mockImplementation(
async (id: FileId) =>
new File(["%PDF-1.7"], `${id}.pdf`, { type: "application/pdf" }),
@@ -40,6 +44,13 @@ async function harness(ids: string[]) {
await import("@app/contexts/file/fileActions");
const stubs = ids.map(stub);
+ if (encrypted)
+ for (const stub of stubs)
+ stub.processedFile = {
+ pages: [],
+ isEncrypted: true,
+ requiresOpeningPassword: true,
+ };
const state = {
files: { ids: [], byId: {} },
pinnedFiles: new Set(),
@@ -72,6 +83,14 @@ async function harness(ids: string[]) {
}
describe("workbench hydration — a stalled parse can't hide the file", () => {
+ test("does not parse locked library files for thumbnails before authentication", async () => {
+ const { published } = await harness(
+ ["locked-a", "locked-b", "locked-c"],
+ true,
+ );
+ expect(published).toHaveLength(3);
+ expect(generateThumbnailPairWithMetadata).not.toHaveBeenCalled();
+ });
test("publishes every file's bytes while their parses hang", async () => {
// Three, because the parse queue only runs two at a time: the third proves
// loading isn't queued behind parses that never finish.
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.test.ts b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
index c2401619c5..2db3387bc7 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.test.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
@@ -7,7 +7,7 @@ import {
clearPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
describe("FileLifecycleManager", () => {
afterEach(clearPdfAccess);
@@ -72,8 +72,6 @@ describe("FileLifecycleManager", () => {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
};
rememberPdfAccess(original, access);
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.ts b/frontend/editor/src/core/contexts/file/lifecycle.ts
index 0f694d5505..65fb9f9ddb 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.ts
@@ -9,7 +9,7 @@ import {
forgetPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
import {
FileContextAction,
FileContextState,
diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts
index 32d1dc322b..f380d9817c 100644
--- a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts
+++ b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts
@@ -6,91 +6,59 @@ import {
useChangePermissionsParameters,
} from "@app/hooks/tools/changePermissions/useChangePermissionsParameters";
import { usePermissionExtraction } from "@app/hooks/tools/changePermissions/usePermissionExtraction";
-import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
-import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
-import { rememberPdfAccess } from "@app/services/pdfPasswordStore";
-
-const {
- getDocumentBytes,
- getPdfiumModule,
- openRawDocument,
- closeDocAndFreeBuffer,
- pdfiumModule,
-} = vi.hoisted(() => ({
- getDocumentBytes: vi.fn(),
- getPdfiumModule: vi.fn(),
- openRawDocument: vi.fn(),
- closeDocAndFreeBuffer: vi.fn(),
- pdfiumModule: { FPDF_GetDocUserPermissions: vi.fn() },
-}));
-
-vi.mock("@app/services/documentBytesCache", () => ({ getDocumentBytes }));
-vi.mock("@app/services/pdfiumService", () => ({
- getPdfiumModule,
- openRawDocument,
- closeDocAndFreeBuffer,
+import {
+ ensureLocalPdfAccess,
+ clearPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+} from "@app/services/pdfAccessService";
+
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ ensureLocalPdfAccess: vi.fn(),
}));
+const inspect = vi.mocked(ensureLocalPdfAccess);
+const access: PdfAccess = {
+ password: "owner",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: PdfPermissionFlag.AllowAll,
+ pageCount: 1,
+};
function renderExtraction(file: File | undefined, enabled = true) {
return renderHook(
({ file, enabled }) => {
const params = useChangePermissionsParameters();
- const extraction = usePermissionExtraction(
- file,
- params.setParameters,
- enabled,
- );
- return { ...extraction, ...params };
+ return {
+ ...usePermissionExtraction(file, params.setParameters, enabled),
+ ...params,
+ };
},
{ initialProps: { file, enabled } },
);
}
-function mockPermissions(permissions: number) {
- pdfiumModule.FPDF_GetDocUserPermissions.mockReturnValueOnce(permissions);
-}
-
-function deferred<T>() {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>((resolvePromise) => {
- resolve = resolvePromise;
- });
- return { promise, resolve };
-}
-
beforeEach(() => {
- vi.resetAllMocks();
- getDocumentBytes.mockResolvedValue(new ArrayBuffer(0));
- getPdfiumModule.mockResolvedValue(pdfiumModule);
- openRawDocument.mockResolvedValue(1);
- pdfiumModule.FPDF_GetDocUserPermissions.mockReturnValue(
- PdfPermissionFlag.AllowAll,
- );
+ clearPdfAccess();
+ inspect.mockReset().mockResolvedValue(access);
});
describe("usePermissionExtraction", () => {
- test("reads stored restrictions using the verified session credential", async () => {
- const file = new File([], "owner.pdf");
- rememberPdfAccess(file, {
- password: "verified-owner",
- encrypted: true,
- signed: false,
- ownerAuthenticated: true,
- permissions: 0,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- });
- mockPermissions(0);
- const { result } = renderExtraction(file);
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(openRawDocument).toHaveBeenCalledWith(
- expect.any(ArrayBuffer),
- "verified-owner",
- );
- expect(result.current.parameters.preventExtractContent).toBe(true);
- expect(result.current.parameters.preventPrinting).toBe(true);
- });
+ test.each([1, 101 * 1024 * 1024])(
+ "uses cached stored restrictions without parsing a %i-byte PDF",
+ async (size) => {
+ const file = new File([], "owner.pdf");
+ Object.defineProperty(file, "size", { value: size });
+ rememberPdfAccess(file, { ...access, permissions: 0 });
+ const { result } = renderExtraction(file);
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.parameters.preventExtractContent).toBe(true);
+ expect(result.current.parameters.preventPrinting).toBe(true);
+ expect(inspect).not.toHaveBeenCalled();
+ },
+ );
test.each([
[PdfPermissionFlag.AssembleDocument, "preventAssembly"],
@@ -104,252 +72,84 @@ describe("usePermissionExtraction", () => {
[PdfPermissionFlag.ModifyAnnotations, "preventModifyAnnotations"],
[PdfPermissionFlag.Print, "preventPrinting"],
[PdfPermissionFlag.PrintHighQuality, "preventPrintingFaithful"],
- ] as const)("maps missing permission %s to %s", async (flag, restriction) => {
- mockPermissions(PdfPermissionFlag.AllowAll & ~flag);
- const bytes = new ArrayBuffer(8);
- getDocumentBytes.mockResolvedValueOnce(bytes);
+ ] as const)("maps stored permission %s to %s", async (flag, restriction) => {
const file = new File([], "restricted.pdf");
+ rememberPdfAccess(file, {
+ ...access,
+ permissions: PdfPermissionFlag.AllowAll & ~flag,
+ });
const { result } = renderExtraction(file);
-
- expect(result.current.isLoading).toBe(true);
await waitFor(() => expect(result.current.isLoading).toBe(false));
-
expect(result.current.parameters).toEqual({
...defaultParameters,
[restriction]: true,
});
- expect(getDocumentBytes).toHaveBeenCalledWith(file);
- expect(openRawDocument).toHaveBeenCalledWith(bytes, undefined);
- expect(pdfiumModule.FPDF_GetDocUserPermissions).toHaveBeenCalledWith(1);
- expect(closeDocAndFreeBuffer).toHaveBeenCalledExactlyOnceWith(
- pdfiumModule,
- 1,
- );
});
- test.each([0xffffffff, -1, PdfPermissionFlag.AllowAll])(
- "allows everything when no restrictions are present (%s)",
- async (permissions) => {
- mockPermissions(permissions);
- const { result } = renderExtraction(new File([], "unrestricted.pdf"));
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.parameters).toEqual(defaultParameters);
- expect(result.current.hasError).toBe(false);
- },
- );
-
- test("refreshes for a different document without overwriting edits on rerender", async () => {
- mockPermissions(0);
- const file = new File([], "first.pdf");
- const { result, rerender } = renderExtraction(file);
- await waitFor(() => expect(result.current.isLoading).toBe(false));
-
- act(() => result.current.updateParameter("preventPrinting", false));
- rerender({ file, enabled: true });
- expect(result.current.parameters.preventPrinting).toBe(false);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
-
- rerender({ file: new File([], "second.pdf"), enabled: true });
+ test("falls back to the cancellable worker without imposing a size limit", async () => {
+ const file = new File([], "large.pdf");
+ Object.defineProperty(file, "size", { value: 101 * 1024 * 1024 });
+ const { result } = renderExtraction(file);
await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.parameters).toEqual(defaultParameters);
- expect(openRawDocument).toHaveBeenCalledTimes(2);
- });
-
- test("preserves batch settings and refreshes when returning to one PDF", async () => {
- const { result, rerender } = renderExtraction(undefined);
- expect(getDocumentBytes).not.toHaveBeenCalled();
- expect(result.current.isLoading).toBe(false);
-
- const file = new File([], "single.pdf");
- mockPermissions(PdfPermissionFlag.AllowAll & ~PdfPermissionFlag.Print);
- rerender({ file, enabled: true });
- await waitFor(() =>
- expect(result.current.parameters.preventPrinting).toBe(true),
- );
-
- act(() => result.current.updateParameter("preventModify", true));
- const batchParameters = {
- ...defaultParameters,
- preventPrinting: true,
- preventModify: true,
- };
- rerender({ file: undefined, enabled: true });
- expect(result.current.parameters).toEqual(batchParameters);
- expect(result.current.isLoading).toBe(false);
+ expect(inspect).toHaveBeenCalledWith(file, expect.any(AbortSignal));
expect(result.current.hasError).toBe(false);
-
- act(() => result.current.updateParameter("preventExtractContent", true));
- rerender({ file: undefined, enabled: false });
- rerender({ file: undefined, enabled: true });
- expect(result.current.parameters).toEqual({
- ...batchParameters,
- preventExtractContent: true,
- });
- expect(openRawDocument).toHaveBeenCalledTimes(1);
-
- rerender({ file, enabled: true });
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.parameters).toEqual(defaultParameters);
- expect(openRawDocument).toHaveBeenCalledTimes(2);
});
- test("serializes file switches and ignores a cancelled document", async () => {
- const pending = deferred<number>();
- openRawDocument.mockReturnValueOnce(pending.promise);
+ test("cancels stale reads on selection changes and does not overwrite the new file", async () => {
+ let finish!: (value: PdfAccess) => void;
+ inspect.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
const { result, rerender } = renderExtraction(new File([], "old.pdf"));
- await waitFor(() => expect(openRawDocument).toHaveBeenCalledTimes(1));
-
+ const signal = inspect.mock.calls[0][1];
rerender({ file: new File([], "new.pdf"), enabled: true });
- expect(getDocumentBytes).toHaveBeenCalledTimes(1);
- await act(async () => pending.resolve(2));
+ expect(signal?.aborted).toBe(true);
await waitFor(() => expect(result.current.isLoading).toBe(false));
-
+ await act(async () => finish({ ...access, permissions: 0 }));
expect(result.current.parameters).toEqual(defaultParameters);
- expect(result.current.hasError).toBe(false);
- expect(
- pdfiumModule.FPDF_GetDocUserPermissions,
- ).toHaveBeenCalledExactlyOnceWith(1);
- expect(closeDocAndFreeBuffer).toHaveBeenCalledWith(pdfiumModule, 2);
- expect(closeDocAndFreeBuffer).toHaveBeenCalledWith(pdfiumModule, 1);
- });
-
- test("reloads a previous document when returning before the next one opens", async () => {
- mockPermissions(0);
- const first = new File([], "first.pdf");
- const { result, rerender } = renderExtraction(first);
- await waitFor(() => expect(result.current.isLoading).toBe(false));
-
- const pending = deferred<number>();
- openRawDocument.mockReturnValueOnce(pending.promise);
- rerender({ file: new File([], "second.pdf"), enabled: true });
- await waitFor(() => expect(openRawDocument).toHaveBeenCalledTimes(2));
-
- mockPermissions(0);
- rerender({ file: first, enabled: true });
- await act(async () => pending.resolve(2));
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.parameters.preventPrinting).toBe(true);
- expect(openRawDocument).toHaveBeenCalledTimes(3);
- expect(closeDocAndFreeBuffer).toHaveBeenCalledWith(pdfiumModule, 2);
});
- test("releases a document that finishes opening after unmount", async () => {
- const pending = deferred<number>();
- openRawDocument.mockReturnValueOnce(pending.promise);
+ test("aborts a pending read when unmounted", () => {
+ inspect.mockReturnValueOnce(new Promise(() => {}));
const { unmount } = renderExtraction(new File([], "pending.pdf"));
- await waitFor(() => expect(openRawDocument).toHaveBeenCalled());
+ const signal = inspect.mock.calls[0][1];
unmount();
- await act(async () => pending.resolve(2));
-
- expect(pdfiumModule.FPDF_GetDocUserPermissions).not.toHaveBeenCalled();
- expect(closeDocAndFreeBuffer).toHaveBeenCalledExactlyOnceWith(
- pdfiumModule,
- 2,
- );
+ expect(signal?.aborted).toBe(true);
});
- test("skips cancelled scans before they read file bytes", async () => {
- const pending = deferred<void>();
- const previousScan = runPdfiumScan(() => pending.promise);
- const { unmount } = renderExtraction(new File([], "queued.pdf"));
- unmount();
- await act(async () => {
- pending.resolve();
- await previousScan;
- });
- expect(getDocumentBytes).not.toHaveBeenCalled();
- expect(openRawDocument).not.toHaveBeenCalled();
- });
-
- test.each(["bytes", "initialize"])(
- "does not open a cancelled document after %s finishes",
- async (stage) => {
- const pending = deferred<void>();
- const read = stage === "bytes" ? getDocumentBytes : getPdfiumModule;
- const value = stage === "bytes" ? new ArrayBuffer(0) : pdfiumModule;
- read.mockReturnValueOnce(pending.promise.then(() => value));
- const { unmount } = renderExtraction(new File([], "cancelled.pdf"));
- await waitFor(() => expect(read).toHaveBeenCalled());
- unmount();
- await act(async () => pending.resolve());
- expect(openRawDocument).not.toHaveBeenCalled();
- },
- );
-
- test.each(["bytes", "initialize", "open", "read"])(
- "preserves manual settings after %s failures when detection resumes",
- async (stage) => {
- const failure = new Error("Unreadable PDF");
- if (stage === "bytes") getDocumentBytes.mockRejectedValueOnce(failure);
- else if (stage === "initialize")
- getPdfiumModule.mockRejectedValueOnce(failure);
- else if (stage === "open") openRawDocument.mockRejectedValueOnce(failure);
- else
- pdfiumModule.FPDF_GetDocUserPermissions.mockImplementationOnce(() => {
- throw failure;
- });
- const file = new File([], "broken.pdf");
- const { result, rerender } = renderExtraction(file);
- await waitFor(() => expect(result.current.hasError).toBe(true));
-
- expect(result.current.isLoading).toBe(false);
- if (stage === "read")
- expect(closeDocAndFreeBuffer).toHaveBeenCalledExactlyOnceWith(
- pdfiumModule,
- 1,
- );
- else expect(closeDocAndFreeBuffer).not.toHaveBeenCalled();
-
- act(() => result.current.updateParameter("preventPrinting", true));
- rerender({ file, enabled: false });
- rerender({ file, enabled: true });
-
- expect(result.current.parameters.preventPrinting).toBe(true);
- expect(result.current.hasError).toBe(true);
- expect(result.current.isLoading).toBe(false);
- expect(getDocumentBytes).toHaveBeenCalledTimes(1);
-
- mockPermissions(0);
- rerender({ file: new File([], "readable.pdf"), enabled: true });
- await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.hasError).toBe(false);
- expect(result.current.parameters.preventModify).toBe(true);
- expect(getDocumentBytes).toHaveBeenCalledTimes(2);
- },
- );
-
- test("leaves oversized documents manual without reading them into memory", async () => {
- const file = new File([], "large.pdf");
- Object.defineProperty(file, "size", { value: LARGE_PDF_PARSE_LIMIT });
- const { result } = renderExtraction(file);
- await waitFor(() => expect(result.current.hasError).toBe(true));
- expect(result.current.isLoading).toBe(false);
- expect(getDocumentBytes).not.toHaveBeenCalled();
- expect(openRawDocument).not.toHaveBeenCalled();
- act(() => result.current.updateParameter("preventPrinting", true));
- expect(result.current.parameters.preventPrinting).toBe(true);
- });
-
- test("preserves settings and results while processing, then reads the output when editing resumes", async () => {
- const file = new File([], "input.pdf");
+ test("preserves edits across rerenders, processing, and batch selection", async () => {
+ const file = new File([], "first.pdf");
const { result, rerender } = renderExtraction(file);
await waitFor(() => expect(result.current.isLoading).toBe(false));
act(() => result.current.updateParameter("preventPrinting", true));
-
+ rerender({ file, enabled: true });
rerender({ file, enabled: false });
rerender({ file, enabled: true });
+ rerender({ file: undefined, enabled: true });
expect(result.current.parameters.preventPrinting).toBe(true);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
-
+ expect(inspect).toHaveBeenCalledTimes(1);
const output = new File([], "output.pdf");
rerender({ file: output, enabled: false });
expect(result.current.parameters.preventPrinting).toBe(true);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
-
- mockPermissions(0);
rerender({ file: output, enabled: true });
await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(openRawDocument).toHaveBeenCalledTimes(2);
- expect(result.current.parameters.preventModify).toBe(true);
+ expect(result.current.parameters).toEqual(defaultParameters);
+ });
+
+ test("keeps manual settings after a failed read until the file changes", async () => {
+ inspect.mockRejectedValueOnce(new Error("Unreadable PDF"));
+ const file = new File([], "broken.pdf");
+ const { result, rerender } = renderExtraction(file);
+ await waitFor(() => expect(result.current.hasError).toBe(true));
+ act(() => result.current.updateParameter("preventPrinting", true));
+ rerender({ file, enabled: false });
+ rerender({ file, enabled: true });
+ expect(result.current.parameters.preventPrinting).toBe(true);
+ expect(inspect).toHaveBeenCalledTimes(1);
+ rerender({ file: new File([], "next.pdf"), enabled: true });
+ await waitFor(() => expect(result.current.hasError).toBe(false));
});
});
diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts
index 1e9b198381..36dcfd55bb 100644
--- a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts
+++ b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts
@@ -1,14 +1,10 @@
import { useEffect, useRef, useState } from "react";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
-import { PdfPermissionFlag } from "@embedpdf/models";
-import { getDocumentBytes } from "@app/services/documentBytesCache";
-import { runPdfiumScan } from "@app/services/pdfiumScanQueue";
import {
- closeDocAndFreeBuffer,
- getPdfiumModule,
- openRawDocument,
-} from "@app/services/pdfiumService";
-import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
+ getPdfAccess,
+ ensureLocalPdfAccess,
+} from "@app/services/pdfAccessService";
+import { PdfPermissionFlag } from "@embedpdf/models";
+
import {
defaultParameters,
type ChangePermissionsParametersHook,
@@ -21,7 +17,7 @@ type ExtractionStatus = "idle" | "loading" | "loaded" | "error";
* Pass no file for a batch to preserve the current settings without inspecting PDFs.
* Disable while processing or reviewing results to preserve the operation state.
* Failed reads keep manual settings until another file is selected.
- * Documents at the browser parsing size limit require manual settings.
+ * Cached stored permissions include restrictions hidden by owner authentication.
*/
export function usePermissionExtraction(
file: File | undefined,
@@ -46,32 +42,14 @@ export function usePermissionExtraction(
setParameters(defaultParameters);
setState({ file, status: "loading" });
- const signal = { cancelled: false };
+ const cancellation = new AbortController();
const readPermissions = async () => {
try {
- if (file.size >= LARGE_PDF_PARSE_LIMIT) {
- throw new Error("PDF exceeds the browser parsing size limit");
- }
- const permissions = await runPdfiumScan(async () => {
- if (signal.cancelled) return;
- const bytes = await getDocumentBytes(file);
- if (signal.cancelled) return;
- const module = await getPdfiumModule();
- if (signal.cancelled) return;
- const docPtr = await openRawDocument(
- bytes,
- getPdfAccess(file)?.password,
- );
- try {
- if (signal.cancelled) return;
- // Owner access must not hide the document's stored user restrictions.
- return module.FPDF_GetDocUserPermissions(docPtr);
- } finally {
- closeDocAndFreeBuffer(module, docPtr);
- }
- });
- if (signal.cancelled || permissions === undefined) return;
+ const { permissions } =
+ getPdfAccess(file) ??
+ (await ensureLocalPdfAccess(file, cancellation.signal));
+ if (cancellation.signal.aborted) return;
const prevented = (flag: PdfPermissionFlag) =>
(permissions & flag) === 0;
@@ -95,7 +73,7 @@ export function usePermissionExtraction(
initializedFile.current = file;
setState({ file, status: "loaded" });
} catch {
- if (!signal.cancelled) {
+ if (!cancellation.signal.aborted) {
initializedFile.current = file;
setState({ file, status: "error" });
}
@@ -105,7 +83,7 @@ export function usePermissionExtraction(
void readPermissions();
return () => {
- signal.cancelled = true;
+ cancellation.abort();
};
}, [file, setParameters, enabled]);
diff --git a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
index f56128fa7e..179e13b6bf 100644
--- a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
+++ b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts
@@ -18,6 +18,9 @@ export const removePasswordToApiParams = (
parameters: RemovePasswordParameters,
): RemovePasswordApiParams => ({
password: parameters.password,
+ ...(parameters.ownerPassword
+ ? { ownerPassword: parameters.ownerPassword }
+ : {}),
});
// Reconstruct the tool's UI parameters from a remove-password request body, so a
@@ -26,6 +29,9 @@ export const removePasswordFromApiParams = (
apiParams: RemovePasswordApiParams,
): Partial<RemovePasswordParameters> => ({
password: apiParams.password ?? defaultParameters.password,
+ ...(apiParams.ownerPassword !== undefined
+ ? { ownerPassword: apiParams.ownerPassword }
+ : {}),
});
/**
@@ -36,10 +42,7 @@ export const buildRemovePasswordFormData = (
parameters: RemovePasswordParameters,
file: File,
): FormData => {
- const form = objectToFormData(removePasswordToApiParams(parameters), {
+ return objectToFormData(removePasswordToApiParams(parameters), {
fileInput: file,
});
- if (parameters.ownerPassword)
- form.set("ownerPassword", parameters.ownerPassword);
- return form;
};
diff --git a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts
index 7598db9c62..c27c21b83a 100644
--- a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts
+++ b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts
@@ -9,7 +9,7 @@ import { createStirlingFile } from "@app/types/fileContext";
import {
clearPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
vi.mock("../shared/useToolOperation", async () => {
const actual = await vi.importActual("../shared/useToolOperation"); // Need to keep ToolType etc.
@@ -76,23 +76,20 @@ describe("useRemovePasswordOperation", () => {
password: opening ? "reader" : "",
encrypted: opening || owner,
requiresOpeningPassword: opening,
- hasOwnerPassword: owner,
ownerAuthenticated: false,
signed: false,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
});
return file;
}
test.each([
- { opening: true, owner: false, password: "reader", ownerPassword: null },
+ { opening: false, owner: false, password: "", ownerPassword: null },
{ opening: false, owner: true, password: "", ownerPassword: "owner" },
{ opening: true, owner: true, password: "reader", ownerPassword: "owner" },
])(
- "only submits passwords present on a file (opening=$opening, owner=$owner)",
+ "omits known absent roles and submits unknown roles (opening=$opening, encrypted-owner=$owner)",
({ opening, owner, password, ownerPassword }) => {
renderHook(() => useRemovePasswordOperation());
const form = getToolConfig().buildFormData(
@@ -105,7 +102,7 @@ describe("useRemovePasswordOperation", () => {
);
test.each(["opening", "owner", "both"] as const)(
- "leaves files without the requested %s password unchanged",
+ "skips known absent %s passwords and lets the endpoint validate unknown roles",
async (remove) => {
const opening = protectedFile(true, false);
const owner = protectedFile(false, true);
@@ -124,11 +121,7 @@ describe("useRemovePasswordOperation", () => {
]);
expect(mockToolOperationReturn.executeOperation).toHaveBeenCalledWith(
params,
- remove === "opening"
- ? [opening, both]
- : remove === "owner"
- ? [owner, both]
- : [opening, owner, both],
+ remove === "opening" ? [opening, both] : [opening, owner, both],
);
},
);
@@ -174,6 +167,21 @@ describe("useRemovePasswordOperation", () => {
protectedFile(false, true),
);
expect(form.get("password")).toBe("owner");
+ expect(form.has("ownerPassword")).toBe(false);
+ });
+
+ test("retains selective owner removal through API parameter conversion", () => {
+ const parameters = { password: "", ownerPassword: "owner" };
+ const api = removePasswordOperationConfig.toApiParams!(parameters);
+ expect(removePasswordOperationConfig.fromApiParams!(api)).toEqual(
+ parameters,
+ );
+ const form = removePasswordOperationConfig.buildFormData(
+ parameters,
+ protectedFile(false, true),
+ );
+ expect(form.get("password")).toBe("");
+ expect(form.get("ownerPassword")).toBe("owner");
});
test("should use correct translation for error messages", () => {
diff --git a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts
index b48af573d2..08ba01baf2 100644
--- a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts
@@ -1,6 +1,6 @@
import { useTranslation } from "react-i18next";
import type { StirlingFile } from "@app/types/fileContext";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import {
useToolOperation,
defineSingleFileTool,
@@ -18,10 +18,6 @@ import {
REMOVE_PASSWORD_ENDPOINT,
} from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";
-// Re-export for backwards compatibility with any other imports
-export { buildRemovePasswordFormData };
-
-// Static configuration object
export const removePasswordOperationConfig = defineSingleFileTool({
validateParams: validateRemovePasswordParameters,
buildFormData: buildRemovePasswordFormData,
@@ -44,10 +40,7 @@ function getRemovePasswordParametersForFile(
access?.encrypted === false || access?.requiresOpeningPassword === false
? ""
: parameters.password,
- ownerPassword:
- access?.encrypted === false || access?.hasOwnerPassword === false
- ? ""
- : parameters.ownerPassword,
+ ownerPassword: access?.encrypted === false ? "" : parameters.ownerPassword,
};
}
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
index 210312ed9d..55f6ec5774 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.failures.test.ts
@@ -4,6 +4,16 @@ import type { AxiosRequestConfig } from "axios";
import { expectConsole } from "@app/tests/failOnConsole";
import { rememberUnprotectedPdf } from "@app/tests/utils/testFileHelpers";
import type { StirlingFile } from "@app/types/fileContext";
+import {
+ inspectLocalPdfAccess,
+ clearPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+ bindPdfAccess,
+ forgetPdfAccess,
+ setPdfAccessPolicy,
+ type PdfAccess,
+} from "@app/services/pdfAccessService";
// One bad file in a batch must come back named, with its error: the caller reports each one,
// and it cannot derive the failure kind without the error the request threw.
@@ -12,6 +22,19 @@ const post = vi.fn();
vi.mock("@app/services/apiClient", () => ({
default: { post: (...args: unknown[]) => post(...args) },
}));
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ inspectLocalPdfAccess: vi.fn(),
+}));
+const inspectLocal = vi.mocked(inspectLocalPdfAccess);
+const plainAccess: PdfAccess = {
+ password: "",
+ encrypted: false,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: -4,
+ pageCount: 1,
+};
// Mirrors the response body, so a 0-byte answer really does produce an empty output.
vi.mock("@app/utils/toolResponseProcessor", () => ({
@@ -46,30 +69,142 @@ function run(files: StirlingFile[]) {
beforeEach(() => {
post.mockReset();
+ inspectLocal.mockReset();
+ clearPdfAccess();
+ setPdfAccessPolicy(undefined);
});
describe("processFiles failure reporting", () => {
- it.each(["add-password", "remove-password"])(
- "discards %s results when cancelled during final inspection",
- async (operation) => {
- post.mockResolvedValueOnce({ data: new Blob(["result"]), status: 200 });
- let completeInspection!: (response: {
- data: {
- encrypted: boolean;
- ownerAuthenticated: boolean;
- permissions: number;
- };
- }) => void;
+ it.each(["active", "completed", "queued"])(
+ "closing a %s file preserves the other batch results",
+ async (closed) => {
+ const inputs = [
+ file("a.pdf", "a"),
+ file("b.pdf", "b"),
+ file("c.pdf", "c"),
+ ];
+ inputs.forEach((input) => bindPdfAccess(input, input.fileId));
+ let completeRequest!: () => void;
+ post.mockResolvedValue({ data: new Blob(["output"]), status: 200 });
+ post.mockResolvedValueOnce({
+ data: new Blob(["first output"]),
+ status: 200,
+ });
post.mockImplementationOnce(
- (_endpoint: string, _form: FormData, config: AxiosRequestConfig) => {
- expect(config.cancelToken).toBeDefined();
- return new Promise((resolve) => {
- completeInspection = resolve;
- });
- },
+ (_endpoint, _form, config: AxiosRequestConfig) =>
+ new Promise((resolve, reject) => {
+ completeRequest = () =>
+ resolve({ data: new Blob(["second output"]), status: 200 });
+ config.signal?.addEventListener?.(
+ "abort",
+ () => reject(new DOMException("Closed", "AbortError")),
+ { once: true },
+ );
+ }),
);
const { result } = renderHook(() => useToolApiCalls());
const markFileError = vi.fn();
+ const processing = result.current.processFiles(
+ undefined,
+ inputs,
+ {
+ endpoint: "/api/v1/misc/compress-pdf",
+ buildFormData: () => new FormData(),
+ },
+ vi.fn(),
+ vi.fn(),
+ markFileError,
+ );
+ await vi.waitFor(() => expect(post).toHaveBeenCalledTimes(2));
+ const closedId =
+ closed === "active" ? "b" : closed === "completed" ? "a" : "c";
+ forgetPdfAccess([closedId]);
+ completeRequest();
+ const output = await processing;
+ expect(output.successSourceIds).toEqual(
+ inputs.map((input) => input.fileId).filter((id) => id !== closedId),
+ );
+ expect(output.outputFiles).toHaveLength(2);
+ expect(output.unprocessedSourceIds).toEqual([closedId]);
+ expect(output.failedInputs).toEqual([]);
+ expect(markFileError).not.toHaveBeenCalled();
+ expect(post).toHaveBeenCalledTimes(closed === "queued" ? 2 : 3);
+ },
+ );
+
+ it("applies the server policy to protection added to a plain source", async () => {
+ const input = file("source.pdf", "source");
+ expect(getPdfAccess(input)?.honorOwnerPasswords).toBeUndefined();
+ setPdfAccessPolicy(false);
+ post.mockResolvedValue({ data: new Blob(["protected"]), status: 200 });
+ inspectLocal.mockResolvedValue({
+ ...plainAccess,
+ encrypted: true,
+ password: "reader",
+ permissions: 0,
+ });
+ const { result } = renderHook(() => useToolApiCalls());
+ try {
+ const output = await result.current.processFiles(
+ undefined,
+ [input],
+ {
+ endpoint: "/api/v1/security/add-password",
+ buildFormData: () => {
+ const form = new FormData();
+ form.set("keyLength", "256");
+ form.set("password", "reader");
+ return form;
+ },
+ },
+ vi.fn(),
+ vi.fn(),
+ );
+ expect(getPdfAccess(output.outputFiles[0])).toMatchObject({
+ encrypted: true,
+ ownerAuthenticated: false,
+ honorOwnerPasswords: false,
+ });
+ const { preflightPdfOperation } =
+ await import("@app/services/pdfSessionUnlock");
+ const requestOwner = vi.fn().mockResolvedValue(false);
+ const nextInput = Object.assign(output.outputFiles[0], {
+ fileId: "output",
+ }) as StirlingFile;
+ expect(
+ await preflightPdfOperation(
+ [nextInput],
+ "/api/v1/misc/compress-pdf",
+ false,
+ requestOwner,
+ ),
+ ).toBe(true);
+ expect(requestOwner).not.toHaveBeenCalled();
+ } finally {
+ setPdfAccessPolicy(undefined);
+ }
+ });
+
+ it.each([
+ ["add-password", "cancel"],
+ ["remove-password", "cancel"],
+ ["add-password", "navigation"],
+ ["remove-password", "navigation"],
+ ])(
+ "handles %s results on %s during local result adoption",
+ async (operation, stop) => {
+ post.mockResolvedValue({ data: new Blob(["result"]), status: 200 });
+ let completeInspection!: () => void;
+ inspectLocal
+ .mockResolvedValue(plainAccess)
+ .mockImplementationOnce(async (_output, _password, signal) => {
+ expect(signal).toBeDefined();
+ return new Promise((resolve) => {
+ completeInspection = () => resolve(plainAccess);
+ });
+ });
+ const { result, unmount } = renderHook(() => useToolApiCalls());
+ const markFileError = vi.fn();
const processing = result.current.processFiles(
undefined,
[file("a.pdf", "a"), file("b.pdf", "b")],
@@ -85,23 +220,134 @@ describe("processFiles failure reporting", () => {
vi.fn(),
markFileError,
);
- const cancelled = expect(processing).rejects.toThrow(
- "Operation was cancelled",
+ const outcome =
+ stop === "cancel"
+ ? expect(processing).rejects.toThrow("Operation was cancelled")
+ : expect(processing).resolves.toMatchObject({
+ successSourceIds: ["a", "b"],
+ });
+ await vi.waitFor(() => expect(inspectLocal).toHaveBeenCalledOnce());
+ if (stop === "navigation") {
+ unmount();
+ } else result.current.cancelOperation();
+ completeInspection();
+ await outcome;
+ expect(post).toHaveBeenCalledTimes(stop === "cancel" ? 1 : 2);
+ expect(markFileError).not.toHaveBeenCalled();
+ if (stop === "cancel")
+ expect(getPdfAccess(inspectLocal.mock.calls[0][0])).toBeUndefined();
+ else
+ expect(getPdfAccess(inspectLocal.mock.calls[0][0])).toMatchObject(
+ plainAccess,
+ );
+ },
+ );
+
+ it.each(["navigation", "logout"])(
+ "handles %s during an unencrypted batch",
+ async (stop) => {
+ let completeRequest!: () => void;
+ post.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ completeRequest = () =>
+ resolve({ data: new Blob(["first output"]), status: 200 });
+ }),
);
- await vi.waitFor(() => expect(post).toHaveBeenCalledTimes(2));
- result.current.cancelOperation();
- completeInspection({
- data: { encrypted: false, ownerAuthenticated: false, permissions: -4 },
+ post.mockResolvedValueOnce({
+ data: new Blob(["second output"]),
+ status: 200,
});
- await cancelled;
- expect(post).toHaveBeenCalledTimes(2);
- expect(markFileError).not.toHaveBeenCalled();
+ const { result, unmount } = renderHook(() => useToolApiCalls());
+ const processing = result.current.processFiles(
+ undefined,
+ [file("a.pdf", "a"), file("b.pdf", "b")],
+ {
+ endpoint: "/api/v1/misc/compress-pdf",
+ buildFormData: () => new FormData(),
+ },
+ vi.fn(),
+ vi.fn(),
+ vi.fn(),
+ );
+ await vi.waitFor(() => expect(post).toHaveBeenCalledOnce());
+ unmount();
+ expect(post.mock.calls[0][2].cancelToken.reason).toBeUndefined();
+ expect(post.mock.calls[0][2].signal.aborted).toBe(false);
+ const outcome =
+ stop === "logout"
+ ? expect(processing).rejects.toThrow("Operation was cancelled")
+ : expect(processing).resolves.toMatchObject({
+ successSourceIds: ["a", "b"],
+ });
+ if (stop === "logout") clearPdfAccess();
+ completeRequest();
+ await outcome;
+ expect(post).toHaveBeenCalledTimes(stop === "logout" ? 1 : 2);
+ expect(inspectLocal).not.toHaveBeenCalled();
},
);
- it.each(["add-password", "remove-password"])(
+ it.each([
+ ["add-password", false, "reader"],
+ ["add-password", true, "reader"],
+ ["remove-password", false, ""],
+ ])(
+ "adopts %s results locally with preserveExisting=%s",
+ async (operation, preserveExisting, password) => {
+ setPdfAccessPolicy(false);
+ const input = file("source.pdf", "source");
+ rememberPdfAccess(input, {
+ ...getPdfAccess(input)!,
+ encrypted: true,
+ password: "owner",
+ openingPassword: "reader",
+ ownerAuthenticated: true,
+ });
+ post.mockResolvedValue({ data: new Blob(["output"]), status: 200 });
+ inspectLocal.mockImplementation(async (_output, credential) => ({
+ ...plainAccess,
+ encrypted: credential !== "",
+ password: credential ?? "",
+ }));
+ const { result } = renderHook(() => useToolApiCalls());
+ const processed = await result.current.processFiles(
+ undefined,
+ [input],
+ {
+ endpoint: `/api/v1/security/${operation}`,
+ buildFormData: () => {
+ const form = new FormData();
+ form.set("password", "reader");
+ if (!preserveExisting) form.set("keyLength", "256");
+ return form;
+ },
+ },
+ vi.fn(),
+ vi.fn(),
+ );
+ expect(processed.outputFiles).toHaveLength(1);
+ expect(post).toHaveBeenCalledOnce();
+ expect(post.mock.calls[0][0]).toBe(`/api/v1/security/${operation}`);
+ expect(inspectLocal).toHaveBeenCalledWith(
+ processed.outputFiles[0],
+ password,
+ expect.any(AbortSignal),
+ );
+ expect(getPdfAccess(processed.outputFiles[0])).toMatchObject({
+ password,
+ honorOwnerPasswords: false,
+ });
+ },
+ );
+
+ it.each([
+ "/api/v1/security/add-password",
+ "/api/v1/security/remove-password",
+ "/api/v1/misc/compress-pdf",
+ ])(
"cancels %s without processing the remaining batch or marking files as failed",
- async (operation) => {
+ async (endpoint) => {
post.mockImplementation(
(_endpoint: string, _form: FormData, config: AxiosRequestConfig) =>
new Promise((_resolve, reject) => {
@@ -114,7 +360,7 @@ describe("processFiles failure reporting", () => {
undefined,
[file("a.pdf", "a"), file("b.pdf", "b")],
{
- endpoint: `/api/v1/security/${operation}`,
+ endpoint,
buildFormData: () => {
const form = new FormData();
form.set("keyLength", "256");
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
index 5b1e5f4ef4..753f04276c 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
@@ -9,16 +9,19 @@ import { isEmptyOutput } from "@app/services/errorUtils";
import type { ProcessingProgress } from "@app/hooks/tools/shared/useToolState";
import type { StirlingFile, FileId } from "@app/types/fileContext";
import { isSignupRequiredError } from "@app/utils/toolErrorHandler";
+import { combineAbortSignals } from "@app/utils/combineAbortSignals";
import {
prepareUnlockedFile,
protectUnlockedResults,
changePdfSecurity,
- unlockPdfForSession,
} from "@app/services/pdfSessionUnlock";
import {
+ inspectLocalPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+ pdfAccessLifetime,
+ pdfAccessSessionLifetime,
+} from "@app/services/pdfAccessService";
/** An input that did not survive the batch, with the error it failed on. */
export interface FailedInput {
@@ -63,6 +66,10 @@ export const useToolApiCalls = <TParams = void>() => {
const cancellation = axios.CancelToken.source();
cancelTokenRef.current = cancellation;
+ const operationCancellation = cancellation.token.toAbortSignal();
+ const sessionLifetime = pdfAccessSessionLifetime();
+ const sourceLifetimes = validFiles.map(pdfAccessLifetime);
+ const outputsBySource = new Map<FileId, File[]>();
// Params are the same for every file, so resolve the endpoint once. A null
// endpoint means the tool has no backend call (e.g. client-side tools) and
@@ -89,9 +96,20 @@ export const useToolApiCalls = <TParams = void>() => {
onProgress({ current: i + 1, total, currentFileName: file.name });
onStatus(`Processing ${file.name} (${i + 1}/${total})`);
+ const sourceLifetime = sourceLifetimes[i];
+ const { signal: fileSignal, dispose } = combineAbortSignals([
+ operationCancellation,
+ sourceLifetime,
+ ]);
try {
cancellation.token.throwIfRequested();
- const workingFile = await prepareUnlockedFile(file, endpoint);
+ sourceLifetime.throwIfAborted();
+ const workingFile = await prepareUnlockedFile(
+ file,
+ endpoint,
+ fileSignal,
+ cancellation.token,
+ );
const formData = config.buildFormData(params, workingFile);
console.debug("[processFiles] POST", { endpoint, name: file.name });
const response =
@@ -110,6 +128,7 @@ export const useToolApiCalls = <TParams = void>() => {
: await apiClient.post(endpoint, formData, {
responseType: "blob",
cancelToken: cancellation.token,
+ signal: sourceLifetime,
});
console.debug("[processFiles] Response OK", {
name: file.name,
@@ -141,11 +160,17 @@ export const useToolApiCalls = <TParams = void>() => {
getPdfAccess(file)?.password ||
"",
));
- for (const output of responseFiles)
- rememberPdfAccess(
+ for (const output of responseFiles) {
+ const access = await inspectLocalPdfAccess(
output,
- await unlockPdfForSession(output, password, cancellation.token),
+ password,
+ fileSignal,
);
+ cancellation.token.throwIfRequested();
+ if (fileSignal.aborted)
+ throw new axios.CanceledError("Operation cancelled");
+ rememberPdfAccess(output, access);
+ }
}
// Guard: some endpoints may return an empty/0-byte file with 200
const empty = isEmptyOutput(responseFiles);
@@ -166,13 +191,16 @@ export const useToolApiCalls = <TParams = void>() => {
}
continue;
}
+ sourceLifetime.throwIfAborted();
const protectedFiles = await protectUnlockedResults(
responseFiles,
[file],
endpoint,
);
cancellation.token.throwIfRequested();
+ sourceLifetime.throwIfAborted();
processedFiles.push(...protectedFiles);
+ outputsBySource.set(file.fileId, protectedFiles);
// record source id as successful
successSourceIds.push(file.fileId);
console.debug("[processFiles] Success", {
@@ -180,6 +208,13 @@ export const useToolApiCalls = <TParams = void>() => {
produced: responseFiles.length,
});
} catch (error) {
+ if (cancellation.token.reason || sessionLifetime.aborted) {
+ throw new Error("Operation was cancelled", { cause: error });
+ }
+ if (sourceLifetime.aborted) {
+ unprocessedSourceIds.push(file.fileId);
+ continue;
+ }
if (isSignupRequiredError(error)) {
if (processedFiles.length === 0) throw error;
unprocessedSourceIds.push(
@@ -187,7 +222,10 @@ export const useToolApiCalls = <TParams = void>() => {
);
break;
}
- if (axios.isCancel(error)) {
+ if (
+ axios.isCancel(error) ||
+ (error instanceof DOMException && error.name === "AbortError")
+ ) {
throw new Error("Operation was cancelled", { cause: error });
}
console.error("[processFiles] Failed", { name: file.name, error });
@@ -199,9 +237,22 @@ export const useToolApiCalls = <TParams = void>() => {
} catch (e) {
console.debug("markFileError", e);
}
+ } finally {
+ dispose();
}
}
+ // A completed source may be closed while another request is still running.
+ for (let i = 0; i < validFiles.length; i++) {
+ const id = validFiles[i].fileId;
+ if (!sourceLifetimes[i].aborted || !outputsBySource.has(id)) continue;
+ const outputs = new Set(outputsBySource.get(id));
+ for (let j = processedFiles.length - 1; j >= 0; j--)
+ if (outputs.has(processedFiles[j])) processedFiles.splice(j, 1);
+ successSourceIds.splice(successSourceIds.indexOf(id), 1);
+ unprocessedSourceIds.push(id);
+ }
+
if (failedFiles.length > 0 && processedFiles.length === 0) {
if (failedInputs.length === 1) throw failedInputs[0].error;
throw new Error(
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index 9d8ab79ad3..b3b7e52a82 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -122,6 +122,7 @@ export const useToolOperation = <TParams>(
const { actions: fileActions } = useFileContext();
const { processFiles, cancelOperation: cancelApiCalls } =
useToolApiCalls<TParams>();
+ const inspectionCancellation = useRef<AbortController | null>(null);
const {
generateThumbnails,
createDownloadInfo,
@@ -241,6 +242,9 @@ export const useToolOperation = <TParams>(
const stub = selectors.getStirlingFileStub(file.fileId);
return stub ? policySourceIds(stub) : [file.fileId];
});
+ const cancellation = new AbortController();
+ inspectionCancellation.current?.abort();
+ inspectionCancellation.current = cancellation;
try {
assertFilesNotBlocked(policyIds);
} catch (error) {
@@ -336,6 +340,10 @@ export const useToolOperation = <TParams>(
file.fileId,
t(`${config.operationType}.title`, config.operationType),
),
+ cancellation.signal,
+ (file) =>
+ selectors.getStirlingFileStub(file.fileId)?.processedFile
+ ?.isEncrypted === true,
);
if (!permitted) return;
let processedFiles: File[];
@@ -348,7 +356,11 @@ export const useToolOperation = <TParams>(
filesForAPI.push(
config.toolType === ToolType.singleFile
? file
- : await prepareUnlockedFile(file, runtimeEndpoint),
+ : await prepareUnlockedFile(
+ file,
+ runtimeEndpoint,
+ cancellation.signal,
+ ),
);
}
@@ -793,6 +805,7 @@ export const useToolOperation = <TParams>(
onToolRunComplete();
}
} catch (error) {
+ if (cancellation.signal.aborted) return;
if (isSignupRequiredError(error)) {
actions.setStatus("");
return;
@@ -824,6 +837,8 @@ export const useToolOperation = <TParams>(
actions.setError(errorMessage);
actions.setStatus("");
} finally {
+ if (inspectionCancellation.current === cancellation)
+ inspectionCancellation.current = null;
window.removeEventListener(FILE_EVENTS.markError, errorListener);
actions.setLoading(false);
actions.setProgress(null);
@@ -854,6 +869,7 @@ export const useToolOperation = <TParams>(
);
const cancelOperation = useCallback(() => {
+ inspectionCancellation.current?.abort();
cancelApiCalls();
actions.setLoading(false);
actions.setProgress(null);
@@ -870,6 +886,7 @@ export const useToolOperation = <TParams>(
// Cleanup on unmount to prevent memory leaks
useEffect(() => {
return () => {
+ inspectionCancellation.current?.abort();
lastOperationRef.current = null;
};
}, []);
diff --git a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
index 1bf1205739..167762092a 100644
--- a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
@@ -2,7 +2,7 @@ import { useState, useEffect } from "react";
import { StirlingFileStub } from "@app/types/fileContext";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import { useFileManagement, useFileSelectors } from "@app/contexts/FileContext";
/**
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
index 382ab8d94e..7014b7bddf 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
@@ -7,7 +7,7 @@ import {
clearPdfAccess,
forgetPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
const storage = vi.hoisted(() => ({
loadFile: vi.fn(),
@@ -32,8 +32,6 @@ const access = {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
};
const id = "protected-preview" as FileId;
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.ts b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
index 403e379b56..7e20704d02 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
@@ -5,7 +5,7 @@ import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
import { readDiskFile } from "@app/services/localFolderContents";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
const THUMBNAIL_SIZE_LIMIT = 100 * 1024 * 1024; // 100MB
diff --git a/frontend/editor/src/core/hooks/usePdfAccess.ts b/frontend/editor/src/core/hooks/usePdfAccess.ts
index c745c66e39..169fd3a035 100644
--- a/frontend/editor/src/core/hooks/usePdfAccess.ts
+++ b/frontend/editor/src/core/hooks/usePdfAccess.ts
@@ -1,11 +1,9 @@
-import { useEffect, useSyncExternalStore } from "react";
-import { unlockPdfForSession } from "@app/services/pdfSessionUnlock";
+import { useSyncExternalStore } from "react";
import {
getPdfAccess,
- rememberPdfAccess,
pdfAccessRevision,
subscribePdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
/** Observe session access without persisting the password in document metadata. */
export function usePdfAccess(file: Blob | string | null | undefined) {
@@ -14,19 +12,5 @@ export function usePdfAccess(file: Blob | string | null | undefined) {
pdfAccessRevision,
pdfAccessRevision,
);
- useEffect(() => {
- if (!(file instanceof File) || getPdfAccess(file)) return;
- let cancelled = false;
- void unlockPdfForSession(file, "")
- .then((access) => {
- if (!cancelled && !getPdfAccess(file)) rememberPdfAccess(file, access);
- })
- .catch(() => {
- /* A failed inspection cannot grant permissions. */
- });
- return () => {
- cancelled = true;
- };
- }, [file]);
return getPdfAccess(file);
}
diff --git a/frontend/editor/src/core/services/fileAnalyzer.test.ts b/frontend/editor/src/core/services/fileAnalyzer.test.ts
index d28fc3674a..66cfadf992 100644
--- a/frontend/editor/src/core/services/fileAnalyzer.test.ts
+++ b/frontend/editor/src/core/services/fileAnalyzer.test.ts
@@ -1,14 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { FileAnalyzer } from "@app/services/fileAnalyzer";
import { pdfWorkerManager } from "@app/services/pdfWorkerManager";
-import { ensurePdfAccess } from "@app/services/pdfSessionUnlock";
-import { clearPdfAccess } from "@app/services/pdfPasswordStore";
+import {
+ ensureLocalPdfAccess,
+ clearPdfAccess,
+} from "@app/services/pdfAccessService";
+
import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
vi.mock("@app/services/pdfWorkerManager", () => ({
pdfWorkerManager: { createDocument: vi.fn(), destroyDocument: vi.fn() },
}));
-vi.mock("@app/services/pdfSessionUnlock", () => ({ ensurePdfAccess: vi.fn() }));
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ ensureLocalPdfAccess: vi.fn(),
+}));
beforeEach(() => {
clearPdfAccess();
@@ -40,18 +46,25 @@ describe("large PDF encryption detection", () => {
const slices = vi.spyOn(file, "slice");
expect(await FileAnalyzer.isPDFEncrypted(file)).toBe(true);
- expect(ensurePdfAccess).not.toHaveBeenCalled();
+ expect(ensureLocalPdfAccess).not.toHaveBeenCalled();
expect(pdfWorkerManager.createDocument).not.toHaveBeenCalled();
expect(readAll).not.toHaveBeenCalled();
expect(slices).toHaveBeenCalledTimes(2);
},
);
+ it("defers authentication of small marked PDFs until opening too", async () => {
+ const file = new File(["%PDF-1.7 /Encrypt 1 0 R"], "large.pdf");
+ expect(await FileAnalyzer.isPDFEncrypted(file)).toBe(true);
+ expect(ensureLocalPdfAccess).not.toHaveBeenCalled();
+ expect(pdfWorkerManager.createDocument).not.toHaveBeenCalled();
+ });
+
it("does not classify a large unmarked PDF as encrypted", async () => {
const file = new File(["%PDF-1.7"], "large.pdf");
Object.defineProperty(file, "size", { value: LARGE_PDF_PARSE_LIMIT });
expect(await FileAnalyzer.isPDFEncrypted(file)).toBe(false);
- expect(ensurePdfAccess).not.toHaveBeenCalled();
+ expect(ensureLocalPdfAccess).not.toHaveBeenCalled();
expect(pdfWorkerManager.createDocument).not.toHaveBeenCalled();
});
});
diff --git a/frontend/editor/src/core/services/fileAnalyzer.ts b/frontend/editor/src/core/services/fileAnalyzer.ts
index a35d922fb3..91648f98a7 100644
--- a/frontend/editor/src/core/services/fileAnalyzer.ts
+++ b/frontend/editor/src/core/services/fileAnalyzer.ts
@@ -1,40 +1,9 @@
import { FileAnalysis, ProcessingStrategy } from "@app/types/processing";
import { pdfWorkerManager } from "@app/services/pdfWorkerManager";
-import { ensurePdfAccess } from "@app/services/pdfSessionUnlock";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
-import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
-import type { PDFDocumentProxy } from "pdfjs-dist";
-
-// Bounded window scanned at each end of the PDF for an /Encrypt entry. The
-// trailer sits at the tail; linearized files also keep a first-page trailer at
-// the head. Sliced, so a multi-GB file is never read into memory.
-const ENCRYPT_PROBE_BYTES = 64 * 1024;
-const PROBE_TIMEOUT = "pdf-probe-timeout";
-const PROBE_TIMEOUT_MS = 30_000;
-
-function bufferHasEncryptMarker(buffer: ArrayBuffer): boolean {
- const view = new Uint8Array(buffer);
- // "/Encrypt" as ASCII bytes
- const needle = [0x2f, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74];
- outer: for (let i = 0; i <= view.length - needle.length; i++) {
- for (let j = 0; j < needle.length; j++) {
- if (view[i + j] !== needle[j]) continue outer;
- }
- return true;
- }
- return false;
-}
+import { getPdfAccess } from "@app/services/pdfAccessService";
-async function hasEncryptMarker(file: File): Promise<boolean> {
- const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
- if (bufferHasEncryptMarker(await file.slice(tailStart).arrayBuffer())) {
- return true;
- }
- if (tailStart === 0) return false;
- return bufferHasEncryptMarker(
- await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer(),
- );
-}
+import { looksEncryptedFromTrailer } from "@app/utils/pdfEncryptionProbe";
+import type { PDFDocumentProxy } from "pdfjs-dist";
export class FileAnalyzer {
private static readonly SIZE_THRESHOLDS = {
@@ -90,65 +59,11 @@ export class FileAnalyzer {
return analysis;
}
- /** Detect encryption and admit empty-password documents without prompting.
- * The marker is an upload optimisation, not authorisation; operations inspect original bytes.
- */
+ /** Admission hint only: never grants access. Authentication waits until the file is opened. */
static async isPDFEncrypted(file: File): Promise<boolean> {
const access = getPdfAccess(file);
if (access) return access.encrypted;
- if (!(await hasEncryptMarker(file))) return false;
- if (file.size >= LARGE_PDF_PARSE_LIMIT) return true;
- if (await this.requiresOpeningPassword(file)) return true;
- try {
- return (await ensurePdfAccess(file)).encrypted;
- } catch {
- return true;
- }
- }
-
- private static async requiresOpeningPassword(file: File): Promise<boolean> {
- if (!(await hasEncryptMarker(file))) return false;
-
- // Too big to hand pdf.js: that full-buffer parse is the renderer OOM the
- // large-file path exists to avoid, so trust the marker instead of it.
- if (file.size >= LARGE_PDF_PARSE_LIMIT) return true;
-
- const arrayBuffer = await file.arrayBuffer();
- let timedOut = false;
- let timer: ReturnType<typeof setTimeout> | undefined;
- const opening = pdfWorkerManager
- .createDocument(arrayBuffer, { stopAtErrors: false, verbosity: 0 })
- .then((pdf) => {
- // Arrived after the timeout won the race - nothing else frees it.
- if (timedOut) pdfWorkerManager.destroyDocument(pdf);
- return pdf;
- });
-
- try {
- const pdf = await Promise.race<PDFDocumentProxy>([
- opening,
- new Promise<never>((_, reject) => {
- timer = setTimeout(() => {
- timedOut = true;
- reject(new Error(PROBE_TIMEOUT));
- }, PROBE_TIMEOUT_MS);
- }),
- ]);
- pdfWorkerManager.destroyDocument(pdf);
- // pdf.js opened it — owner-password-only case, no prompt needed.
- return false;
- } catch (error) {
- const errorMessage =
- error instanceof Error ? error.message.toLowerCase() : "";
- // Unconfirmed either way; the /Encrypt marker is the better guess, and a
- // spurious prompt beats a card that never stops spinning.
- if (errorMessage === PROBE_TIMEOUT) return true;
- return (
- errorMessage.includes("password") || errorMessage.includes("encrypted")
- );
- } finally {
- clearTimeout(timer);
- }
+ return looksEncryptedFromTrailer(file);
}
static async quickPDFAnalysis(file: File): Promise<{
diff --git a/frontend/editor/src/core/services/fileStorage.encryption.test.ts b/frontend/editor/src/core/services/fileStorage.encryption.test.ts
index 1a9be0c6b8..153506feb7 100644
--- a/frontend/editor/src/core/services/fileStorage.encryption.test.ts
+++ b/frontend/editor/src/core/services/fileStorage.encryption.test.ts
@@ -16,7 +16,7 @@ import {
clearPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
afterEach(async () => {
clearPdfAccess();
@@ -36,8 +36,6 @@ describe("stored PDF protection metadata", () => {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
await fileStorage.storeStirlingFile(original, stub);
@@ -51,7 +49,11 @@ describe("stored PDF protection metadata", () => {
type: "application/pdf",
});
const stub = createNewStirlingFileStub(file);
- stub.processedFile = { pages: [], isEncrypted: true };
+ stub.processedFile = {
+ pages: [],
+ isEncrypted: true,
+ requiresOpeningPassword: true,
+ };
stub.thumbnailUrl = "data:image/png;base64,private";
await fileStorage.storeStirlingFile(
createStirlingFile(file, stub.id),
@@ -65,7 +67,10 @@ describe("stored PDF protection metadata", () => {
];
expect(reads).toHaveLength(3);
for (const read of reads)
- expect(read?.processedFile?.isEncrypted).toBe(true);
+ expect(read?.processedFile).toMatchObject({
+ isEncrypted: true,
+ requiresOpeningPassword: true,
+ });
});
it("discards legacy PDF previews whose encryption status was never stored", async () => {
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index 83855d23e0..06fcb67a05 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -18,7 +18,7 @@ import {
} from "@app/services/indexedDBManager";
import { alert } from "@app/components/toast";
import i18n from "i18next";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
/**
* Storage record - single source of truth
@@ -34,8 +34,9 @@ export interface StoredStirlingFileRecord extends BaseFileMetadata {
quickKey: string; // Matches runtime StirlingFile.quickKey exactly
thumbnail?: string;
thumbnailStoredAt?: number; // Epoch ms - sliding 30-day TTL
- /** Whether opening these bytes requires a password; undefined for legacy records. */
+ /** Encryption hint only; does not grant session access. */
isEncrypted?: boolean;
+ requiresOpeningPassword?: boolean;
url?: string; // For compatibility with existing components
// Disk path this file came from (desktop only). Persisted so the link to the
// real file survives a reload - without it every restart drops to the stored copy.
@@ -383,6 +384,9 @@ class FileStorageService {
isEncrypted:
getPdfAccess(stirlingFile)?.encrypted ??
stub.processedFile?.isEncrypted,
+ requiresOpeningPassword:
+ getPdfAccess(stirlingFile)?.requiresOpeningPassword ??
+ stub.processedFile?.requiresOpeningPassword,
localFilePath: stub.localFilePath,
diskSyncedSize: stub.diskSyncedSize,
diskSyncedModifiedMs: stub.diskSyncedModifiedMs,
@@ -802,7 +806,11 @@ class FileStorageService {
processedFile:
record.isEncrypted === undefined
? undefined
- : { pages: [], isEncrypted: record.isEncrypted },
+ : {
+ pages: [],
+ isEncrypted: record.isEncrypted,
+ requiresOpeningPassword: record.requiresOpeningPassword,
+ },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
@@ -882,7 +890,11 @@ class FileStorageService {
processedFile:
record.isEncrypted === undefined
? undefined
- : { pages: [], isEncrypted: record.isEncrypted },
+ : {
+ pages: [],
+ isEncrypted: record.isEncrypted,
+ requiresOpeningPassword: record.requiresOpeningPassword,
+ },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
@@ -994,7 +1006,11 @@ class FileStorageService {
processedFile:
record.isEncrypted === undefined
? undefined
- : { pages: [], isEncrypted: record.isEncrypted },
+ : {
+ pages: [],
+ isEncrypted: record.isEncrypted,
+ requiresOpeningPassword: record.requiresOpeningPassword,
+ },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
diff --git a/frontend/editor/src/core/services/pdfAccessService.test.ts b/frontend/editor/src/core/services/pdfAccessService.test.ts
new file mode 100644
index 0000000000..ca6edfbb01
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfAccessService.test.ts
@@ -0,0 +1,298 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ clearPdfAccess,
+ bindPdfAccess,
+ forgetPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+ ensureLocalPdfAccess,
+ inspectLocalPdfAccess,
+ setPdfAccessPolicy,
+ subscribePdfAccess,
+} from "@app/services/pdfAccessService";
+
+import { preflightPdfOperation } from "@app/services/pdfSessionUnlock";
+import { createStirlingFile } from "@app/types/fileContext";
+import apiClient from "@app/services/apiClient";
+
+vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+
+const workers = vi.hoisted(
+ () =>
+ [] as {
+ onmessage?: (event: {
+ data: { access: PdfAccess } | { error: string; code: number };
+ }) => void;
+ onerror?: () => void;
+ postMessage: ReturnType<typeof vi.fn>;
+ terminate: ReturnType<typeof vi.fn>;
+ }[],
+);
+
+vi.mock("@app/workers/pdfAccessWorker?worker", () => ({
+ default: class {
+ postMessage = vi.fn();
+ terminate = vi.fn();
+ constructor() {
+ workers.push(this);
+ }
+ },
+}));
+vi.mock("@app/services/wasmPrecompiler", () => ({
+ pdfiumWasmUrl: "/pdfium.wasm",
+ pdfiumWasmModulePromise: Promise.resolve("precompiled-module"),
+ startEagerWasmCompilation: vi.fn(),
+}));
+
+const access: PdfAccess = {
+ password: "reader",
+ encrypted: true,
+ ownerAuthenticated: false,
+ signed: false,
+ permissions: 0,
+ pageCount: 1,
+};
+
+const nativeAny = AbortSignal.any;
+beforeEach(() => {
+ Object.defineProperty(AbortSignal, "any", { value: undefined });
+ clearPdfAccess();
+ setPdfAccessPolicy(undefined);
+ workers.length = 0;
+});
+afterEach(() => {
+ clearPdfAccess();
+ setPdfAccessPolicy(undefined);
+ Object.defineProperty(AbortSignal, "any", { value: nativeAny });
+ vi.useRealTimers();
+});
+
+describe("local inspection lifetime", () => {
+ it("applies active policy to fresh inspections and subsequent policy changes", async () => {
+ const file = new File(["PDF"], "source.pdf", { type: "application/pdf" });
+ setPdfAccessPolicy(false);
+ const pending = ensureLocalPdfAccess(file);
+ workers[0].onmessage?.({ data: { access } });
+ const inspected = await pending;
+ expect(inspected.honorOwnerPasswords).toBe(false);
+ expect(getPdfAccess(file)).toBe(inspected);
+ const changed = vi.fn();
+ const unsubscribe = subscribePdfAccess(changed);
+ try {
+ setPdfAccessPolicy(true);
+ expect(changed).toHaveBeenCalledOnce();
+ const restricted = getPdfAccess(file);
+ expect(restricted?.honorOwnerPasswords).toBe(true);
+ expect(restricted?.ownerAuthenticated).toBe(false);
+ expect(getPdfAccess(file)).toBe(restricted);
+ expect(
+ rememberPdfAccess(file, { ...access, honorOwnerPasswords: false })
+ .honorOwnerPasswords,
+ ).toBe(true);
+ } finally {
+ unsubscribe();
+ }
+ });
+
+ it("passes the compiled module to the worker", async () => {
+ const file = new File(["PDF"], "plain.pdf");
+ const result = inspectLocalPdfAccess(file);
+ await vi.waitFor(() =>
+ expect(workers[0].postMessage).toHaveBeenCalledWith({
+ file,
+ password: "",
+ wasmUrl: "/pdfium.wasm",
+ wasmModule: "precompiled-module",
+ }),
+ );
+ workers[0].onmessage?.({ data: { access } });
+ await result;
+ });
+
+ it("bounds concurrent inspections and drops a cancelled queued file", async () => {
+ const files = Array.from(
+ { length: 4 },
+ (_, i) => new File(["PDF"], `${i}.pdf`),
+ );
+ const controller = new AbortController();
+ const results = files.map((file, i) =>
+ inspectLocalPdfAccess(file, "", i === 2 ? controller.signal : undefined),
+ );
+ const cancelled = expect(results[2]).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ expect(workers).toHaveLength(2);
+ controller.abort();
+ await cancelled;
+ workers[0].onmessage?.({ data: { access } });
+ expect(workers).toHaveLength(3);
+ await vi.waitFor(() =>
+ expect(workers[2].postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ file: files[3] }),
+ ),
+ );
+ workers[1].onmessage?.({ data: { access } });
+ workers[2].onmessage?.({ data: { access } });
+ await Promise.all([results[0], results[1], results[3]]);
+ });
+
+ it("still verifies files over 100 MiB, with no other inspection heap active", async () => {
+ const file = new File(["PDF"], "large.pdf");
+ Object.defineProperty(file, "size", { value: 150 * 1024 * 1024 });
+ const large = ensureLocalPdfAccess(file);
+ const small = inspectLocalPdfAccess(new File(["PDF"], "small.pdf"));
+ expect(workers).toHaveLength(1);
+ expect(getPdfAccess(file)).toBeUndefined();
+ workers[0].onmessage?.({ data: { access } });
+ await expect(large).resolves.toMatchObject({ encrypted: true });
+ expect(workers).toHaveLength(2);
+ workers[1].onmessage?.({ data: { access } });
+ await small;
+ });
+
+ it("terminates stalled inspection, releases its slot, and leaves access unknown", async () => {
+ vi.useFakeTimers();
+ const file = new File(["PDF"], "stalled.pdf");
+ Object.defineProperty(file, "size", { value: 150 * 1024 * 1024 });
+ const stalled = ensureLocalPdfAccess(file);
+ const failure = expect(stalled).rejects.toMatchObject({
+ name: "TimeoutError",
+ });
+ const next = inspectLocalPdfAccess(new File(["PDF"], "next.pdf"));
+ await vi.advanceTimersByTimeAsync(30_000);
+ await failure;
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ workers[0].onmessage?.({ data: { access } });
+ expect(getPdfAccess(file)).toBeUndefined();
+ expect(workers).toHaveLength(2);
+ workers[1].onmessage?.({ data: { access } });
+ await next;
+ });
+ it("shares a worker without letting one consumer cancel another", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const first = new AbortController();
+ const cancelled = inspectLocalPdfAccess(file, "reader", first.signal);
+ const rejected = expect(cancelled).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ const retained = inspectLocalPdfAccess(file, "reader");
+ expect(workers).toHaveLength(1);
+ first.abort();
+ await rejected;
+ expect(workers[0].terminate).not.toHaveBeenCalled();
+ workers[0].onmessage?.({ data: { access } });
+ await expect(retained).resolves.toEqual(access);
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ expect(getPdfAccess(file)).toBeUndefined();
+ });
+
+ it("starts a new inspection after every consumer cancels", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const first = new AbortController();
+ const cancelled = inspectLocalPdfAccess(file, "reader", first.signal);
+ const rejected = expect(cancelled).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ first.abort();
+ const retry = inspectLocalPdfAccess(file, "reader");
+ expect(workers).toHaveLength(2);
+ workers[1].onmessage?.({ data: { access } });
+ await rejected;
+ await expect(retry).resolves.toEqual(access);
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ });
+
+ it("keeps different credentials in separate inspections", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const reader = inspectLocalPdfAccess(file, "reader");
+ const owner = inspectLocalPdfAccess(file, "owner");
+ expect(workers).toHaveLength(2);
+ workers[0].onmessage?.({ data: { access } });
+ workers[1].onmessage?.({
+ data: {
+ access: { ...access, password: "owner", ownerAuthenticated: true },
+ },
+ });
+ await expect(reader).resolves.toMatchObject({
+ password: "reader",
+ ownerAuthenticated: false,
+ });
+ await expect(owner).resolves.toMatchObject({
+ password: "owner",
+ ownerAuthenticated: true,
+ });
+ });
+
+ it("reuses access without reading the file or creating a worker", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const stored = rememberPdfAccess(file, access);
+ expect(await ensureLocalPdfAccess(file)).toBe(stored);
+ expect(workers).toHaveLength(0);
+ });
+
+ it("releases the worker after publishing a local inspection", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const result = ensureLocalPdfAccess(file);
+ expect(getPdfAccess(file)).toBeUndefined();
+ workers[0].onmessage?.({ data: { access } });
+ await expect(result).resolves.toMatchObject(access);
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ });
+
+ it.each(["abort", "logout", "close", "replace"])(
+ "discards credentials and terminates work on %s",
+ async (action) => {
+ const file = createStirlingFile(new File(["PDF"], "protected.pdf"));
+ bindPdfAccess(file, file.fileId);
+ const controller = new AbortController();
+ const result = ensureLocalPdfAccess(file, controller.signal);
+ const rejected = expect(result).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ if (action === "abort") controller.abort();
+ else if (action === "close") forgetPdfAccess([file.fileId]);
+ else if (action === "replace")
+ bindPdfAccess(new File(["replacement"], file.name), file.fileId);
+ else clearPdfAccess();
+ await rejected;
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ workers[0].onmessage?.({ data: { access } });
+ expect(getPdfAccess(file)).toBeUndefined();
+ },
+ );
+
+ it("preflights uncached tool inputs locally and reuses the result", async () => {
+ const file = createStirlingFile(new File(["PDF"], "protected.pdf"));
+ const ownerPrompt = vi.fn();
+ const preflight = () =>
+ preflightPdfOperation(
+ [file],
+ "/api/v1/general/rotate-pdf",
+ false,
+ ownerPrompt,
+ );
+ const pending = preflight();
+ workers[0].onmessage?.({
+ data: { access: { ...access, permissions: -4 } },
+ });
+ await expect(pending).resolves.toBe(true);
+ await expect(preflight()).resolves.toBe(true);
+ expect(workers).toHaveLength(1);
+ expect(ownerPrompt).not.toHaveBeenCalled();
+ expect(apiClient.post).not.toHaveBeenCalled();
+ });
+
+ it("preserves password error classification and permits retry", async () => {
+ const file = new File(["PDF"], "protected.pdf");
+ const failed = inspectLocalPdfAccess(file, "incorrect");
+ const rejected = expect(failed).rejects.toMatchObject({ code: 4 });
+ workers[0].onmessage?.({ data: { error: "Unable to open PDF", code: 4 } });
+ await rejected;
+ expect(workers[0].terminate).toHaveBeenCalledOnce();
+ const retry = inspectLocalPdfAccess(file, "reader");
+ workers[1].onmessage?.({ data: { access } });
+ await expect(retry).resolves.toEqual(access);
+ expect(getPdfAccess(file)).toBeUndefined();
+ });
+});
diff --git a/frontend/editor/src/core/services/pdfAccessService.ts b/frontend/editor/src/core/services/pdfAccessService.ts
new file mode 100644
index 0000000000..9121a31ed1
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfAccessService.ts
@@ -0,0 +1,421 @@
+/** Owns session access, file lifetimes and local inspection. Credentials are never persisted. */
+import type { FileId } from "@app/types/file";
+import { combineAbortSignals } from "@app/utils/combineAbortSignals";
+import PdfAccessWorker from "@app/workers/pdfAccessWorker?worker";
+import type {
+ PdfAccessRequest,
+ PdfAccessResponse,
+} from "@app/workers/pdfAccessWorker";
+import {
+ pdfiumWasmUrl,
+ pdfiumWasmModulePromise,
+ startEagerWasmCompilation,
+} from "@app/services/wasmPrecompiler";
+
+/** Session-only access to encrypted bytes. Never serialize this object or include it in tool parameters. */
+export interface PdfAccess {
+ password: string;
+ openingPassword?: string;
+ openingAuthenticated?: boolean;
+ encrypted: boolean;
+ requiresOpeningPassword?: boolean;
+ signed: boolean;
+ ownerAuthenticated: boolean;
+ /** Active instance policy; absent configuration defaults to enforcing restrictions. */
+ honorOwnerPasswords?: boolean;
+ permissions: number;
+ encryptionRevision?: number;
+ pageCount: number;
+}
+
+let accessByFile = new WeakMap<Blob, PdfAccess>();
+let ownerPasswordPolicy: boolean | undefined;
+let sessionLifetime = new AbortController();
+let accessLifetimes = new WeakMap<
+ Blob,
+ { controller: AbortController; signal: AbortSignal }
+>();
+const filesById = new Map<string, WeakRef<Blob>>();
+const listeners = new Set<() => void>();
+let revision = 0;
+/** Sets the active server policy for every access path; undefined releases the provider's policy. */
+export function setPdfAccessPolicy(
+ honorOwnerPasswords: boolean | undefined,
+): void {
+ if (ownerPasswordPolicy === honorOwnerPasswords) return;
+ ownerPasswordPolicy = honorOwnerPasswords;
+ publish();
+}
+
+/** Aborted by logout or FileContext teardown, independently of individual document closures. */
+export function pdfAccessSessionLifetime(): AbortSignal {
+ return sessionLifetime.signal;
+}
+/** Aborted by replacement, close or logout; also identifies the generation allowed to retain credentials. */
+export function pdfAccessLifetime(file: Blob): AbortSignal {
+ let lifetime = accessLifetimes.get(file);
+ if (!lifetime) {
+ const controller = new AbortController();
+ lifetime = {
+ controller,
+ signal: combineAbortSignals([controller.signal, sessionLifetime.signal])
+ .signal,
+ };
+ accessLifetimes.set(file, lifetime);
+ }
+ return lifetime.signal;
+}
+
+/** Only call after a parser or a protection-preserving export proves these bytes unencrypted. */
+export function rememberUnencryptedPdf(
+ file: Blob,
+ pageCount: number,
+): PdfAccess {
+ return rememberPdfAccess(file, {
+ password: "",
+ encrypted: false,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: -4,
+ pageCount,
+ });
+}
+
+/** For viewer exports that cannot add encryption; arbitrary tool outputs must inspect their own bytes. */
+export function rememberPlainPdfExport(source: Blob, output: Blob): void {
+ const access = getPdfAccess(source);
+ if (access?.encrypted === false)
+ rememberUnencryptedPdf(output, access.pageCount);
+}
+
+function publish(): void {
+ revision++;
+ for (const listener of listeners) listener();
+}
+
+/** Look up credentials for these exact bytes; a replacement with the same filename must unlock separately. */
+export function getPdfAccess(
+ file: Blob | string | null | undefined,
+): PdfAccess | undefined {
+ if (!file) return undefined;
+ const blob = typeof file === "string" ? filesById.get(file)?.deref() : file;
+ if (!blob) return undefined;
+ let access = accessByFile.get(blob);
+ if (
+ access &&
+ ownerPasswordPolicy !== undefined &&
+ access.honorOwnerPasswords !== ownerPasswordPolicy
+ ) {
+ access = { ...access, honorOwnerPasswords: ownerPasswordPolicy };
+ accessByFile.set(blob, access);
+ }
+ return access;
+}
+
+/** Retain access without changing the file; returns the identity used by preview cleanup. */
+export function rememberPdfAccess(file: Blob, access: PdfAccess): PdfAccess {
+ const previous = accessByFile.get(file);
+ if (previous?.password === access.password) {
+ access = {
+ ...previous,
+ ...access,
+ honorOwnerPasswords:
+ access.honorOwnerPasswords ?? previous.honorOwnerPasswords,
+ openingAuthenticated:
+ access.openingAuthenticated ?? previous.openingAuthenticated,
+ requiresOpeningPassword:
+ access.requiresOpeningPassword ?? previous.requiresOpeningPassword,
+ };
+ }
+ const storedAccess = {
+ ...access,
+ honorOwnerPasswords: ownerPasswordPolicy ?? access.honorOwnerPasswords,
+ openingPassword: access.encrypted
+ ? access.openingAuthenticated || !access.ownerAuthenticated
+ ? access.password
+ : (access.openingPassword ?? accessByFile.get(file)?.openingPassword)
+ : undefined,
+ };
+ accessByFile.set(file, storedAccess);
+ if ("fileId" in file && typeof file.fileId === "string")
+ filesById.set(file.fileId, new WeakRef(file));
+ publish();
+ return storedAccess;
+}
+
+/** Bind FileContext identity without retaining closed/library-only bytes; replacements invalidate pending access. */
+export function bindPdfAccess(file: Blob, id: FileId): void {
+ const previous = filesById.get(id)?.deref();
+ if (previous && previous !== file) {
+ accessByFile.delete(previous);
+ accessLifetimes.get(previous)?.controller.abort();
+ accessLifetimes.delete(previous);
+ filesById.delete(id);
+ }
+ filesById.set(id, new WeakRef(file));
+ if (previous && previous !== file) publish();
+}
+
+/** Closing a document drops its credential; reopening requires authentication again. */
+export function forgetPdfAccess(ids: readonly string[]): void {
+ for (const id of ids) {
+ const file = filesById.get(id)?.deref();
+ if (file) {
+ accessByFile.delete(file);
+ accessLifetimes.get(file)?.controller.abort();
+ accessLifetimes.delete(file);
+ }
+ filesById.delete(id);
+ }
+ publish();
+}
+
+/** Drop preview-owned access unless the same bytes have since entered FileContext. */
+export function forgetPreviewPdfAccess(file: Blob, access: PdfAccess): void {
+ if (
+ accessByFile.get(file) !== access ||
+ [...filesById.values()].some((ref) => ref.deref() === file)
+ )
+ return;
+ accessByFile.delete(file);
+ accessLifetimes.get(file)?.controller.abort();
+ accessLifetimes.delete(file);
+ publish();
+}
+
+/** Clear all credentials on logout or FileContext teardown. */
+export function clearPdfAccess(): void {
+ sessionLifetime.abort();
+ sessionLifetime = new AbortController();
+ accessLifetimes = new WeakMap();
+ accessByFile = new WeakMap();
+ filesById.clear();
+ publish();
+}
+
+/** Subscribe to unlock/lock changes without exposing credentials in React state. */
+export function subscribePdfAccess(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** Monotonic snapshot for useSyncExternalStore. */
+export function pdfAccessRevision(): number {
+ return revision;
+}
+
+interface Inspection {
+ controller: AbortController;
+ promise: Promise<PdfAccess>;
+ consumers: number;
+}
+
+const inspections = new WeakMap<Blob, Map<string, Inspection>>();
+const INSPECTION_TIMEOUT_MS = 30_000;
+const MAX_INSPECTION_WORKERS = 2;
+// Each worker holds the input buffer and a WASM copy. Larger files run alone.
+const INSPECTION_BYTE_BUDGET = 100 * 1024 * 1024;
+const inspectionQueue: { size: number; start: () => void }[] = [];
+let activeInspections = 0;
+let inspectingBytes = 0;
+
+function drainInspections(): void {
+ while (inspectionQueue.length && activeInspections < MAX_INSPECTION_WORKERS) {
+ const next = inspectionQueue[0];
+ if (
+ activeInspections &&
+ inspectingBytes + next.size > INSPECTION_BYTE_BUDGET
+ )
+ return;
+ inspectionQueue.shift();
+ next.start();
+ }
+}
+
+function runInspection(
+ file: Blob,
+ password: string,
+ signal: AbortSignal,
+): Promise<PdfAccess> {
+ return new Promise((resolve, reject) => {
+ let worker: Worker | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let started = false;
+ let finished = false;
+ const finish = () => {
+ if (finished) return false;
+ finished = true;
+ worker?.terminate();
+ clearTimeout(timer);
+ signal.removeEventListener("abort", abort);
+ if (started) {
+ activeInspections--;
+ inspectingBytes -= file.size;
+ } else {
+ const index = inspectionQueue.indexOf(queued);
+ if (index !== -1) inspectionQueue.splice(index, 1);
+ }
+ drainInspections();
+ return true;
+ };
+ const abort = () => {
+ if (finish())
+ reject(new DOMException("Operation cancelled", "AbortError"));
+ };
+ const queued = {
+ size: file.size,
+ start: () => {
+ if (signal.aborted) {
+ abort();
+ return;
+ }
+ started = true;
+ activeInspections++;
+ inspectingBytes += file.size;
+ timer = setTimeout(() => {
+ if (finish())
+ reject(
+ new DOMException(
+ "PDF permission inspection timed out. Try opening the file again.",
+ "TimeoutError",
+ ),
+ );
+ }, INSPECTION_TIMEOUT_MS);
+ try {
+ worker = new PdfAccessWorker();
+ worker.onmessage = ({ data }: MessageEvent<PdfAccessResponse>) => {
+ if (!finish()) return;
+ if ("access" in data) resolve(data.access);
+ else
+ reject(Object.assign(new Error(data.error), { code: data.code }));
+ };
+ worker.onerror = () => {
+ if (finish())
+ reject(new Error("Unable to inspect PDF security locally"));
+ };
+ startEagerWasmCompilation();
+ void pdfiumWasmModulePromise
+ .then((wasmModule) => {
+ if (finished) return;
+ const request: PdfAccessRequest = {
+ file,
+ password,
+ wasmUrl: pdfiumWasmUrl,
+ wasmModule,
+ };
+ try {
+ worker!.postMessage(request);
+ } catch (error) {
+ if (
+ !(error instanceof DOMException) ||
+ error.name !== "DataCloneError"
+ )
+ throw error;
+ // Some browsers cannot clone a compiled module into a worker.
+ worker!.postMessage({ ...request, wasmModule: null });
+ }
+ })
+ .catch((error: unknown) => {
+ if (finish()) reject(error);
+ });
+ } catch (error) {
+ if (finish()) reject(error);
+ }
+ },
+ };
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) abort();
+ else {
+ inspectionQueue.push(queued);
+ drainInspections();
+ }
+ });
+}
+
+/** Authenticate without publishing credentials; concurrent readers share one worker per file and password. */
+export function inspectLocalPdfAccess(
+ file: Blob,
+ password = "",
+ signal?: AbortSignal,
+): Promise<PdfAccess> {
+ const lifetime = pdfAccessLifetime(file);
+ const { signal: cancellation, dispose } = combineAbortSignals([
+ lifetime,
+ ...(signal ? [signal] : []),
+ ]);
+ if (cancellation.aborted) {
+ dispose();
+ return Promise.reject(
+ new DOMException("Operation cancelled", "AbortError"),
+ );
+ }
+ let pending = inspections.get(file);
+ if (!pending) {
+ pending = new Map();
+ inspections.set(file, pending);
+ }
+ let inspection = pending.get(password);
+ if (!inspection || inspection.controller.signal.aborted) {
+ const controller = new AbortController();
+ const combined = combineAbortSignals([controller.signal, lifetime]);
+ const job: Inspection = {
+ controller,
+ consumers: 0,
+ promise: runInspection(file, password, combined.signal).finally(() => {
+ combined.dispose();
+ if (pending.get(password) === job) pending.delete(password);
+ }),
+ };
+ pending.set(password, job);
+ inspection = job;
+ }
+ const job = inspection;
+ job.consumers++;
+ return new Promise((resolve, reject) => {
+ let finished = false;
+ const finish = () => {
+ if (finished) return false;
+ finished = true;
+ cancellation.removeEventListener("abort", abort);
+ dispose();
+ if (--job.consumers === 0) job.controller.abort();
+ return true;
+ };
+ const abort = () => {
+ if (finish())
+ reject(new DOMException("Operation cancelled", "AbortError"));
+ };
+ cancellation.addEventListener("abort", abort, { once: true });
+ job.promise.then(
+ (access) => {
+ if (finish()) resolve(access);
+ },
+ (error) => {
+ if (finish()) reject(error);
+ },
+ );
+ });
+}
+
+/** Reuse access for these exact bytes and credentials, or inspect locally before publishing it. */
+export async function ensureLocalPdfAccess(
+ file: Blob,
+ signal?: AbortSignal,
+ password?: string,
+): Promise<PdfAccess> {
+ if (signal?.aborted)
+ throw new DOMException("Operation cancelled", "AbortError");
+ const existing = getPdfAccess(file);
+ if (existing && (password === undefined || password === existing.password))
+ return existing;
+ const lifetime = pdfAccessLifetime(file);
+ const access = await inspectLocalPdfAccess(file, password ?? "", signal);
+ if (signal?.aborted || lifetime.aborted)
+ throw new DOMException("Session closed", "AbortError");
+ const current = getPdfAccess(file);
+ return current && current !== existing
+ ? current
+ : rememberPdfAccess(file, access);
+}
diff --git a/frontend/editor/src/core/services/pdfPasswordStore.ts b/frontend/editor/src/core/services/pdfPasswordStore.ts
deleted file mode 100644
index 2c0fc95604..0000000000
--- a/frontend/editor/src/core/services/pdfPasswordStore.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import type { FileId } from "@app/types/file";
-
-/** Session-only access to encrypted bytes. Never serialize this object or include it in tool parameters. */
-export interface PdfAccess {
- password: string;
- openingPassword?: string;
- openingAuthenticated?: boolean;
- hasOwnerPassword?: boolean;
- encrypted: boolean;
- requiresOpeningPassword?: boolean;
- signed: boolean;
- ownerAuthenticated: boolean;
- /** Server policy at inspection time; older servers default to enforcing restrictions. */
- honorOwnerPasswords?: boolean;
- permissions: number;
- /** Older servers omit these; native exports must reject unverifiable protection. */
- encryptionKeyLength?: number;
- encryptionRevision?: number;
- credentialFingerprint?: string;
- canModify: boolean;
- canAssemble: boolean;
- canExtract?: boolean;
- canPrint?: boolean;
- canPrintFaithful?: boolean;
- pageCount: number;
-}
-
-let accessByFile = new WeakMap<Blob, PdfAccess>();
-const filesById = new Map<string, Blob>();
-const listeners = new Set<() => void>();
-let revision = 0;
-
-function publish(): void {
- revision++;
- for (const listener of listeners) listener();
-}
-
-/** Look up credentials for these exact bytes; a replacement with the same filename must unlock separately. */
-export function getPdfAccess(
- file: Blob | string | null | undefined,
-): PdfAccess | undefined {
- if (!file) return undefined;
- const blob = typeof file === "string" ? filesById.get(file) : file;
- return blob ? accessByFile.get(blob) : undefined;
-}
-
-/** Retain access without changing the file; returns the identity used by preview cleanup. */
-export function rememberPdfAccess(file: Blob, access: PdfAccess): PdfAccess {
- const storedAccess = {
- ...access,
- openingPassword: access.encrypted
- ? access.openingAuthenticated || !access.ownerAuthenticated
- ? access.password
- : (access.openingPassword ?? accessByFile.get(file)?.openingPassword)
- : undefined,
- };
- accessByFile.set(file, storedAccess);
- if ("fileId" in file && typeof file.fileId === "string")
- filesById.set(file.fileId, file);
- publish();
- return storedAccess;
-}
-
-/** Bind a newly assigned FileContext identity to credentials already attached to its bytes. */
-export function bindPdfAccess(file: Blob, id: FileId): void {
- const previous = filesById.get(id);
- if (previous && previous !== file) {
- accessByFile.delete(previous);
- filesById.delete(id);
- }
- if (accessByFile.has(file)) filesById.set(id, file);
-}
-
-/** Closing a document drops its credential; reopening requires authentication again. */
-export function forgetPdfAccess(ids: readonly string[]): void {
- for (const id of ids) {
- const file = filesById.get(id);
- if (file) accessByFile.delete(file);
- filesById.delete(id);
- }
- publish();
-}
-
-/** Drop preview-owned access unless the same bytes have since entered FileContext. */
-export function forgetPreviewPdfAccess(file: Blob, access: PdfAccess): void {
- if (
- accessByFile.get(file) !== access ||
- [...filesById.values()].includes(file)
- )
- return;
- accessByFile.delete(file);
- publish();
-}
-
-/** Clear all credentials on logout or FileContext teardown. */
-export function clearPdfAccess(): void {
- accessByFile = new WeakMap();
- filesById.clear();
- publish();
-}
-
-/** Subscribe to unlock/lock changes without exposing credentials in React state. */
-export function subscribePdfAccess(listener: () => void): () => void {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-}
-
-/** Monotonic snapshot for useSyncExternalStore. */
-export function pdfAccessRevision(): number {
- return revision;
-}
diff --git a/frontend/editor/src/core/services/pdfPermissions.ts b/frontend/editor/src/core/services/pdfPermissions.ts
index fc086a4e7a..fc482b3df2 100644
--- a/frontend/editor/src/core/services/pdfPermissions.ts
+++ b/frontend/editor/src/core/services/pdfPermissions.ts
@@ -1,20 +1,48 @@
-import type { PdfAccess } from "@app/services/pdfPasswordStore";
-import { PdfPermissionFlag } from "@app/contexts/viewer/viewerBridges";
+import type { PdfAccess } from "@app/services/pdfAccessService";
+import { PdfPermissionFlag } from "@embedpdf/models";
-/** Applies owner policy and rejects low-quality-only printing, which this viewer cannot produce. */
-export function canPrintPdf(
- access:
- | (Pick<PdfAccess, "encrypted" | "ownerAuthenticated" | "permissions"> &
- Partial<Pick<PdfAccess, "honorOwnerPasswords" | "encryptionRevision">>)
- | undefined,
+type PermissionAccess = Pick<
+ PdfAccess,
+ "encrypted" | "ownerAuthenticated" | "permissions"
+> &
+ Partial<Pick<PdfAccess, "honorOwnerPasswords" | "encryptionRevision">>;
+
+/** Grants actions without changing the document's actual authentication role. */
+export function hasPdfPermissionOverride(
+ access: Partial<PdfAccess> | undefined,
+): boolean {
+ return (
+ access?.ownerAuthenticated === true || access?.honorOwnerPasswords === false
+ );
+}
+
+/** Applies owner policy and the encryption revision's interpretation of stored permission flags. */
+export function pdfAllows(
+ access: PermissionAccess | undefined,
+ flag: PdfPermissionFlag,
): boolean {
if (!access) return false;
+ if (
+ access.encryptionRevision === 2 &&
+ flag === PdfPermissionFlag.AssembleDocument
+ )
+ flag = PdfPermissionFlag.ModifyContents;
+ if (
+ access.encryptionRevision === 2 &&
+ flag === PdfPermissionFlag.PrintHighQuality
+ )
+ flag = PdfPermissionFlag.Print;
return (
!access.encrypted ||
- access.ownerAuthenticated ||
- access.honorOwnerPasswords === false ||
- ((access.permissions & PdfPermissionFlag.Print) !== 0 &&
- (access.encryptionRevision === 2 ||
- (access.permissions & PdfPermissionFlag.PrintHighQuality) !== 0))
+ hasPdfPermissionOverride(access) ||
+ (access.permissions & flag) !== 0
+ );
+}
+
+/** Applies owner policy and rejects low-quality-only printing, which this viewer cannot produce. */
+export function canPrintPdf(access: PermissionAccess | undefined): boolean {
+ return (
+ pdfAllows(access, PdfPermissionFlag.Print) &&
+ pdfAllows(access, PdfPermissionFlag.PrintHighQuality)
);
}
diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.test.ts b/frontend/editor/src/core/services/pdfSessionUnlock.test.ts
index 4cadfb5eae..508276f681 100644
--- a/frontend/editor/src/core/services/pdfSessionUnlock.test.ts
+++ b/frontend/editor/src/core/services/pdfSessionUnlock.test.ts
@@ -3,7 +3,6 @@ import apiClient from "@app/services/apiClient";
import axios from "axios";
import JSZip from "jszip";
import { zipFileService } from "@app/services/zipFileService";
-import { handlePasswordError } from "@app/utils/toolErrorHandler";
import { createStirlingFile } from "@app/types/fileContext";
import {
clearPdfAccess,
@@ -11,17 +10,17 @@ import {
getPdfAccess,
rememberPdfAccess,
type PdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
+import {
+ hasPdfPermissionOverride,
+ pdfAllows,
+} from "@app/services/pdfPermissions";
import {
prepareUnlockedFile,
protectUnlockedResults,
- unlockPdfForSession,
- verifyEditedPdfProtection,
assertPdfSessionEditable,
preflightPdfOperation,
changePdfSecurity,
- hasPdfPermissionOverride,
- pdfAllows,
} from "@app/services/pdfSessionUnlock";
import { PdfPermissionFlag } from "@embedpdf/models";
@@ -33,11 +32,7 @@ const access: PdfAccess = {
signed: false,
ownerAuthenticated: false,
permissions: -4,
- encryptionKeyLength: 256,
encryptionRevision: 6,
- credentialFingerprint: "source-credentials",
- canModify: true,
- canAssemble: true,
pageCount: 2,
};
const rotate = "/api/v1/general/rotate-pdf";
@@ -49,22 +44,121 @@ beforeEach(() => {
afterEach(clearPdfAccess);
describe("session PDF access", () => {
- it("sanitizes cancelled inspections without losing cancellation classification", async () => {
- const file = new File(["encrypted"], "restricted.pdf");
- const cancellation = axios.CancelToken.source();
- const original = Object.assign(new axios.CanceledError("cancelled"), {
- config: { data: "password-bearing form" },
+ it.each([false, true])(
+ "authenticates known encrypted input before changing protection, cancelled: %s",
+ async (cancelled) => {
+ const file = createStirlingFile(new File(["encrypted"], "locked.pdf"));
+ const requestOwner = vi.fn(async () => {
+ if (cancelled) return false;
+ rememberPdfAccess(file, {
+ ...access,
+ password: "source-owner",
+ ownerAuthenticated: true,
+ });
+ return true;
+ });
+ const endpoint = "/api/v1/security/add-password";
+ const permitted = await preflightPdfOperation(
+ [file],
+ endpoint,
+ false,
+ requestOwner,
+ undefined,
+ () => true,
+ );
+ expect(requestOwner).toHaveBeenCalledExactlyOnceWith(file);
+ expect(permitted).toBe(!cancelled);
+ expect(post).not.toHaveBeenCalled();
+ if (permitted) {
+ const form = new FormData();
+ form.set("keyLength", "256");
+ form.set("password", "new-reader");
+ post.mockResolvedValueOnce({ data: new Blob(["result"]) });
+ await changePdfSecurity(file, form, endpoint);
+ expect(form.get("sourcePassword")).toBe("source-owner");
+ expect(form.get("password")).toBe("new-reader");
+ }
+ },
+ );
+
+ it.each([
+ ["add-password", false],
+ ["add-password", true],
+ ["remove-password", false],
+ ])(
+ "lets %s validate unknown protection with preserveExisting=%s",
+ async (operation, preserveExisting) => {
+ const file = createStirlingFile(new File(["pdf"], "unknown.pdf"));
+ const endpoint = `/api/v1/security/${operation}`;
+ const requestOwner = vi.fn();
+ expect(
+ await preflightPdfOperation(
+ [file],
+ endpoint,
+ false,
+ requestOwner,
+ undefined,
+ () => operation === "remove-password",
+ ),
+ ).toBe(true);
+ expect(requestOwner).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+ const form = new FormData();
+ form.set("password", "reader");
+ if (!preserveExisting) form.set("keyLength", "256");
+ post.mockResolvedValueOnce({ data: new Blob(["result"]) });
+ await changePdfSecurity(file, form, endpoint);
+ expect(post).toHaveBeenCalledOnce();
+ expect(post.mock.calls[0][0]).toBe(endpoint);
+ expect(form.get("preserveExisting")).toBe(
+ preserveExisting ? "true" : null,
+ );
+ expect(form.get("sourcePassword")).toBe(
+ operation === "remove-password" ? "reader" : "",
+ );
+ },
+ );
+
+ it("submits both removal selections with incomplete local role information", async () => {
+ const file = createStirlingFile(new File(["pdf"], "protected.pdf"));
+ rememberPdfAccess(file, { ...access });
+ const requestOwner = vi.fn();
+ expect(
+ await preflightPdfOperation(
+ [file],
+ "/api/v1/security/remove-password",
+ false,
+ requestOwner,
+ ),
+ ).toBe(true);
+ const form = new FormData();
+ form.set("password", "reader");
+ form.set("ownerPassword", "owner");
+ post.mockResolvedValueOnce({ data: new Blob(["result"]) });
+ await changePdfSecurity(file, form, "/api/v1/security/remove-password");
+ expect(requestOwner).not.toHaveBeenCalled();
+ expect(post).toHaveBeenCalledOnce();
+ expect(form.get("password")).toBe("reader");
+ expect(form.get("ownerPassword")).toBe("owner");
+ });
+
+ it("retains policy and known opening credentials when local facts refresh", () => {
+ const file = new File(["source"], "protected.pdf");
+ rememberPdfAccess(file, {
+ ...access,
+ honorOwnerPasswords: false,
+ requiresOpeningPassword: true,
});
- post.mockRejectedValueOnce(original);
- const error = await unlockPdfForSession(
- file,
- "secret",
- cancellation.token,
- ).catch((failure: unknown) => failure);
- expect(axios.isCancel(error)).toBe(true);
- expect(error).not.toHaveProperty("config");
- expect(error).not.toHaveProperty("cause");
- expect(post.mock.calls[0][2]?.cancelToken).toBe(cancellation.token);
+ const refreshed = rememberPdfAccess(file, {
+ ...access,
+ requiresOpeningPassword: undefined,
+ });
+ expect(refreshed).toMatchObject({
+ honorOwnerPasswords: false,
+ requiresOpeningPassword: true,
+ openingPassword: access.password,
+ });
+ expect(post).not.toHaveBeenCalled();
});
it("preserves cancellation classification without retaining password-bearing requests", async () => {
@@ -100,7 +194,6 @@ describe("session PDF access", () => {
const reader = {
...access,
permissions: 0,
- canModify: false,
honorOwnerPasswords,
};
rememberPdfAccess(file, reader);
@@ -156,7 +249,7 @@ describe("session PDF access", () => {
expect(form.get("sourcePassword")).toBe(access.password);
expect(form.get("retainedOpeningPassword")).toBe(access.password);
expect(form.get("ownerPassword")).toBe("selected-owner");
- expect(post.mock.calls[0][0]).toBe("/api/v1/security/remove-pdf-passwords");
+ expect(post.mock.calls[0][0]).toBe("/api/v1/security/remove-password");
expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);
});
@@ -248,10 +341,9 @@ describe("session PDF access", () => {
const form = new FormData();
form.set("preventModify", "true");
await changePdfSecurity(file, form, "/api/v1/security/add-password");
- expect(post.mock.calls[0][0]).toBe(
- "/api/v1/security/change-pdf-permissions",
- );
+ expect(post.mock.calls[0][0]).toBe("/api/v1/security/add-password");
expect(form.get("sourcePassword")).toBe(access.password);
+ expect(form.get("preserveExisting")).toBe("true");
expect(form.has("ownerPassword")).toBe(false);
});
@@ -263,102 +355,17 @@ describe("session PDF access", () => {
await changePdfSecurity(file, form, "/api/v1/security/remove-password");
expect(form.get("sourcePassword")).toBe(access.password);
expect(form.has("password")).toBe(false);
- expect(post.mock.calls[0][0]).toBe("/api/v1/security/remove-pdf-passwords");
+ expect(post.mock.calls[0][0]).toBe("/api/v1/security/remove-password");
});
- it("authenticates without rewriting bytes or retaining credentials before adoption", async () => {
- const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));
- const { password, ...info } = access;
- post.mockResolvedValueOnce({ data: info });
- expect(await unlockPdfForSession(original, password)).toEqual(access);
- expect(post).toHaveBeenCalledOnce();
- expect(post.mock.calls[0][0]).toBe("/api/v1/security/inspect-pdf-security");
- const form = post.mock.calls[0][1] as FormData;
- expect(form.get("fileInput")).toBe(original);
- expect(form.get("password")).toBe(password);
- expect(getPdfAccess(original)).toBeUndefined();
- });
-
- it("does not cache a rejected password", async () => {
- const original = new File(["encrypted"], "locked.pdf");
- post.mockRejectedValueOnce(new Error("Incorrect password"));
- await expect(unlockPdfForSession(original, "wrong")).rejects.toThrow(
- "Incorrect password",
+ it("blocks signed protected edits", () => {
+ expect(() => assertPdfSessionEditable({ ...access, signed: true })).toThrow(
+ "digital signatures",
);
- expect(getPdfAccess(original)).toBeUndefined();
- });
-
- it("strips password-bearing request objects while preserving password errors", async () => {
- const form = new FormData();
- form.set("password", "secret");
- const config = { data: form };
- const original = Object.assign(new Error("Bad request"), {
- isAxiosError: true,
- config,
- request: { config },
- response: { status: 400, data: { type: "/errors/pdf-password" }, config },
- });
- post.mockRejectedValueOnce(original);
- const error = await unlockPdfForSession(
- new File(["pdf"], "test.pdf"),
- "secret",
- ).catch((error: unknown) => error);
- expect(error).not.toBe(original);
- expect(error).not.toHaveProperty("config");
- expect(error).not.toHaveProperty("request");
- expect(error).not.toHaveProperty("response.config");
- expect(error).not.toHaveProperty("cause");
- expect(
- await handlePasswordError(error, "Incorrect password", "Failed"),
- ).toBe("Incorrect password");
- });
-
- it.each([
- { encrypted: false },
- { permissions: -44 },
- { encryptionKeyLength: 128 },
- { encryptionRevision: 4 },
- { ownerAuthenticated: true },
- { encryptionKeyLength: undefined },
- { credentialFingerprint: "replaced-owner" },
- { credentialFingerprint: undefined },
- ])("rejects a native export with changed protection: %j", async (changed) => {
- const output = new File(["export"], "edited.pdf");
- post.mockResolvedValueOnce({ data: { ...access, ...changed } });
- await expect(verifyEditedPdfProtection(output, access)).rejects.toThrow(
- "Unable to preserve PDF protection",
- );
- expect(getPdfAccess(output)).toBeUndefined();
- });
-
- it("adopts a verified native export and blocks signed protected edits", async () => {
- const output = new File(["export"], "edited.pdf");
- post.mockResolvedValueOnce({ data: access });
- await verifyEditedPdfProtection(output, access);
- expect(getPdfAccess(output)).toEqual({
- ...access,
- openingPassword: access.password,
- });
- await expect(
- verifyEditedPdfProtection(output, { ...access, signed: true }),
- ).rejects.toThrow("digital signatures");
- expect(post).toHaveBeenCalledOnce();
expect(() =>
- assertPdfSessionEditable({ encrypted: false, signed: true }),
+ assertPdfSessionEditable({ ...access, encrypted: false, signed: true }),
).not.toThrow();
});
- it("rejects native exports when the source protection cannot be verified", async () => {
- post.mockResolvedValueOnce({ data: access });
- const output = new File(["export"], "edited.pdf");
- await expect(
- verifyEditedPdfProtection(output, {
- ...access,
- encryptionKeyLength: undefined,
- }),
- ).rejects.toThrow("Unable to preserve PDF protection");
- expect(getPdfAccess(output)).toBeUndefined();
- });
-
it("isolates same-name files and drops access when a document closes", () => {
const first = createStirlingFile(new File(["one"], "locked.pdf"));
const second = createStirlingFile(new File(["two"], "locked.pdf"));
@@ -378,7 +385,17 @@ describe("session PDF access", () => {
const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));
rememberPdfAccess(original, access);
post.mockResolvedValueOnce({ data: new Blob(["decrypted"]) });
- const working = await prepareUnlockedFile(original, rotate);
+ const navigation = new AbortController();
+ navigation.abort();
+ const cancellation = axios.CancelToken.source();
+ const working = await prepareUnlockedFile(
+ original,
+ rotate,
+ navigation.signal,
+ cancellation.token,
+ );
+ expect(post.mock.calls[0][2]?.signal?.aborted).toBe(false);
+ expect(post.mock.calls[0][2]?.cancelToken).toBe(cancellation.token);
expect(working).not.toBe(original);
expect(working.name).toBe(original.name);
expect(getPdfAccess(working)).toBeUndefined();
@@ -403,11 +420,7 @@ describe("session PDF access", () => {
it.each([
["/api/v1/security/auto-redact", access, "cannot yet preserve"],
[rotate, { ...access, signed: true }, "digital signatures"],
- [
- rotate,
- { ...access, canAssemble: false, permissions: -4 & ~1024 },
- "permissions password",
- ],
+ [rotate, { ...access, permissions: -4 & ~1024 }, "permissions password"],
])(
"rejects unsupported or restricted processing before decrypting",
async (endpoint, permission, message) => {
diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.ts b/frontend/editor/src/core/services/pdfSessionUnlock.ts
index 5af138193f..68cb0b22ed 100644
--- a/frontend/editor/src/core/services/pdfSessionUnlock.ts
+++ b/frontend/editor/src/core/services/pdfSessionUnlock.ts
@@ -1,55 +1,22 @@
-import apiClient from "@app/services/apiClient";
-import axios, { type CancelToken } from "axios";
-import i18n from "i18next";
import {
+ ensureLocalPdfAccess,
getPdfAccess,
+ pdfAccessLifetime,
rememberPdfAccess,
type PdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
+import apiClient from "@app/services/apiClient";
+import axios, { type CancelToken } from "axios";
+import i18n from "i18next";
+
import type { StirlingFile } from "@app/types/fileContext";
import { PdfPermissionFlag } from "@embedpdf/models";
import { zipFileService } from "@app/services/zipFileService";
-/** An override grants actions without changing the document's actual authentication role. */
-export function hasPdfPermissionOverride(
- access: Partial<PdfAccess> | undefined,
-): boolean {
- return (
- access?.ownerAuthenticated === true || access?.honorOwnerPasswords === false
- );
-}
-
-/** Applies the server policy and authenticated access to the document's stored restrictions. */
-export function pdfAllows(
- access: PdfAccess | undefined,
- flag: PdfPermissionFlag,
-): boolean {
- if (!access) return false;
- if (
- access.encryptionRevision === 2 &&
- flag === PdfPermissionFlag.AssembleDocument
- )
- flag = PdfPermissionFlag.ModifyContents;
- if (
- access.encryptionRevision === 2 &&
- flag === PdfPermissionFlag.PrintHighQuality
- )
- flag = PdfPermissionFlag.Print;
- return (
- !access.encrypted ||
- hasPdfPermissionOverride(access) ||
- (access.permissions & flag) !== 0
- );
-}
-
-/** Inspect original bytes even when an older library record missed owner-only encryption. */
-export async function ensurePdfAccess(file: File): Promise<PdfAccess> {
- const existing = getPdfAccess(file);
- if (existing) return existing;
- const access = await unlockPdfForSession(file, "");
- if (!getPdfAccess(file)) rememberPdfAccess(file, access);
- return getPdfAccess(file)!;
-}
+import {
+ hasPdfPermissionOverride,
+ pdfAllows,
+} from "@app/services/pdfPermissions";
const SUPPORTED_ENDPOINTS = new Set([
"/api/v1/security/add-password",
@@ -72,12 +39,14 @@ async function requestWorkingPdf(
form: FormData,
message: string,
cancelToken?: CancelToken,
+ signal?: AbortSignal,
): Promise<Blob> {
try {
const response = await apiClient.post<Blob>(endpoint, form, {
responseType: "blob",
suppressErrorToast: true,
cancelToken,
+ signal,
});
return response.data;
} catch (error) {
@@ -94,18 +63,30 @@ export function supportsSessionUnlock(endpoint: string | undefined): boolean {
return endpoint !== undefined && SUPPORTED_ENDPOINTS.has(endpoint);
}
-/** Checks the whole selection before processing or prompting for credentials. */
+/** Checks the whole selection before processing; encryption hints request authentication but never grant access. */
export async function preflightPdfOperation(
files: readonly StirlingFile[],
endpoint: string | undefined,
combinesFiles: boolean,
requestOwner: (file: StirlingFile) => Promise<boolean>,
+ signal?: AbortSignal,
+ isKnownEncrypted: (file: StirlingFile) => boolean = () => false,
): Promise<boolean> {
const protectedFiles: StirlingFile[] = [];
+ const changesProtection =
+ endpoint === "/api/v1/security/add-password" ||
+ endpoint === "/api/v1/security/remove-password";
for (const file of files) {
+ if (signal?.aborted) throw new axios.CanceledError("Operation cancelled");
if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)) continue;
- const access = await ensurePdfAccess(file);
- if (!access.encrypted) continue;
+ // Password endpoints validate the requested change themselves; unknown roles need no preflight upload.
+ const access = changesProtection
+ ? getPdfAccess(file)
+ : await ensureLocalPdfAccess(file, signal);
+ const encrypted =
+ access?.encrypted ??
+ (endpoint === "/api/v1/security/add-password" && isKnownEncrypted(file));
+ if (!encrypted) continue;
if (!supportsSessionUnlock(endpoint))
throw new Error(
i18n.t(
@@ -113,7 +94,7 @@ export async function preflightPdfOperation(
"This tool cannot yet preserve this PDF's protection.",
),
);
- if (access.signed)
+ if (access?.signed)
throw new Error(
i18n.t(
"encryptedPdfUnlock.signedReadOnly",
@@ -130,13 +111,15 @@ export async function preflightPdfOperation(
),
);
for (const file of protectedFiles) {
+ if (signal?.aborted) throw new axios.CanceledError("Operation cancelled");
if (endpoint === "/api/v1/security/remove-password") continue;
- const access = getPdfAccess(file)!;
+ const access = getPdfAccess(file);
const needsOwner = endpoint?.includes("password")
? !hasPdfPermissionOverride(access)
: !pdfAllows(access, operationPermission(endpoint));
if (needsOwner && !(await requestOwner(file))) return false;
}
+ if (signal?.aborted) throw new axios.CanceledError("Operation cancelled");
return true;
}
@@ -148,57 +131,8 @@ function operationPermission(endpoint: string | undefined): PdfPermissionFlag {
: PdfPermissionFlag.AssembleDocument;
}
-/** Authenticate without rewriting the uploaded document. The password stays outside file metadata. */
-export async function unlockPdfForSession(
- file: File,
- password: string,
- cancelToken?: CancelToken,
-): Promise<PdfAccess> {
- const form = new FormData();
- form.append("fileInput", file);
- form.append("password", password);
- try {
- const response = await apiClient.post<Omit<PdfAccess, "password">>(
- "/api/v1/security/inspect-pdf-security",
- form,
- {
- suppressErrorToast: true,
- ...(cancelToken ? { cancelToken } : {}),
- },
- );
- cancelToken?.throwIfRequested();
- if (
- typeof response.data?.encrypted !== "boolean" ||
- typeof response.data?.ownerAuthenticated !== "boolean" ||
- !Number.isInteger(response.data?.permissions)
- )
- throw new Error("Unable to verify PDF security");
- return { ...response.data, password };
- } catch (error) {
- if (axios.isCancel(error))
- throw new axios.CanceledError("Operation cancelled");
- const sanitized = new Error(
- error instanceof Error ? error.message : "Unable to unlock this PDF.",
- );
- if (axios.isAxiosError(error)) {
- // Keep password-error classification without retaining the request or its FormData.
- Object.assign(sanitized, {
- isAxiosError: true,
- response: error.response
- ? { status: error.response.status, data: error.response.data }
- : undefined,
- });
- }
- throw sanitized;
- }
-}
-
/** Signed protected PDFs remain view-only until their edits can preserve signatures. */
-export function assertPdfSessionEditable(
- access:
- | (Pick<PdfAccess, "encrypted" | "signed"> & Partial<PdfAccess>)
- | undefined,
-): void {
+export function assertPdfSessionEditable(access: PdfAccess | undefined): void {
if (access?.encrypted && access.signed)
throw new Error(
i18n.t(
@@ -206,11 +140,7 @@ export function assertPdfSessionEditable(
"This PDF has digital signatures. Session unlocking supports viewing it, but processing signed PDFs is not supported yet.",
),
);
- if (
- access?.encrypted &&
- !hasPdfPermissionOverride(access) &&
- access.canModify !== true
- )
+ if (access?.encrypted && !pdfAllows(access, PdfPermissionFlag.ModifyContents))
throw new Error(
i18n.t(
"encryptedPdfUnlock.restrictedOperation",
@@ -219,41 +149,15 @@ export function assertPdfSessionEditable(
);
}
-/** Native exports must retain source protection before storage or download can receive them. */
-export async function verifyEditedPdfProtection(
- output: File,
- sourceAccess: PdfAccess | undefined,
-): Promise<void> {
- if (!sourceAccess?.encrypted) return;
- assertPdfSessionEditable(sourceAccess);
- const access = await unlockPdfForSession(output, sourceAccess.password);
- if (
- !access.encrypted ||
- access.permissions !== sourceAccess.permissions ||
- access.ownerAuthenticated !== sourceAccess.ownerAuthenticated ||
- sourceAccess.encryptionKeyLength === undefined ||
- access.encryptionKeyLength !== sourceAccess.encryptionKeyLength ||
- sourceAccess.encryptionRevision === undefined ||
- access.encryptionRevision !== sourceAccess.encryptionRevision ||
- !sourceAccess.credentialFingerprint ||
- access.credentialFingerprint !== sourceAccess.credentialFingerprint
- )
- throw new Error(
- i18n.t(
- "encryptedPdfUnlock.restoreFailed",
- "Unable to preserve PDF protection. No unprotected result was saved.",
- ),
- );
- rememberPdfAccess(output, {
- ...access,
- openingPassword: sourceAccess.openingPassword,
- });
-}
-
-/** Decrypted bytes belong only to this operation. They must never enter FileContext or persistence. */
+/**
+ * Decrypted bytes belong only to this operation, never FileContext or persistence.
+ * Navigation cancels fresh permission reads; preparation stops on explicit cancellation or source closure.
+ */
export async function prepareUnlockedFile(
file: StirlingFile,
endpoint: string | undefined,
+ inspectionSignal?: AbortSignal,
+ cancelToken?: CancelToken,
): Promise<File> {
if (
endpoint === "/api/v1/security/remove-password" ||
@@ -262,7 +166,8 @@ export async function prepareUnlockedFile(
return file;
if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name))
return file;
- const access = await ensurePdfAccess(file);
+ const access =
+ getPdfAccess(file) ?? (await ensureLocalPdfAccess(file, inspectionSignal));
if (!access.encrypted) return file;
if (!supportsSessionUnlock(endpoint))
throw new Error(
@@ -297,6 +202,8 @@ export async function prepareUnlockedFile(
"encryptedPdfUnlock.prepareFailed",
"Unable to prepare this protected PDF for processing.",
),
+ cancelToken,
+ pdfAccessLifetime(file),
);
return new File([bytes], file.name, { type: "application/pdf" });
}
@@ -382,7 +289,7 @@ export async function protectUnlockedResults(
return protectedFiles;
}
-/** Interactive security changes use stricter contracts than the legacy public API. */
+/** Session credentials authenticate the source without selecting which passwords to remove. */
export async function changePdfSecurity(
file: File,
form: FormData,
@@ -390,27 +297,27 @@ export async function changePdfSecurity(
cancelToken?: CancelToken,
): Promise<Blob> {
const settingProtection = endpoint === "/api/v1/security/add-password";
+ const access = getPdfAccess(file);
if (settingProtection) {
- const access = await ensurePdfAccess(file);
- if (access.encrypted && !hasPdfPermissionOverride(access))
+ if (access?.encrypted && !hasPdfPermissionOverride(access))
throw new Error(
i18n.t(
"encryptedPdfUnlock.ownerRequired",
"Enter the permissions password to allow restricted actions.",
),
);
- form.set("sourcePassword", access.password);
+ form.set("sourcePassword", access?.password ?? "");
if (!form.has("keyLength")) {
+ form.set("preserveExisting", "true");
form.delete("password");
- if (access.openingPassword !== undefined)
+ if (access?.openingPassword !== undefined)
form.set("password", access.openingPassword);
}
} else {
- const access = await ensurePdfAccess(file);
if (
form.get("ownerPassword") &&
!form.get("password") &&
- access.requiresOpeningPassword &&
+ access?.requiresOpeningPassword &&
access.openingPassword === undefined
) {
throw new Error(
@@ -420,21 +327,21 @@ export async function changePdfSecurity(
),
);
}
- form.set("sourcePassword", access.password);
- if (access.openingPassword !== undefined)
+ form.set(
+ "sourcePassword",
+ access?.password || String(form.get("password") ?? ""),
+ );
+ if (access?.openingPassword !== undefined)
form.set("retainedOpeningPassword", access.openingPassword);
}
return requestWorkingPdf(
- settingProtection
- ? form.has("keyLength")
- ? "/api/v1/security/set-pdf-protection"
- : "/api/v1/security/change-pdf-permissions"
- : "/api/v1/security/remove-pdf-passwords",
+ endpoint,
form,
i18n.t(
"encryptedPdfUnlock.securityChangeFailed",
"Unable to change protection. Check the permissions password and the new security settings.",
),
cancelToken,
+ pdfAccessLifetime(file),
);
}
diff --git a/frontend/editor/src/core/services/thumbnailGenerationService.ts b/frontend/editor/src/core/services/thumbnailGenerationService.ts
index 5e96c31433..e8b5c5f181 100644
--- a/frontend/editor/src/core/services/thumbnailGenerationService.ts
+++ b/frontend/editor/src/core/services/thumbnailGenerationService.ts
@@ -3,7 +3,7 @@
*/
import { FileId } from "@app/types/file";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import {
openRawDocumentSafe,
closeRawDocument,
diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
index d5039ecfdf..0b870cfbd1 100644
--- a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
@@ -36,7 +36,7 @@ import {
rememberPdfAccess,
clearPdfAccess,
forgetPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
const workspace = {
files: [] as StirlingFile[],
@@ -213,8 +213,6 @@ describe("tool file selection", () => {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
try {
@@ -308,13 +306,15 @@ describe("tool file selection", () => {
expect(onPreviewRender).toHaveBeenCalledTimes(previewRenders);
const original = workspace.files[0];
- workspace.files = [
- createStirlingFile(
- new File(["updated pdf"], original.name, { type: original.type }),
- original.fileId,
- ),
- workspace.files[1],
- ];
+ act(() => {
+ workspace.files = [
+ createStirlingFile(
+ new File(["updated pdf"], original.name, { type: original.type }),
+ original.fileId,
+ ),
+ workspace.files[1],
+ ];
+ });
view.rerender(renderConvert());
await waitFor(() =>
expect(pdfWorker.destroyDocument).toHaveBeenCalledTimes(2),
diff --git a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
index 35e5b392d9..626a39eb5a 100644
--- a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
+++ b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
@@ -66,8 +66,16 @@ vi.mock("../../services/apiClient", () => ({
// Import the mocked apiClient
import apiClient from "@app/services/apiClient";
+import {
+ inspectLocalPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfAccessService";
import { notifyToolCompleted } from "@app/services/toolUsageTracker";
const mockedApiClient = vi.mocked(apiClient, { deep: true });
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ inspectLocalPdfAccess: vi.fn(),
+}));
// Usage-recommendation tracking would add its own posts to the apiClient spy.
vi.mock("../../services/toolUsageTracker", () => ({
@@ -157,8 +165,6 @@ describe("Convert Tool Integration Tests", () => {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
const files = [locked, pdf];
@@ -261,8 +267,6 @@ describe("Convert Tool Integration Tests", () => {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
const files = [image, locked, pdf, svg];
@@ -335,15 +339,14 @@ describe("Convert Tool Integration Tests", () => {
mockedApiClient.post.mockResolvedValueOnce({
data: new Blob(["protected output"], { type: "application/pdf" }),
});
- mockedApiClient.post.mockResolvedValueOnce({
- data: {
- encrypted: true,
- ownerAuthenticated: false,
- permissions: -4,
- requiresOpeningPassword: false,
- signed: false,
- keyLength: 256,
- },
+ vi.mocked(inspectLocalPdfAccess).mockResolvedValueOnce({
+ password: "",
+ encrypted: true,
+ ownerAuthenticated: false,
+ permissions: -4,
+ requiresOpeningPassword: false,
+ signed: false,
+ pageCount: 1,
});
await act(async () => {
await result.current.unlock.executeOperation({ password: "secret" }, [
@@ -351,9 +354,10 @@ describe("Convert Tool Integration Tests", () => {
locked,
]);
});
- expect(mockedApiClient.post).toHaveBeenCalledTimes(4);
+ expect(mockedApiClient.post).toHaveBeenCalledTimes(3);
+ expect(inspectLocalPdfAccess).toHaveBeenCalledOnce();
expect(mockedApiClient.post.mock.calls[2][0]).toBe(
- "/api/v1/security/remove-pdf-passwords",
+ "/api/v1/security/remove-password",
);
expect(
(mockedApiClient.post.mock.calls[2][1] as FormData).get("password"),
@@ -1386,4 +1390,3 @@ describe("Convert Tool Integration Tests", () => {
* - Test graceful degradation when endpoints are disabled
* - Test dynamic endpoint configuration updates
*/
-import { rememberPdfAccess } from "@app/services/pdfPasswordStore";
diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.ts
index fcf95f9626..150bbbc99b 100644
--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts
+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts
@@ -169,19 +169,6 @@ export async function mockAppApis(
page: Page,
opts: MockAppApiOptions = {},
): Promise<void> {
- await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- json: {
- encrypted: false,
- signed: false,
- ownerAuthenticated: false,
- permissions: -4,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- }),
- );
const {
enableLogin = false,
isAdmin = false,
diff --git a/frontend/editor/src/core/tests/helpers/pdf-encryption.ts b/frontend/editor/src/core/tests/helpers/pdf-encryption.ts
new file mode 100644
index 0000000000..f4673176a4
--- /dev/null
+++ b/frontend/editor/src/core/tests/helpers/pdf-encryption.ts
@@ -0,0 +1,45 @@
+import {
+ PDFArray,
+ PDFDict,
+ PDFDocument,
+ PDFHexString,
+ PDFName,
+ PDFString,
+} from "@cantoo/pdf-lib";
+
+/** Captures stored encryption and credential entries for comparison across saves; plain PDFs return an empty object. */
+export async function readEncryptionDictionary(bytes: Uint8Array) {
+ const pdf = await PDFDocument.load(bytes, {
+ ignoreEncryption: true,
+ updateMetadata: false,
+ });
+ const encryption = pdf.context.lookup(pdf.context.trailerInfo.Encrypt);
+ const entries: Record<string, string | undefined> = {};
+ if (!(encryption instanceof PDFDict)) return entries;
+ for (const key of [
+ "O",
+ "U",
+ "OE",
+ "UE",
+ "Perms",
+ "P",
+ "R",
+ "V",
+ "Length",
+ "EncryptMetadata",
+ ]) {
+ const value = encryption.get(PDFName.of(key));
+ entries[key] =
+ value instanceof PDFHexString || value instanceof PDFString
+ ? Buffer.from(value.asBytes()).toString("hex")
+ : value?.toString();
+ // Signed and unsigned PDF integers can encode the same 32 permission bits.
+ if (key === "P" && value)
+ entries[key] = String(Number(value.toString()) | 0);
+ }
+ const ids = pdf.context.lookup(pdf.context.trailerInfo.ID);
+ const id = ids instanceof PDFArray ? ids.get(0) : undefined;
+ if (id instanceof PDFHexString || id instanceof PDFString)
+ entries.ID = Buffer.from(id.asBytes()).toString("hex");
+ return entries;
+}
diff --git a/frontend/editor/src/core/tests/helpers/pdf-protection.ts b/frontend/editor/src/core/tests/helpers/pdf-protection.ts
new file mode 100644
index 0000000000..283cafad01
--- /dev/null
+++ b/frontend/editor/src/core/tests/helpers/pdf-protection.ts
@@ -0,0 +1,79 @@
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { init } from "@embedpdf/pdfium";
+import { readEncryptionDictionary } from "@app/tests/helpers/pdf-encryption";
+import type { Page } from "@playwright/test";
+import { liveApiHeaders } from "@app/tests/helpers/live-api";
+
+const require = createRequire(import.meta.url);
+const modulePromise = readFile(
+ require.resolve("@embedpdf/pdfium/pdfium.wasm"),
+).then(async (wasmBinary) => {
+ const module = await init({ wasmBinary });
+ module.PDFiumExt_Init();
+ return module;
+});
+
+/** Opens result bytes in PDFium; invalid credentials reject without making an API request. */
+export async function readPdfProtection(buffer: Buffer, password = "") {
+ const module = await modulePromise;
+ const pointer = module.pdfium.wasmExports.malloc(buffer.length);
+ const runtime = module.pdfium as typeof module.pdfium & {
+ HEAPU8: Uint8Array;
+ };
+ runtime.HEAPU8.set(buffer, pointer);
+ let document = 0;
+ try {
+ document = module.FPDF_LoadMemDocument(pointer, buffer.length, password);
+ if (!document)
+ throw new Error(`PDF open failed: ${module.FPDF_GetLastError()}`);
+ const encrypted = module.EPDF_IsEncrypted(document);
+ const ownerAuthenticated =
+ encrypted && module.EPDF_IsOwnerUnlocked(document);
+ const permissions = module.FPDF_GetDocUserPermissions(document);
+ const encryptionRevision = module.FPDF_GetSecurityHandlerRevision(document);
+ const empty = module.FPDF_LoadMemDocument(pointer, buffer.length, "");
+ const requiresOpeningPassword = !empty;
+ if (empty) module.FPDF_CloseDocument(empty);
+ const allows = (flag: number) =>
+ !encrypted || ownerAuthenticated || (permissions & flag) !== 0;
+ return {
+ encrypted,
+ ownerAuthenticated,
+ permissions,
+ encryptionRevision,
+ credentialEntries: await readEncryptionDictionary(buffer),
+ requiresOpeningPassword,
+ signed: module.FPDF_GetSignatureCount(document) > 0,
+ pageCount: module.FPDF_GetPageCount(document),
+ canModify: allows(8),
+ canPrint: allows(4),
+ canExtract: allows(16),
+ canAssemble: allows(encryptionRevision === 2 ? 8 : 1024),
+ canPrintFaithful: allows(encryptionRevision === 2 ? 4 : 2048),
+ };
+ } finally {
+ if (document) module.FPDF_CloseDocument(document);
+ module.pdfium.wasmExports.free(pointer);
+ }
+}
+
+/** Combines local PDF facts with the running instance's policy for live workflow assertions. */
+export async function inspectPdfProtection(
+ page: Page,
+ buffer: Buffer,
+ password = "",
+) {
+ const access = await readPdfProtection(buffer, password);
+ const config = await page.request.get("/api/v1/config/app-config", {
+ headers: await liveApiHeaders(page),
+ });
+ if (!config.ok())
+ throw new Error(`App config returned HTTP ${config.status()}`);
+ return {
+ ...access,
+ honorOwnerPasswords: (await config.json()).honorOwnerPasswords as
+ | boolean
+ | undefined,
+ };
+}
diff --git a/frontend/editor/src/core/tests/live/pdf-owner-policy.spec.ts b/frontend/editor/src/core/tests/live/pdf-owner-policy.spec.ts
index d632dc71f5..fd792f0add 100644
--- a/frontend/editor/src/core/tests/live/pdf-owner-policy.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-owner-policy.spec.ts
@@ -1,3 +1,4 @@
+import { inspectPdfProtection as inspect } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
import type { Page } from "@playwright/test";
@@ -18,49 +19,31 @@ test.beforeEach(async ({ page }) => {
});
async function protect(page: Page, password = "") {
- const response = await page.request.post(
- "/api/v1/security/set-pdf-protection",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: {
- name: "sample.pdf",
- mimeType: "application/pdf",
- buffer: await fs.readFile(path.join(fixtures, "sample.pdf")),
- },
- password,
- ownerPassword: owner,
- keyLength: 256,
- preventAssembly: true,
- preventExtractContent: true,
- preventExtractForAccessibility: true,
- preventFillInForm: true,
- preventModify: true,
- preventModifyAnnotations: true,
- preventPrinting: true,
- preventPrintingFaithful: true,
+ const response = await page.request.post("/api/v1/security/add-password", {
+ headers: await liveApiHeaders(page),
+ multipart: {
+ fileInput: {
+ name: "sample.pdf",
+ mimeType: "application/pdf",
+ buffer: await fs.readFile(path.join(fixtures, "sample.pdf")),
},
+ password,
+ ownerPassword: owner,
+ keyLength: 256,
+ preventAssembly: true,
+ preventExtractContent: true,
+ preventExtractForAccessibility: true,
+ preventFillInForm: true,
+ preventModify: true,
+ preventModifyAnnotations: true,
+ preventPrinting: true,
+ preventPrintingFaithful: true,
},
- );
+ });
expect(response.ok()).toBe(true);
return response.body();
}
-async function inspect(page: Page, buffer: Buffer, password = "") {
- const response = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },
- password,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.json();
-}
-
async function upload(page: Page, buffer: Buffer, route = "/editor") {
await page.goto(route);
await page.getByTestId("file-input").setInputFiles({
@@ -150,9 +133,7 @@ test("unprotected copy needs no owner password when enforcement is disabled", as
await page
.getByRole("button", { name: "Create an unprotected copy", exact: true })
.click();
- const response = page.waitForResponse(
- "**/api/v1/security/remove-pdf-protection",
- );
+ const response = page.waitForResponse("**/api/v1/security/remove-password");
await page
.getByRole("button", { name: "Create an unprotected copy", exact: true })
.click();
@@ -191,7 +172,7 @@ test("restricted rotation preserves the original protection without owner authen
encrypted: true,
ownerAuthenticated: false,
permissions: originalAccess.permissions,
- credentialFingerprint: originalAccess.credentialFingerprint,
+ credentialEntries: originalAccess.credentialEntries,
});
expect(await inspect(page, saved, owner)).toMatchObject({
ownerAuthenticated: true,
@@ -214,9 +195,7 @@ test("changing restrictions preserves the unknown owner password unless replacem
await page
.getByRole("checkbox", { name: "Prevent printing", exact: true })
.uncheck();
- const response = page.waitForResponse(
- "**/api/v1/security/change-pdf-permissions",
- );
+ const response = page.waitForResponse("**/api/v1/security/add-password");
await page
.getByRole("button", { name: /^Change Permissions(?: \(this file\))?$/ })
.click();
@@ -248,9 +227,7 @@ test("removing an opening password retains the blank owner field even when enfor
await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();
await expect(dialog).toBeHidden();
await page.getByLabel("Password to open", { exact: true }).fill(opening);
- const response = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
- );
+ const response = page.waitForResponse("**/api/v1/security/remove-password");
await page
.getByRole("button", {
name: /^Remove Password(?: \(this file\))?$/,
@@ -311,7 +288,7 @@ test("text editing bypass retains encryption and the original credentials in the
ownerAuthenticated: false,
canModify: false,
permissions: originalAccess.permissions,
- credentialFingerprint: originalAccess.credentialFingerprint,
+ credentialEntries: originalAccess.credentialEntries,
});
expect(await inspect(page, saved, "owner-test-password")).toMatchObject({
ownerAuthenticated: true,
diff --git a/frontend/editor/src/core/tests/live/pdf-password-removal.spec.ts b/frontend/editor/src/core/tests/live/pdf-password-removal.spec.ts
index 1d9fb728eb..688c87670c 100644
--- a/frontend/editor/src/core/tests/live/pdf-password-removal.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-password-removal.spec.ts
@@ -1,9 +1,21 @@
+import { inspectPdfProtection } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
import type { Page, Response } from "@playwright/test";
import path from "node:path";
import fs from "node:fs/promises";
+async function inspect(page: Page, buffer: Buffer, password: string) {
+ const access = await inspectPdfProtection(page, buffer, password);
+ const hasOwnerPassword =
+ access.encrypted &&
+ (await inspectPdfProtection(page, buffer, owner).then(
+ (result) => result.ownerAuthenticated,
+ () => false,
+ ));
+ return { ...access, hasOwnerPassword };
+}
+
const reader = "removal-reader";
const owner = "removal-owner";
const fixture = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");
@@ -17,36 +29,23 @@ async function protectedPdf(
opening: boolean,
permissions: boolean,
) {
- const response = await page.request.post(
- "/api/v1/security/set-pdf-protection",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: {
- name: "sample.pdf",
- mimeType: "application/pdf",
- buffer: await fs.readFile(fixture),
- },
- password: opening ? reader : "",
- ownerPassword: permissions ? owner : "",
- keyLength: 256,
- preventPrinting: permissions,
- preventModify: permissions,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.body();
-}
-
-async function inspect(page: Page, buffer: Buffer, password: string) {
- return page.request.post("/api/v1/security/inspect-pdf-security", {
+ const response = await page.request.post("/api/v1/security/add-password", {
headers: await liveApiHeaders(page),
multipart: {
- fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },
- password,
+ fileInput: {
+ name: "sample.pdf",
+ mimeType: "application/pdf",
+ buffer: await fs.readFile(fixture),
+ },
+ password: opening ? reader : "",
+ ownerPassword: permissions ? owner : "",
+ keyLength: 256,
+ preventPrinting: permissions,
+ preventModify: permissions,
},
});
+ expect(response.ok()).toBe(true);
+ return response.body();
}
async function upload(page: Page, buffer: Buffer, opening = true) {
@@ -62,6 +61,8 @@ async function upload(page: Page, buffer: Buffer, opening = true) {
await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();
await expect(dialog).toBeHidden();
}
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();
+ await expect(page.getByRole("dialog", { name: /^Open PDF/ })).toBeHidden();
await expect(
page.getByText("Leave a field blank to keep that password."),
).toBeVisible();
@@ -107,7 +108,7 @@ for (const permissions of [false, true]) {
await expect(dialog.getByRole("alert")).toContainText("Incorrect password");
await dialog.getByLabel("Password to open", { exact: true }).fill(reader);
const removalResponse = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
+ "**/api/v1/security/remove-password",
);
await remove.click();
if (permissions) {
@@ -145,21 +146,17 @@ for (const permissions of [false, true]) {
page.getByText("load-time_password_removed.pdf", { exact: true }).first(),
).toBeVisible();
const result = await inspect(page, saved, "");
- expect(result.ok()).toBe(true);
- expect(await result.json()).toMatchObject({
+ expect(result).toMatchObject({
encrypted: permissions,
requiresOpeningPassword: false,
hasOwnerPassword: permissions,
canPrint: !permissions,
});
if (permissions) {
- expect(
- (await (await inspect(page, saved, owner)).json()).ownerAuthenticated,
- ).toBe(true);
+ expect((await inspect(page, saved, owner)).ownerAuthenticated).toBe(true);
}
expect(
- (await (await inspect(page, original, reader)).json())
- .requiresOpeningPassword,
+ (await inspect(page, original, reader)).requiresOpeningPassword,
).toBe(true);
});
}
@@ -170,7 +167,7 @@ test("closing load-time owner verification leaves the protected source unchanged
const original = await protectedPdf(page, true, true);
let removals = 0;
page.on("request", (request) => {
- if (request.url().endsWith("/remove-pdf-passwords")) removals++;
+ if (request.url().endsWith("/remove-password")) removals++;
});
await page.goto("/editor");
await page.getByTestId("file-input").setInputFiles({
@@ -190,10 +187,9 @@ test("closing load-time owner verification leaves the protected source unchanged
await expect(dialog).toBeHidden();
expect(removals).toBe(0);
await expect(page.locator('[data-page-index="0"]')).toHaveCount(0);
- expect(
- (await (await inspect(page, original, reader)).json())
- .requiresOpeningPassword,
- ).toBe(true);
+ expect((await inspect(page, original, reader)).requiresOpeningPassword).toBe(
+ true,
+ );
});
for (const remove of ["opening", "owner", "both"] as const) {
@@ -202,8 +198,7 @@ for (const remove of ["opening", "owner", "both"] as const) {
}) => {
const original = await protectedPdf(page, true, true);
const honor =
- (await (await inspect(page, original, reader)).json())
- .honorOwnerPasswords !== false;
+ (await inspect(page, original, reader)).honorOwnerPasswords !== false;
await upload(page, original);
const submit = page.getByRole("button", {
name: /^Remove Password(?: \(this file\))?$/,
@@ -222,7 +217,7 @@ for (const remove of ["opening", "owner", "both"] as const) {
.getByLabel("Permissions password", { exact: true })
.fill(owner);
const responsePromise = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
+ "**/api/v1/security/remove-password",
);
await submit.click();
if (remove === "opening") {
@@ -245,33 +240,21 @@ for (const remove of ["opening", "owner", "both"] as const) {
const saved = await response.body();
const password = remove === "owner" ? reader : "";
const result = await inspect(page, saved, password);
- expect(result.ok()).toBe(true);
- expect(await result.json()).toMatchObject({
+ expect(result).toMatchObject({
encrypted: remove !== "both",
requiresOpeningPassword: remove === "owner",
hasOwnerPassword: remove === "opening",
canPrint: remove !== "opening",
});
if (remove === "opening") {
- expect(
- (await (await inspect(page, saved, owner)).json()).ownerAuthenticated,
- ).toBe(true);
- await expect(
- page.getByText("Opening password removed. Restrictions retained."),
- ).toBeVisible();
+ expect((await inspect(page, saved, owner)).ownerAuthenticated).toBe(true);
} else if (remove === "owner") {
- expect((await inspect(page, saved, "")).ok()).toBe(false);
- expect((await inspect(page, saved, owner)).ok()).toBe(false);
- await expect(
- page.getByText(
- "Permissions password and restrictions removed. Opening password kept.",
- ),
- ).toBeVisible();
- } else {
- await expect(
- page.getByText("Both passwords and restrictions removed."),
- ).toBeVisible();
+ await expect(inspect(page, saved, "")).rejects.toThrow("PDF open failed");
+ await expect(inspect(page, saved, owner)).rejects.toThrow(
+ "PDF open failed",
+ );
}
+ await expect(page.getByTestId("download-result-button")).toBeEnabled();
await expect(page.getByRole("dialog")).toHaveCount(0);
await expect(
page.getByRole("button", { name: "Print PDF", exact: true }),
@@ -285,14 +268,13 @@ for (const remove of ["opening", "owner", "both"] as const) {
).toHaveAttribute("src", /^blob:/);
}
expect(
- (await (await inspect(page, original, reader)).json())
- .requiresOpeningPassword,
+ (await inspect(page, original, reader)).requiresOpeningPassword,
).toBe(true);
});
}
for (const only of ["opening", "owner"] as const) {
- test(`only enables the ${only} password when that is the only password set`, async ({
+ test(`removes the ${only} password while leaving unknown roles selectable`, async ({
page,
}) => {
const original = await protectedPdf(
@@ -306,23 +288,23 @@ for (const only of ["opening", "owner"] as const) {
).toBeEnabled({ enabled: only === "opening" });
await expect(
page.getByLabel("Permissions password", { exact: true }),
- ).toBeEnabled({ enabled: only === "owner" });
+ ).toBeEnabled();
const label =
only === "opening" ? "Password to open" : "Permissions password";
await page
.getByLabel(label, { exact: true })
.fill(only === "opening" ? reader : owner);
const responsePromise = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
+ "**/api/v1/security/remove-password",
);
await page
.getByRole("button", { name: /^Remove Password(?: \(this file\))?$/ })
.click();
const response = await responsePromise;
expect(response.ok()).toBe(true);
- expect(
- (await (await inspect(page, await response.body(), "")).json()).encrypted,
- ).toBe(false);
+ expect((await inspect(page, await response.body(), "")).encrypted).toBe(
+ false,
+ );
await expect(
page.getByRole("button", { name: "Print PDF", exact: true }),
).toBeEnabled();
@@ -350,7 +332,7 @@ test("wrong role credentials cannot remove protection and cancelled verification
).toHaveValue("");
await page.getByLabel("Permissions password", { exact: true }).fill(reader);
const responsePromise = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
+ "**/api/v1/security/remove-password",
);
await page
.getByRole("button", { name: /^Remove Password(?: \(this file\))?$/ })
@@ -360,7 +342,7 @@ test("wrong role credentials cannot remove protection and cancelled verification
});
for (const remove of ["opening", "owner", "both"] as const) {
- test(`mixed selections remove ${remove} passwords only where set`, async ({
+ test(`mixed selections validate unknown ${remove} roles during processing`, async ({
page,
}) => {
const inputs = [
@@ -391,9 +373,26 @@ for (const remove of ["opening", "owner", "both"] as const) {
.locator("label")
.filter({ hasText: /^Active Files$/ })
.click();
+ // Opening these fixtures makes absent protection known without inspecting unopened files.
+ for (const name of ["plain.pdf", "owner-only.pdf"]) {
+ await page
+ .getByTestId("file-thumbnail")
+ .filter({ hasText: name })
+ .dblclick();
+ await expect(
+ page.getByLabel("Password to open", { exact: true }),
+ ).toBeDisabled();
+ await expect(
+ page.getByLabel("Permissions password", { exact: true }),
+ ).toBeEnabled({ enabled: name === "owner-only.pdf" });
+ await page
+ .locator("label")
+ .filter({ hasText: /^Active Files$/ })
+ .click();
+ }
await expect(
page.getByText("Set on 2 of 4 PDFs", { exact: true }),
- ).toHaveCount(2);
+ ).toHaveCount(1);
const openingInput = page.getByLabel("Password to open", { exact: true });
const ownerInput = page.getByLabel("Permissions password", { exact: true });
await expect(openingInput).toBeEnabled();
@@ -402,8 +401,7 @@ for (const remove of ["opening", "owner", "both"] as const) {
if (remove !== "opening") await ownerInput.fill(owner);
const responses: Response[] = [];
page.on("response", (response) => {
- if (response.url().endsWith("/remove-pdf-passwords"))
- responses.push(response);
+ if (response.url().endsWith("/remove-password")) responses.push(response);
});
await page.getByRole("button", { name: /^Remove Password/ }).click();
if (remove === "opening") {
@@ -421,23 +419,21 @@ for (const remove of ["opening", "owner", "both"] as const) {
.getByRole("button", { name: "Continue", exact: true })
.click();
}
- await expect(
- page.getByText(
- "Entered passwords removed where set. Blank fields kept unchanged.",
- ),
- ).toBeVisible();
+ await expect(page.getByTestId("download-result-button")).toBeEnabled();
+ // Owner-only removal rejects ambiguous opening credentials before sending a request.
expect(responses).toHaveLength(remove === "both" ? 3 : 2);
+ expect(responses.filter((response) => !response.ok())).toHaveLength(
+ remove === "both" ? 1 : 0,
+ );
const protection = [];
for (const response of responses) {
- expect(response.ok()).toBe(true);
+ if (!response.ok()) continue;
const buffer = await response.body();
- const inspection = await inspect(
+ const result = await inspect(
page,
buffer,
remove === "owner" ? reader : "",
);
- expect(inspection.ok()).toBe(true);
- const result = await inspection.json();
protection.push({
encrypted: result.encrypted,
requiresOpeningPassword: result.requiresOpeningPassword,
@@ -445,10 +441,9 @@ for (const remove of ["opening", "owner", "both"] as const) {
canPrint: result.canPrint,
});
if (result.hasOwnerPassword)
- expect(
- (await (await inspect(page, buffer, owner)).json())
- .ownerAuthenticated,
- ).toBe(true);
+ expect((await inspect(page, buffer, owner)).ownerAuthenticated).toBe(
+ true,
+ );
}
const unprotected = {
encrypted: false,
@@ -457,9 +452,7 @@ for (const remove of ["opening", "owner", "both"] as const) {
canPrint: true,
};
expect(protection.filter((result) => !result.encrypted)).toEqual(
- remove === "both"
- ? [unprotected, unprotected, unprotected]
- : [unprotected],
+ remove === "both" ? [unprotected, unprotected] : [unprotected],
);
if (remove !== "both")
expect(protection.filter((result) => result.encrypted)).toEqual([
@@ -476,15 +469,20 @@ for (const remove of ["opening", "owner", "both"] as const) {
.filter({ hasText: "plain.pdf" })
.getByText("v1", { exact: true }),
).toBeVisible();
- if (remove !== "both")
+ await expect(
+ page
+ .getByTestId("file-thumbnail")
+ .filter({
+ hasText: remove === "opening" ? "owner-only.pdf" : "opening-only.pdf",
+ })
+ .getByText("v1", { exact: true }),
+ ).toBeVisible();
+ if (remove !== "opening")
await expect(
page
.getByTestId("file-thumbnail")
- .filter({
- hasText:
- remove === "opening" ? "owner-only.pdf" : "opening-only.pdf",
- })
- .getByText("v1", { exact: true }),
+ .filter({ hasText: "opening-only.pdf" })
+ .getByText("Error", { exact: true }),
).toBeVisible();
});
}
diff --git a/frontend/editor/src/core/tests/live/pdf-permissions-matrix.spec.ts b/frontend/editor/src/core/tests/live/pdf-permissions-matrix.spec.ts
index d53004eaaa..882d231869 100644
--- a/frontend/editor/src/core/tests/live/pdf-permissions-matrix.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-permissions-matrix.spec.ts
@@ -1,3 +1,4 @@
+import { inspectPdfProtection as inspect } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
import { skipOnboarding } from "@app/tests/helpers/login";
@@ -43,21 +44,6 @@ test.beforeEach(async ({ page }) => {
await loadLiveAppConfig(page);
});
-async function inspect(page: Page, buffer: Buffer, password = "") {
- const response = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },
- password,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.json();
-}
-
async function openFresh(
source: Page,
buffer: Buffer,
@@ -149,7 +135,7 @@ for (const restriction of restrictions) {
.getByRole("textbox", { name: "New permissions password", exact: true })
.fill(owner);
const protectedResponse = page.waitForResponse(
- "**/api/v1/security/set-pdf-protection",
+ "**/api/v1/security/add-password",
);
await page
.getByRole("button", { name: "Save protection", exact: true })
@@ -233,7 +219,7 @@ for (const restriction of restrictions) {
.uncheck();
const savedOwner = owner;
const changedResponse = page.waitForResponse(
- "**/api/v1/security/change-pdf-permissions",
+ "**/api/v1/security/add-password",
);
await page
.getByRole("button", {
diff --git a/frontend/editor/src/core/tests/live/pdf-protection-sessions.spec.ts b/frontend/editor/src/core/tests/live/pdf-protection-sessions.spec.ts
index 2e019d2744..140129b8ab 100644
--- a/frontend/editor/src/core/tests/live/pdf-protection-sessions.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-protection-sessions.spec.ts
@@ -1,3 +1,4 @@
+import { inspectPdfProtection as inspect } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
import type { Page } from "@playwright/test";
@@ -13,45 +14,27 @@ test.beforeEach(async ({ page }) => {
});
async function protect(page: Page) {
- const response = await page.request.post(
- "/api/v1/security/set-pdf-protection",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: {
- name: "sample.pdf",
- mimeType: "application/pdf",
- buffer: await fs.readFile(path.join(fixtures, "sample.pdf")),
- },
- password: reader,
- ownerPassword: owner,
- keyLength: 256,
- preventPrinting: true,
- preventAssembly: true,
- preventModify: true,
- preventExtractContent: true,
+ const response = await page.request.post("/api/v1/security/add-password", {
+ headers: await liveApiHeaders(page),
+ multipart: {
+ fileInput: {
+ name: "sample.pdf",
+ mimeType: "application/pdf",
+ buffer: await fs.readFile(path.join(fixtures, "sample.pdf")),
},
+ password: reader,
+ ownerPassword: owner,
+ keyLength: 256,
+ preventPrinting: true,
+ preventAssembly: true,
+ preventModify: true,
+ preventExtractContent: true,
},
- );
+ });
expect(response.ok()).toBe(true);
return response.body();
}
-async function inspect(page: Page, buffer: Buffer, password: string) {
- const response = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },
- password,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.json();
-}
-
async function open(page: Page, password: string) {
const dialog = page.getByRole("dialog", { name: /^Open PDF/ });
await dialog.getByLabel("Password to open", { exact: true }).fill(password);
@@ -143,7 +126,7 @@ test("restricted processing preserves both passwords and prompts only when enfor
ownerAuthenticated: false,
requiresOpeningPassword: true,
permissions: access.permissions,
- credentialFingerprint: access.credentialFingerprint,
+ credentialEntries: access.credentialEntries,
});
expect(await inspect(page, saved, owner)).toMatchObject({
ownerAuthenticated: true,
@@ -162,7 +145,7 @@ test("removing all protection can be cancelled, then opening-only protection can
const access = await inspect(page, buffer, reader);
let removals = 0;
page.on("request", (request) => {
- if (request.url().endsWith("/remove-pdf-protection")) removals++;
+ if (request.url().endsWith("/remove-password")) removals++;
});
await page.goto("/editor");
await page.getByTestId("file-input").setInputFiles({
@@ -191,9 +174,7 @@ test("removing all protection can be cancelled, then opening-only protection can
await page
.getByRole("button", { name: "Create an unprotected copy", exact: true })
.click();
- const response = page.waitForResponse(
- "**/api/v1/security/remove-pdf-protection",
- );
+ const response = page.waitForResponse("**/api/v1/security/remove-password");
await page
.getByRole("button", { name: "Create an unprotected copy", exact: true })
.click();
@@ -224,9 +205,7 @@ test("removing all protection can be cancelled, then opening-only protection can
buffer: unprotected,
});
await page.getByLabel("Password to open", { exact: true }).fill(reader);
- const protection = page.waitForResponse(
- "**/api/v1/security/set-pdf-protection",
- );
+ const protection = page.waitForResponse("**/api/v1/security/add-password");
await page
.getByRole("button", { name: /^Save protection(?: \(this file\))?$/ })
.click();
diff --git a/frontend/editor/src/core/tests/live/pdf-protection-workflow.spec.ts b/frontend/editor/src/core/tests/live/pdf-protection-workflow.spec.ts
index 8240cf3036..cb386c9560 100644
--- a/frontend/editor/src/core/tests/live/pdf-protection-workflow.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-protection-workflow.spec.ts
@@ -1,6 +1,6 @@
+import { inspectPdfProtection as inspect } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
-import type { Page } from "@playwright/test";
import path from "node:path";
import fs from "node:fs";
@@ -12,21 +12,6 @@ test.beforeEach(async ({ page }) => {
await loadLiveAppConfig(page);
});
-async function inspect(page: Page, buffer: Buffer, password: string) {
- const response = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },
- password,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.json();
-}
-
test("saving protection opens the result as a reader and changing permissions preserves its opening password", async ({
page,
}) => {
@@ -54,9 +39,7 @@ test("saving protection opens the result as a reader and changing permissions pr
page.getByRole("button", { name: "Save protection", exact: true }),
).toBeDisabled();
await ownerInput.fill(owner);
- const protection = page.waitForResponse(
- "**/api/v1/security/set-pdf-protection",
- );
+ const protection = page.waitForResponse("**/api/v1/security/add-password");
await page
.getByRole("button", { name: "Save protection", exact: true })
.click();
@@ -67,8 +50,6 @@ test("saving protection opens the result as a reader and changing permissions pr
expect(readerAccess).toMatchObject({
encrypted: true,
requiresOpeningPassword: true,
- openingAuthenticated: true,
- hasOwnerPassword: true,
ownerAuthenticated: false,
canPrint: false,
});
@@ -103,9 +84,7 @@ test("saving protection opens the result as a reader and changing permissions pr
await page
.getByRole("checkbox", { name: "Prevent printing", exact: true })
.uncheck();
- const changed = page.waitForResponse(
- "**/api/v1/security/change-pdf-permissions",
- );
+ const changed = page.waitForResponse("**/api/v1/security/add-password");
await page
.getByRole("button", { name: "Change Permissions", exact: true })
.click();
@@ -184,9 +163,7 @@ for (const action of [
const honorOwnerPasswords =
(await inspect(page, buffer, "")).honorOwnerPasswords !== false;
const endpoint =
- action === "Change Permissions"
- ? "change-pdf-permissions"
- : "remove-pdf-protection";
+ action === "Change Permissions" ? "add-password" : "remove-password";
const denied = await page.request.post(`/api/v1/security/${endpoint}`, {
headers: await liveApiHeaders(page),
multipart: {
@@ -197,6 +174,8 @@ for (const action of [
},
password: "",
sourcePassword: "",
+ preserveExisting: action === "Change Permissions",
+ removeAll: action !== "Change Permissions",
},
});
expect(denied.status()).toBe(honorOwnerPasswords ? 403 : 200);
@@ -341,7 +320,7 @@ test("a PDF with only an opening password opens and prints after removing its op
.setInputFiles(path.join(fixtures, "sample.pdf"));
await page.getByLabel("Password to open", { exact: true }).fill(reader);
const protectedResponse = page.waitForResponse(
- "**/api/v1/security/set-pdf-protection",
+ "**/api/v1/security/add-password",
);
await page
.getByRole("button", { name: "Save protection", exact: true })
@@ -363,13 +342,13 @@ test("a PDF with only an opening password opens and prints after removing its op
.getByRole("button", { name: "Remove Password", exact: true })
.click();
await expect(page.getByRole("dialog")).toHaveCount(0);
- const removedResponse = page.waitForResponse(
- "**/api/v1/security/remove-pdf-passwords",
- );
await expect(
page.getByLabel("Permissions password", { exact: true }),
- ).toBeDisabled();
+ ).toBeEnabled();
await page.getByLabel("Password to open", { exact: true }).fill(reader);
+ const removedResponse = page.waitForResponse(
+ "**/api/v1/security/remove-password",
+ );
await page
.getByRole("button", { name: "Remove Password", exact: true })
.click();
@@ -413,7 +392,7 @@ test("replacing the permissions password follows the owner policy and invalidate
.getByRole("textbox", { name: "New permissions password", exact: true })
.fill(owner);
const changedResponse = page.waitForResponse(
- "**/api/v1/security/change-pdf-permissions",
+ "**/api/v1/security/add-password",
);
await page
.getByRole("button", { name: "Change Permissions", exact: true })
@@ -447,17 +426,9 @@ test("replacing the permissions password follows the owner policy and invalidate
ownerAuthenticated: false,
canPrint: false,
});
- const oldCredential = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: { name: "updated.pdf", mimeType: "application/pdf", buffer },
- password: "owner-test-password",
- },
- },
+ await expect(inspect(page, buffer, "owner-test-password")).rejects.toThrow(
+ "PDF open failed",
);
- expect(oldCredential.ok()).toBe(false);
});
for (const tool of ["annotate", "form-fill", "redact"]) {
diff --git a/frontend/editor/src/core/tests/live/pdf-text-editor-permissions.spec.ts b/frontend/editor/src/core/tests/live/pdf-text-editor-permissions.spec.ts
index db18f2139f..1527f96355 100644
--- a/frontend/editor/src/core/tests/live/pdf-text-editor-permissions.spec.ts
+++ b/frontend/editor/src/core/tests/live/pdf-text-editor-permissions.spec.ts
@@ -1,5 +1,6 @@
+import { inspectPdfProtection as inspect } from "@app/tests/helpers/pdf-protection";
import { test, expect } from "@app/tests/helpers/test-base";
-import { liveApiHeaders, loadLiveAppConfig } from "@app/tests/helpers/live-api";
+import { loadLiveAppConfig } from "@app/tests/helpers/live-api";
import { skipOnboarding } from "@app/tests/helpers/login";
import type { Page } from "@playwright/test";
import path from "node:path";
@@ -24,25 +25,6 @@ async function openTextEditor(page: Page) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible();
}
-async function inspect(page: Page, buffer: Buffer, password: string) {
- const response = await page.request.post(
- "/api/v1/security/inspect-pdf-security",
- {
- headers: await liveApiHeaders(page),
- multipart: {
- fileInput: {
- name: "restricted.pdf",
- mimeType: "application/pdf",
- buffer,
- },
- password,
- },
- },
- );
- expect(response.ok()).toBe(true);
- return response.json();
-}
-
for (const entry of ["workbench", "editor upload"] as const) {
test(`a fresh reader follows the owner policy through ${entry}`, async ({
page,
@@ -208,9 +190,8 @@ test("permitted text edits preserve protection and a fresh reader follows the se
ownerAuthenticated: false,
canModify: false,
permissions: sourceAccess.permissions,
- encryptionKeyLength: sourceAccess.encryptionKeyLength,
encryptionRevision: sourceAccess.encryptionRevision,
- credentialFingerprint: sourceAccess.credentialFingerprint,
+ credentialEntries: sourceAccess.credentialEntries,
});
expect(await inspect(page, saved, owner)).toMatchObject({
ownerAuthenticated: true,
diff --git a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
index 6814e892d7..a3ec4f6ccb 100644
--- a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
@@ -79,13 +79,13 @@ test("a 10-file upload wave classifies every file into its group", async ({
const header = (name: string, count: number) =>
page.getByRole("button", { name: `${name} ${count}`, exact: true });
- // Unclassified files stay in Other until processing finishes; only generic notes remain.
- await expect(header("Other", 1)).toBeVisible({ timeout: 150_000 });
-
- // The Spanish lease is also classified as Legal.
- await expect(header("Financial", 3)).toBeVisible();
- await expect(header("HR", 3)).toBeVisible();
- await expect(header("Legal", 3)).toBeVisible();
+ // Progressive admission can briefly show Other 1 before the full batch arrives.
+ await expect(async () => {
+ await expect(header("Financial", 3)).toBeVisible();
+ await expect(header("HR", 3)).toBeVisible();
+ await expect(header("Legal", 3)).toBeVisible();
+ await expect(header("Other", 1)).toBeVisible();
+ }).toPass({ timeout: 150_000 });
// A filename can render in Recent, its group, or the viewer; any hit proves presence.
await expect(page.getByText("generic_notes.pdf").first()).toBeVisible();
diff --git a/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts b/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
index d28617901a..e7730e4b63 100644
--- a/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
@@ -1,6 +1,6 @@
/**
* Backend-free coverage for session unlocks and cached preview privacy.
- * Security inspection is stubbed; EmbedPDF renders the actual encrypted fixture.
+ * PDFium authenticates real encrypted fixtures; server processing is stubbed.
*/
import { test, expect, type Page } from "@playwright/test";
@@ -15,40 +15,6 @@ import { suppressNativeFilePicker } from "@app/tests/helpers/ui-helpers";
const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");
const ENCRYPTED_PDF = path.join(FIXTURES_DIR, "encrypted.pdf");
-function mockUnlockSuccess(page: Page, pageCount = 1) {
- return page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify({
- encrypted: true,
- signed: false,
- ownerAuthenticated: true,
- permissions: -4,
- canModify: true,
- canAssemble: true,
- pageCount,
- }),
- }),
- );
-}
-
-function mockUnlockWrongPassword(page: Page) {
- return page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- status: 400,
- contentType: "application/problem+json",
- body: JSON.stringify({
- type: "/errors/pdf-password",
- title: "PDF password incorrect",
- status: 400,
- detail:
- "The PDF is passworded and requires the correct password to open.",
- }),
- }),
- );
-}
-
async function uploadEncryptedFile(page: Page, filePath: string) {
// `files-button`'s native picker is mocked globally
// (suppressNativeFilePicker), so the click is safe cross-browser; set the
@@ -85,6 +51,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {
// otherwise leak the native dialog onto the host and close the page).
suppressNativeFilePicker(page);
await mockAppApis(page);
+
await page.goto("/?bypassOnboarding=true");
await page.waitForSelector('[data-testid="files-button"]', {
timeout: 10000,
@@ -99,7 +66,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {
page,
}, testInfo) => {
const source = path.join(FIXTURES_DIR, "encrypted-ten-pages.pdf");
- await mockUnlockSuccess(page, 10);
+
await uploadEncryptedFile(page, source);
await fillPassword(page, "james");
await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
@@ -136,7 +103,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {
zip.file(`page-${index}.pdf`, splitPage);
const splitZip = await zip.generateAsync({ type: "nodebuffer" });
const restoredNames: string[] = [];
- await mockUnlockSuccess(page, 10);
+
await page.route("**/api/v1/security/prepare-pdf-session", (route) =>
route.fulfill({ contentType: "application/pdf", body: workingPdf }),
);
@@ -260,27 +227,12 @@ test.describe("Encrypted PDF Unlock Modal", () => {
}) => {
const sample = fs.readFileSync(path.join(FIXTURES_DIR, "sample.pdf"));
let removals = 0;
- await page.route("**/api/v1/security/remove-pdf-protection", (route) => {
+ await page.route("**/api/v1/security/remove-password", (route) => {
removals++;
+ expect(route.request().postData()).toContain('name="removeAll"');
return route.fulfill({ contentType: "application/pdf", body: sample });
});
- await page.route("**/api/v1/security/inspect-pdf-security", (route) => {
- const copy = (route.request().postData() ?? "").includes(
- "encrypted_unprotected.pdf",
- );
- return route.fulfill({
- json: {
- encrypted: !copy,
- requiresOpeningPassword: !copy,
- signed: false,
- ownerAuthenticated: !copy,
- permissions: -4,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- });
- });
+
await uploadEncryptedFile(page, ENCRYPTED_PDF);
await fillPassword(page, "testpass123");
await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
@@ -373,7 +325,6 @@ test.describe("Encrypted PDF Unlock Modal", () => {
)
removalRequests.push(request.url());
});
- await mockUnlockSuccess(page);
await uploadEncryptedFile(page, ENCRYPTED_PDF);
await expect(
@@ -421,8 +372,6 @@ test.describe("Encrypted PDF Unlock Modal", () => {
test("incorrect password keeps the modal open with an inline error", async ({
page,
}) => {
- await mockUnlockWrongPassword(page);
-
await uploadEncryptedFile(page, ENCRYPTED_PDF);
await expect(
page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
@@ -446,7 +395,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {
route.fulfill({ json: { languages: ["eng"] } }),
);
await page.goto("/ocr");
- await mockUnlockSuccess(page);
+
await uploadEncryptedFile(page, ENCRYPTED_PDF);
await fillPassword(page, "testpass123");
await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
@@ -561,8 +510,6 @@ test.describe("Encrypted PDF Unlock Modal", () => {
test("pressing Enter in the password field triggers unlock", async ({
page,
}) => {
- await mockUnlockSuccess(page);
-
await uploadEncryptedFile(page, ENCRYPTED_PDF);
await expect(
page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
@@ -579,8 +526,6 @@ test.describe("Encrypted PDF Unlock Modal", () => {
test("multi-file unlock-all closes the modal after one password entry", async ({
page,
}) => {
- await mockUnlockSuccess(page);
-
// `files-button`'s native picker is mocked globally; click it, then set
// the files on the hidden input directly.
await page.getByTestId("files-button").click();
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-permission-lifecycle.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-permission-lifecycle.spec.ts
new file mode 100644
index 0000000000..cf896d4b19
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/pdf-permission-lifecycle.spec.ts
@@ -0,0 +1,375 @@
+import path from "node:path";
+import { readFile, writeFile } from "node:fs/promises";
+import { PDFDocument, PDFName } from "@cantoo/pdf-lib";
+import { test as base, expect } from "@app/tests/helpers/stub-test-base";
+
+const test = base.extend({
+ page: async ({ page }, use) => {
+ const inspectionUploads: string[] = [];
+ page.on("request", (request) => {
+ if (new URL(request.url()).pathname.endsWith("/inspect-pdf-security"))
+ inspectionUploads.push(request.url());
+ });
+ await use(page);
+ expect(inspectionUploads, "PDF access must be inspected locally").toEqual(
+ [],
+ );
+ },
+});
+
+const links = path.join(
+ import.meta.dirname,
+ "../test-fixtures/link-annotations-sample.pdf",
+);
+
+test("removing a password keeps the result after switching tools", async ({
+ page,
+}) => {
+ const output = await readFile(links);
+ let finish!: () => void;
+ const responseReady = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ let requested = false;
+ await page.route("**/api/v1/security/remove-password", async (route) => {
+ requested = true;
+ await responseReady;
+ await route.fulfill({ contentType: "application/pdf", body: output });
+ });
+ await page.goto("/remove-password");
+ await page
+ .getByTestId("file-input")
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures/owner-only-restricted.pdf",
+ ),
+ );
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage.locator("img").first()).toBeVisible();
+ await firstPage.evaluate((node) =>
+ node.setAttribute("data-before-tool", "true"),
+ );
+ await page
+ .getByLabel("Permissions password", { exact: true })
+ .fill("owner-test-password");
+ await page
+ .getByRole("button", { name: "Remove Password", exact: true })
+ .click();
+ await expect.poll(() => requested).toBe(true);
+ try {
+ await page
+ .getByRole("button", { name: "Annotations", exact: true })
+ .click();
+ await expect(page).toHaveURL(/\/annotate$/);
+ } finally {
+ finish();
+ }
+ await expect(firstPage).not.toHaveAttribute("data-before-tool", "true");
+ await expect(firstPage.locator(".pdf-link-overlay")).toHaveCount(4);
+ await page.getByRole("button", { name: "Square", exact: true }).click();
+ await expect(
+ page.getByRole("button", { name: "Square", exact: true }),
+ ).toHaveAttribute("data-variant", "filled");
+});
+
+test("escaped encryption names still enforce permissions after admission", async ({
+ page,
+}) => {
+ const original = await readFile(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures/owner-only-restricted.pdf",
+ ),
+ );
+ const bytes = Buffer.from(
+ original.toString("latin1").replace("/Encrypt", "/En#63rypt"),
+ "latin1",
+ );
+ expect(bytes.includes(Buffer.from("/Encrypt"))).toBe(false);
+ await page.getByTestId("file-input").setInputFiles({
+ name: "escaped.pdf",
+ mimeType: "application/pdf",
+ buffer: bytes,
+ });
+ await expect(page.locator('[data-page-index="0"] img').first()).toBeVisible();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(
+ page.getByText("Protected PDF", { exact: true }).first(),
+ ).toBeVisible();
+ await page
+ .getByRole("button", { name: "Manage protection", exact: true })
+ .click();
+ await expect(
+ page
+ .getByRole("dialog")
+ .getByText("Printing", { exact: true })
+ .locator(".."),
+ ).toContainText("Restricted");
+});
+
+for (const operation of ["compress", "remove-password"] as const) {
+ test(`drawing tools work immediately after ${operation} replaces the open PDF`, async ({
+ page,
+ }) => {
+ const browserErrors: string[] = [];
+ page.on("pageerror", (error) => browserErrors.push(error.message));
+ const output = await readFile(links);
+ await page.route(
+ operation === "compress"
+ ? "**/api/v1/misc/compress-pdf"
+ : "**/api/v1/security/remove-password",
+ (route) => {
+ return route.fulfill({
+ contentType: "application/pdf",
+ body: output,
+ headers: {
+ "content-disposition": 'attachment; filename="updated.pdf"',
+ },
+ });
+ },
+ );
+ await page.goto(`/${operation}`);
+ await page
+ .getByTestId("file-input")
+ .setInputFiles(
+ operation === "compress"
+ ? links
+ : path.join(
+ import.meta.dirname,
+ "../test-fixtures/owner-only-restricted.pdf",
+ ),
+ );
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage.locator("img").first()).toBeVisible();
+ await firstPage.evaluate((node) =>
+ node.setAttribute("data-before-tool", "true"),
+ );
+ if (operation === "remove-password")
+ await page
+ .getByLabel("Permissions password", { exact: true })
+ .fill("owner-test-password");
+ await page
+ .getByRole("button", {
+ name: operation === "compress" ? "Compress" : "Remove Password",
+ exact: true,
+ })
+ .click();
+ await expect(firstPage).not.toHaveAttribute("data-before-tool", "true");
+ await expect(firstPage.locator(".pdf-link-overlay")).toHaveCount(4);
+ await page
+ .getByRole("button", { name: "Annotations", exact: true })
+ .click();
+ await expect(page).toHaveURL(/\/annotate$/);
+ await page.getByRole("button", { name: "Polygon", exact: true }).click();
+ await expect(
+ page.getByRole("button", { name: "Polygon", exact: true }),
+ ).toHaveAttribute("data-variant", "filled");
+ await page.getByRole("button", { name: "Square", exact: true }).click();
+ await expect(
+ page.getByRole("button", { name: "Square", exact: true }),
+ ).toHaveAttribute("data-variant", "filled");
+ const bounds = await firstPage.boundingBox();
+ if (!bounds) throw new Error("PDF page has no bounds");
+ await page.mouse.move(
+ bounds.x + bounds.width * 0.3,
+ bounds.y + bounds.height * 0.3,
+ );
+ await page.mouse.down();
+ await page.mouse.move(
+ bounds.x + bounds.width * 0.5,
+ bounds.y + bounds.height * 0.5,
+ { steps: 5 },
+ );
+ await page.mouse.up();
+ await expect(
+ page.getByRole("button", { name: "Save Changes", exact: true }).first(),
+ ).toBeEnabled();
+ expect(browserErrors).toEqual([]);
+ });
+}
+
+for (const role of ["reader", "owner", "unrestricted-reader"] as const) {
+ test(`opens with ${role} locally and preserves the authentication role`, async ({
+ page,
+ }, testInfo) => {
+ const pdf = await PDFDocument.load(await readFile(links));
+ const unrestricted = role === "unrestricted-reader";
+ pdf.encrypt({
+ userPassword: "reader-test",
+ ownerPassword: "owner-test",
+ permissions: {
+ copying: unrestricted,
+ modifying: unrestricted,
+ annotating: unrestricted,
+ printing: unrestricted ? "highResolution" : false,
+ },
+ });
+ const filename = testInfo.outputPath("protected.pdf");
+ await writeFile(filename, await pdf.save());
+ await page.getByTestId("file-input").setInputFiles(filename);
+ const password = page.getByLabel("Password to open", { exact: true });
+ await password.fill("incorrect-password");
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await expect(
+ page.getByRole("alert").filter({ hasText: "Incorrect password" }),
+ ).toBeVisible();
+ await password.fill(role === "owner" ? "owner-test" : "reader-test");
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(
+ page.locator('[data-page-index="0"] img').first(),
+ ).toBeVisible();
+ await expect(
+ page
+ .getByText(
+ role === "owner"
+ ? "Permissions unlocked for this session"
+ : "Protected PDF",
+ { exact: true },
+ )
+ .first(),
+ ).toBeVisible();
+ await page
+ .getByRole("button", { name: "Manage protection", exact: true })
+ .click();
+ const dialog = page.getByRole("dialog");
+ if (role === "owner") {
+ await expect(
+ dialog.getByRole("button", {
+ name: "Printing unlocked for this session",
+ exact: true,
+ }),
+ ).toBeVisible();
+ } else {
+ await expect(
+ dialog.getByText("Printing", { exact: true }).locator(".."),
+ ).toContainText(unrestricted ? "Allowed" : "Restricted");
+ }
+ });
+}
+
+test("local opening applies the administrator policy without claiming owner authentication", async ({
+ page,
+}) => {
+ await page.route("**/api/v1/config/app-config", (route) =>
+ route.fulfill({
+ json: {
+ enableLogin: false,
+ enableAnalytics: false,
+ languages: ["en-US"],
+ defaultLocale: "en-US",
+ honorOwnerPasswords: false,
+ },
+ }),
+ );
+ await page.goto("/editor");
+ await page
+ .getByTestId("file-input")
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures/owner-only-restricted.pdf",
+ ),
+ );
+ await expect(
+ page.getByText("Protected PDF", { exact: true }).first(),
+ ).toBeVisible();
+ await page
+ .getByRole("button", { name: "Manage protection", exact: true })
+ .click();
+ await expect(
+ page.getByRole("dialog").getByRole("button", {
+ name: "Printing restriction ignored",
+ exact: true,
+ }),
+ ).toBeVisible();
+});
+
+test("repeated annotation saves remain editable", async ({ page }) => {
+ await page.goto("/annotate");
+ await page.locator('input[type="file"]').first().setInputFiles(links);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ const overlays = firstPage.locator(".pdf-link-overlay");
+ await expect(overlays).toHaveCount(4);
+ await firstPage.evaluate((node) =>
+ node.setAttribute("data-permission-test", "original"),
+ );
+ for (const remaining of [3, 2]) {
+ await overlays.first().click();
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ await expect(menu).toBeVisible();
+ await menu.getByRole("button", { name: "Delete", exact: true }).click();
+ await expect(overlays).toHaveCount(remaining);
+ const save = page
+ .getByRole("button", { name: "Save Changes", exact: true })
+ .first();
+ await expect(save).toBeEnabled();
+ await save.click();
+ await expect(save).toBeDisabled();
+ await expect(firstPage).toHaveAttribute("data-permission-test", "original");
+ await expect(
+ page.getByRole("button", { name: "Undo", exact: true }).first(),
+ ).toBeEnabled();
+ }
+ await overlays.first().click();
+ await expect(
+ page.locator("[data-annotation-selection-menu]").first(),
+ ).toBeVisible();
+});
+
+for (const protection of ["ordinary", "owner-only", "opening-password"]) {
+ const encrypted = protection !== "ordinary";
+ const password = protection === "opening-password" ? "reader-test" : "";
+ test(`PDF above 100 MiB establishes ${protection} access before interaction`, async ({
+ page,
+ context,
+ }, testInfo) => {
+ test.setTimeout(180_000);
+ const pdf = await PDFDocument.load(await readFile(links));
+ const payload = pdf.context.register(
+ pdf.context.stream(new Uint8Array(105 * 1024 ** 2)),
+ );
+ pdf.catalog.set(PDFName.of("BenchmarkPayload"), payload);
+ if (encrypted)
+ pdf.encrypt({
+ userPassword: password,
+ ownerPassword: "owner-test",
+ permissions: {
+ copying: false,
+ modifying: false,
+ annotating: false,
+ printing: false,
+ },
+ });
+ const filename = testInfo.outputPath("large.pdf");
+ await writeFile(filename, await pdf.save({ useObjectStreams: false }));
+ await page.locator('input[type="file"]').first().setInputFiles(filename);
+ if (password) {
+ await page.getByLabel("Password to open", { exact: true }).fill(password);
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ }
+ const link = page.locator('.pdf-link-overlay[href^="https:"]').first();
+ await expect(link).toBeVisible({ timeout: 90_000 });
+ await link.hover();
+ const toolbar = page.locator(".pdf-link-toolbar");
+ await expect(toolbar).toBeVisible();
+ if (encrypted)
+ await expect(
+ toolbar.locator(".pdf-link-toolbar-btn--delete"),
+ ).toHaveCount(0);
+ else
+ await expect(
+ toolbar.locator(".pdf-link-toolbar-btn--delete"),
+ ).toBeVisible();
+ const href = await link.getAttribute("href");
+ if (!href) throw new Error("Fixture has no external link");
+ await context.route(href, (route) =>
+ route.fulfill({ body: "Link destination" }),
+ );
+ const popup = page.waitForEvent("popup");
+ await toolbar.locator(".pdf-link-toolbar-btn--go").click();
+ await expect(await popup).toHaveURL(href);
+ });
+}
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-permissions-workflow.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-permissions-workflow.spec.ts
index 276950560a..8a949bbd6f 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-permissions-workflow.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-permissions-workflow.spec.ts
@@ -1,6 +1,7 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import path from "node:path";
import fs from "node:fs";
+import { PDFDocument } from "@cantoo/pdf-lib";
const fixture = path.join(
import.meta.dirname,
@@ -10,32 +11,88 @@ const sample = fs.readFileSync(
path.join(import.meta.dirname, "../test-fixtures/sample.pdf"),
);
-test.beforeEach(async ({ page }) => {
- await page.route("**/api/v1/security/inspect-pdf-security", (route) => {
- const body = route.request().postData() ?? "";
- const password = /name="password"\r\n\r\n([^\r]*)/.exec(body)?.[1] ?? "";
- if (password && password !== "owner-test-password")
- return route.fulfill({
- status: 400,
- json: { type: "/errors/pdf-password", status: 400 },
+for (const entry of ["opening dialog", "Remove Password tool"]) {
+ test(`${entry} retains owner protection using local authentication`, async ({
+ page,
+ }) => {
+ const original = await PDFDocument.load(sample);
+ original.encrypt({
+ userPassword: "local-reader",
+ ownerPassword: "local-owner",
+ permissions: { printing: false },
+ });
+ const output = await PDFDocument.load(sample);
+ output.encrypt({
+ userPassword: "",
+ ownerPassword: "local-owner",
+ permissions: { printing: false },
+ });
+ const outputBytes = Buffer.from(await output.save());
+ let removals = 0;
+ await page.route("**/api/v1/security/remove-password", async (route) => {
+ const request = new Request(route.request().url(), {
+ method: "POST",
+ headers: route.request().headers(),
+ body: new Uint8Array(route.request().postDataBuffer()!),
});
- return route.fulfill({
- json: {
- encrypted: true,
- requiresOpeningPassword: false,
- signed: false,
- ownerAuthenticated: password === "owner-test-password",
- permissions: 0,
- encryptionKeyLength: 256,
- encryptionRevision: 6,
- credentialFingerprint: "fixture-credentials",
- canModify: password !== "",
- canAssemble: password !== "",
- pageCount: 1,
- },
+ const form = await request.formData();
+ expect(form.get("password")).toBe("local-reader");
+ expect(form.get("sourcePassword")).toBe("local-owner");
+ expect(form.get("ownerPassword")).toBeFalsy();
+ removals++;
+ await route.fulfill({
+ contentType: "application/pdf",
+ body: outputBytes,
+ });
+ });
+ await page.goto(
+ entry === "opening dialog" ? "/editor" : "/remove-password",
+ );
+ await page.getByTestId("file-input").setInputFiles({
+ name: "protected.pdf",
+ mimeType: "application/pdf",
+ buffer: Buffer.from(await original.save()),
+ });
+ const opening = page.getByRole("dialog", { name: /^Open PDF/ });
+ await opening
+ .getByLabel("Password to open", { exact: true })
+ .fill("local-reader");
+ if (entry === "opening dialog") {
+ await opening
+ .getByRole("button", { name: "Remove Password", exact: true })
+ .click();
+ } else {
+ await opening
+ .getByRole("button", { name: "Open PDF", exact: true })
+ .click();
+ await expect(opening).toBeHidden();
+ await page
+ .getByLabel("Password to open", { exact: true })
+ .fill("local-reader");
+ await page
+ .getByRole("button", { name: /^Remove Password(?: \(this file\))?$/ })
+ .click();
+ }
+ const verification = page.getByRole("dialog", {
+ name: "Enter permissions password",
+ exact: true,
});
+ await expect(
+ verification.getByText(/This will not remove it/),
+ ).toBeVisible();
+ await verification
+ .getByLabel("Permissions password", { exact: true })
+ .fill("local-owner");
+ await verification
+ .getByRole("button", { name: "Continue", exact: true })
+ .click();
+ await expect(verification).toBeHidden();
+ await expect(
+ page.getByText("Protected PDF", { exact: true }).first(),
+ ).toBeVisible();
+ expect(removals).toBe(1);
});
-});
+}
for (const { name, route } of [
{ name: "Remove Password", route: "/remove-password" },
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
index 4a5845450b..bd06382eea 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
@@ -1,6 +1,9 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
+import { readFile, writeFile } from "node:fs/promises";
+import { readPdfProtection } from "@app/tests/helpers/pdf-protection";
+import { PDFDocument } from "@cantoo/pdf-lib";
/** Coverage for two save/open safety features. */
@@ -30,122 +33,82 @@ async function upload(page: Page, file: string): Promise<void> {
}
test.describe("PDF text editor - encrypted PDF password prompt", () => {
- for (const protectedOutput of [true, false]) {
- test(
- protectedOutput
- ? "reuses the session unlock when opening and saving a workbench PDF"
- : "refuses to save or download an export that lost its protection",
- async ({ page }) => {
- await page.route("**/encode-charcodes", (route) => route.abort());
- let inspections = 0;
- await page.route("**/api/v1/security/inspect-pdf-security", (route) => {
- inspections++;
- return route.fulfill({
- json: {
- encrypted: inspections === 1 || protectedOutput,
- signed: false,
- ownerAuthenticated: true,
- permissions: -4,
- encryptionKeyLength: 256,
- encryptionRevision: 6,
- credentialFingerprint: "original-credentials",
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- });
- });
- await page.goto("/editor");
- await page
- .locator('[data-testid="file-input"]')
- .setInputFiles(ENCRYPTED);
- await page
- .getByLabel("Password to open", { exact: true })
- .fill(ENCRYPTED_PASSWORD);
- await page
- .getByRole("button", { name: "Open PDF", exact: true })
- .click();
- await expect(page.getByRole("dialog")).toHaveCount(0);
- await page
- .getByRole("link", { name: "PDF Text Editor", exact: true })
- .first()
- .click();
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
- });
- await expect(
- page.getByTestId("pdf-editor-password-modal"),
- ).toBeHidden();
- await expect(page.getByRole("dialog")).toHaveCount(0);
- expect(inspections).toBe(1);
+ test("saves a protected workbench PDF without uploading it for inspection", async ({
+ page,
+ }) => {
+ await page.route("**/encode-charcodes", (route) => route.abort());
+ await page.goto("/editor");
+ await page.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);
+ await page
+ .getByLabel("Password to open", { exact: true })
+ .fill(ENCRYPTED_PASSWORD);
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect(page.getByTestId("pdf-editor-password-modal")).toBeHidden();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
- await page.evaluate(() => {
- const run = document.querySelector<HTMLElement>(
- '[data-testid^="pdf-editor-run-"]',
- );
- if (!run) throw new Error("Expected an editable text run");
- run.focus();
- const range = document.createRange();
- range.selectNodeContents(run);
- range.collapse(false);
- const selection = window.getSelection()!;
- selection.removeAllRanges();
- selection.addRange(range);
- document.execCommand("insertText", false, " Test");
- });
- await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
- await page.getByTestId("pdf-editor-download").click();
- await expect(
- page.getByTestId("pdf-editor-save-risk-modal"),
- ).toContainText(/encryption/i);
- if (!protectedOutput) {
- const downloads: string[] = [];
- page.on("download", (download) =>
- downloads.push(download.suggestedFilename()),
- );
- await page.getByTestId("pdf-editor-save-risk-confirm").click();
- await expect(
- page.getByText(
- "Unable to preserve PDF protection. No unprotected result was saved.",
- ),
- ).toBeVisible();
- await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
- expect(downloads).toEqual([]);
- expect(inspections).toBe(2);
- return;
- }
- const downloadPromise = page.waitForEvent("download");
- await page.getByTestId("pdf-editor-save-risk-confirm").click();
- const download = await downloadPromise;
- expect(download.suggestedFilename()).toBe("encrypted_edited.pdf");
- await download.saveAs(test.info().outputPath("encrypted_edited.pdf"));
- await expect(page.getByRole("dialog")).toHaveCount(0);
- await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden();
- expect(inspections).toBe(2);
- },
+ await page.evaluate(() => {
+ const run = document.querySelector<HTMLElement>(
+ '[data-testid^="pdf-editor-run-"]',
+ );
+ if (!run) throw new Error("Expected an editable text run");
+ run.focus();
+ const range = document.createRange();
+ range.selectNodeContents(run);
+ range.collapse(false);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ document.execCommand("insertText", false, " Test");
+ });
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+ await page.getByTestId("pdf-editor-download").click();
+ await expect(page.getByTestId("pdf-editor-save-risk-modal")).toContainText(
+ /encryption/i,
);
- }
+
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-save-risk-confirm").click();
+ const download = await downloadPromise;
+ expect(download.suggestedFilename()).toBe("encrypted_edited.pdf");
+ const savedPath = test.info().outputPath("encrypted_edited.pdf");
+ await download.saveAs(savedPath);
+ const source = await readPdfProtection(
+ await readFile(ENCRYPTED),
+ ENCRYPTED_PASSWORD,
+ );
+ expect(
+ await readPdfProtection(await readFile(savedPath), ENCRYPTED_PASSWORD),
+ ).toMatchObject(source);
+ await expect(
+ readPdfProtection(await readFile(savedPath), "wrong-password"),
+ ).rejects.toThrow("PDF open failed");
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden();
+ });
test("keeps an unlocked signed PDF out of the text editor", async ({
page,
- }) => {
- await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- json: {
- encrypted: true,
- signed: true,
- ownerAuthenticated: true,
- permissions: -4,
- encryptionKeyLength: 256,
- encryptionRevision: 6,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- }),
- );
+ }, testInfo) => {
+ const pdf = await PDFDocument.load(await readFile(SIGNED));
+ pdf.encrypt({
+ userPassword: ENCRYPTED_PASSWORD,
+ ownerPassword: ENCRYPTED_PASSWORD,
+ });
+ const signedProtected = testInfo.outputPath("signed-protected.pdf");
+ await writeFile(signedProtected, await pdf.save());
+
await page.goto("/editor");
- await page.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);
+ await page
+ .locator('[data-testid="file-input"]')
+ .setInputFiles(signedProtected);
await page
.getByLabel("Password to open", { exact: true })
.fill(ENCRYPTED_PASSWORD);
@@ -167,21 +130,7 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {
page,
}) => {
test.setTimeout(90_000);
- await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- json: {
- encrypted: true,
- signed: false,
- ownerAuthenticated: true,
- permissions: -4,
- encryptionKeyLength: 256,
- encryptionRevision: 6,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- }),
- );
+
await gotoEditor(page);
await upload(page, ENCRYPTED);
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
index ffcfe58e3f..eb18478a00 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
@@ -17,21 +17,7 @@ for (const source of ["workbench", "disk"] as const) {
if (request.url().includes("/api/v1/misc/ocr-pdf"))
ocrRequests.push(request.url());
});
- await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- json: {
- encrypted: true,
- signed: false,
- ownerAuthenticated: true,
- permissions: -4,
- encryptionKeyLength: 256,
- encryptionRevision: 6,
- canModify: true,
- canAssemble: true,
- pageCount: 1,
- },
- }),
- );
+
if (source === "workbench") {
await page.goto("/editor");
await page.getByTestId("file-input").setInputFiles(SCAN);
diff --git a/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts
index f59d0b6094..98cfbaaf7a 100644
--- a/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts
@@ -4,22 +4,7 @@ import path from "node:path";
const fixtures = path.join(import.meta.dirname, "../test-fixtures");
-async function unlockFixture(page: Page, filename: string, pageCount: number) {
- await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
- route.fulfill({
- json: {
- encrypted:
- route.request().postData()?.includes(`filename="${filename}"`) ??
- false,
- signed: false,
- ownerAuthenticated: true,
- permissions: -4,
- canModify: true,
- canAssemble: true,
- pageCount,
- },
- }),
- );
+async function unlockFixture(page: Page, filename: string) {
await page.goto("/annotate", { waitUntil: "domcontentloaded" });
await page.getByTestId("files-button").click();
await page
@@ -41,7 +26,7 @@ async function unlockFixture(page: Page, filename: string, pageCount: number) {
test("unlocked annotations render before opening comments and remain read-only", async ({
page,
}) => {
- await unlockFixture(page, "encrypted-annotations.pdf", 3);
+ await unlockFixture(page, "encrypted-annotations.pdf");
const firstPage = page.locator('[data-page-index="0"]').first();
const annotations = firstPage.locator("[data-no-interaction]");
@@ -106,7 +91,7 @@ test("unlocked annotations render before opening comments and remain read-only",
test("unlocked links remain navigable and text selection offers reading actions only", async ({
page,
}) => {
- await unlockFixture(page, "encrypted-links.pdf", 2);
+ await unlockFixture(page, "encrypted-links.pdf");
const firstPage = page.locator('[data-page-index="0"]').first();
const links = firstPage.locator(".pdf-link-overlay");
await expect(links).toHaveCount(4, { timeout: 30_000 });
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts
index 7b835014a7..d8bd2e6b85 100644
--- a/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts
@@ -35,11 +35,14 @@ test("link annotations render as overlays with no annotation-layer hit boxes", a
test("hovering a link overlay still opens the link toolbar", async ({
page,
+ context,
}) => {
test.setTimeout(120_000);
const firstPage = await loadViewer(page);
- const overlay = firstPage.locator(".pdf-link-overlay").first();
+ const overlay = firstPage
+ .locator('.pdf-link-overlay[href^="https:"]')
+ .first();
await expect(overlay).toBeAttached({ timeout: 15_000 });
await overlay.hover();
@@ -47,6 +50,14 @@ test("hovering a link overlay still opens the link toolbar", async ({
await expect(toolbar).toBeVisible({ timeout: 5_000 });
await expect(toolbar.locator(".pdf-link-toolbar-btn--delete")).toBeVisible();
await expect(toolbar.locator(".pdf-link-toolbar-btn--go")).toBeVisible();
+ const href = await overlay.getAttribute("href");
+ if (!href) throw new Error("Fixture has no external link");
+ await context.route(href, (route) =>
+ route.fulfill({ body: "Link destination" }),
+ );
+ const popup = page.waitForEvent("popup");
+ await overlay.click();
+ await expect(await popup).toHaveURL(href);
});
test("annotation editing selects a link instead of navigating", async ({
diff --git a/frontend/editor/src/core/tests/utils/testFileHelpers.ts b/frontend/editor/src/core/tests/utils/testFileHelpers.ts
index f0034a87ac..d4ce679af5 100644
--- a/frontend/editor/src/core/tests/utils/testFileHelpers.ts
+++ b/frontend/editor/src/core/tests/utils/testFileHelpers.ts
@@ -2,7 +2,7 @@
* Test utilities for creating StirlingFile objects in tests
*/
-import { rememberPdfAccess } from "@app/services/pdfPasswordStore";
+import { rememberPdfAccess } from "@app/services/pdfAccessService";
import { StirlingFile, createStirlingFile } from "@app/types/fileContext";
/**
@@ -38,8 +38,6 @@ export function rememberUnprotectedPdf(file: File): File {
signed: false,
ownerAuthenticated: false,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
return file;
diff --git a/frontend/editor/src/core/tools/AddPassword.test.tsx b/frontend/editor/src/core/tools/AddPassword.test.tsx
index 6d958a0ddb..ada9a37d87 100644
--- a/frontend/editor/src/core/tools/AddPassword.test.tsx
+++ b/frontend/editor/src/core/tools/AddPassword.test.tsx
@@ -14,24 +14,23 @@ import type { AddPasswordFullParameters } from "@app/hooks/tools/addPassword/use
import { defaultParameters } from "@app/hooks/tools/changePermissions/useChangePermissionsParameters";
import AddPassword from "@app/tools/AddPassword";
import { createStirlingFile, type StirlingFile } from "@app/types/fileContext";
-
-const { selection, operation, flow, openRawDocument, getUserPermissions } =
- vi.hoisted(() => ({
- selection: { files: [] as StirlingFile[] },
- operation: {
- files: [] as File[],
- downloadUrl: null,
- isLoading: false,
- resetResults: vi.fn(),
- executeOperation: vi.fn().mockResolvedValue(undefined),
- undoOperation: vi.fn(),
- },
- flow: vi.fn<(config: ToolFlowConfig<AddPasswordFullParameters>) => null>(
- () => null,
- ),
- openRawDocument: vi.fn(),
- getUserPermissions: vi.fn(),
- }));
+import { clearPdfAccess, type PdfAccess } from "@app/services/pdfAccessService";
+
+const { selection, operation, flow, inspectAccess } = vi.hoisted(() => ({
+ selection: { files: [] as StirlingFile[] },
+ operation: {
+ files: [] as File[],
+ downloadUrl: null,
+ isLoading: false,
+ resetResults: vi.fn(),
+ executeOperation: vi.fn().mockResolvedValue(undefined),
+ undoOperation: vi.fn(),
+ },
+ flow: vi.fn<(config: ToolFlowConfig<AddPasswordFullParameters>) => null>(
+ () => null,
+ ),
+ inspectAccess: vi.fn(),
+}));
vi.mock("@app/components/tools/shared/createToolFlow", () => ({
createToolFlow: flow,
@@ -51,17 +50,20 @@ vi.mock("@app/components/tooltips/useAddPasswordTips", () => ({
vi.mock("@app/components/tooltips/useAddPasswordPermissionsTips", () => ({
useAddPasswordPermissionsTips: () => ({}),
}));
-vi.mock("@app/services/documentBytesCache", () => ({
- getDocumentBytes: vi.fn().mockResolvedValue(new ArrayBuffer(0)),
-}));
-vi.mock("@app/services/pdfiumService", () => ({
- getPdfiumModule: vi
- .fn()
- .mockResolvedValue({ FPDF_GetDocUserPermissions: getUserPermissions }),
- openRawDocument,
- closeDocAndFreeBuffer: vi.fn(),
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ ensureLocalPdfAccess: inspectAccess,
}));
+const access: PdfAccess = {
+ password: "",
+ encrypted: false,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: PdfPermissionFlag.AllowAll,
+ pageCount: 1,
+};
+
function currentFlow() {
return flow.mock.calls.at(-1)![0];
}
@@ -97,8 +99,8 @@ function permissionSettings() {
beforeEach(() => {
vi.clearAllMocks();
- openRawDocument.mockReset().mockResolvedValue(1);
- getUserPermissions.mockReset().mockReturnValue(PdfPermissionFlag.AllowAll);
+ clearPdfAccess();
+ inspectAccess.mockReset().mockResolvedValue(access);
selection.files = [createStirlingFile(new File([], "input.pdf"))];
operation.files = [];
operation.isLoading = false;
@@ -106,14 +108,11 @@ beforeEach(() => {
describe("Add Password permission detection", () => {
test("loads existing restrictions before encryption and preserves password settings", async () => {
- let resolveDocument!: (document: number) => void;
- const pending = new Promise<number>((resolve) => {
+ let resolveDocument!: (document: PdfAccess) => void;
+ const pending = new Promise<PdfAccess>((resolve) => {
resolveDocument = resolve;
});
- openRawDocument.mockReturnValueOnce(pending);
- getUserPermissions.mockReturnValueOnce(
- PdfPermissionFlag.AllowAll & ~PdfPermissionFlag.Print,
- );
+ inspectAccess.mockReturnValueOnce(pending);
render(<AddPassword />);
expect(currentFlow().executeButton?.disabled).toBe(true);
@@ -124,7 +123,12 @@ describe("Add Password permission detection", () => {
passwordSettings().onParameterChange("keyLength", 256);
});
- await act(async () => resolveDocument(1));
+ await act(async () =>
+ resolveDocument({
+ ...access,
+ permissions: PdfPermissionFlag.AllowAll & ~PdfPermissionFlag.Print,
+ }),
+ );
expect(permissionSettings().parameters).toEqual({
...defaultParameters,
preventPrinting: true,
@@ -146,14 +150,14 @@ describe("Add Password permission detection", () => {
},
selection.files,
);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
+ expect(inspectAccess).toHaveBeenCalledTimes(1);
});
test("keeps batch permissions manual", async () => {
selection.files.push(createStirlingFile(new File([], "second.pdf")));
render(<AddPassword />);
- expect(openRawDocument).not.toHaveBeenCalled();
+ expect(inspectAccess).not.toHaveBeenCalled();
expect(currentFlow().executeButton?.disabled).toBe(false);
act(() =>
@@ -199,7 +203,7 @@ describe("Add Password permission detection", () => {
}),
selection.files,
);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
+ expect(inspectAccess).toHaveBeenCalledTimes(1);
});
test("does not read encrypted outputs or reset results during processing and review", async () => {
@@ -217,12 +221,12 @@ describe("Add Password permission detection", () => {
rerender(<AddPassword />);
expect(currentFlow().review.isVisible).toBe(true);
- expect(openRawDocument).toHaveBeenCalledTimes(1);
+ expect(inspectAccess).toHaveBeenCalledTimes(1);
expect(operation.resetResults).not.toHaveBeenCalled();
});
test("expands the permission step to show read failures", async () => {
- openRawDocument.mockRejectedValueOnce(new Error("Cannot read PDF"));
+ inspectAccess.mockRejectedValueOnce(new Error("Cannot read PDF"));
render(<AddPassword />);
expect(currentFlow().steps[1].isCollapsed).toBe(true);
diff --git a/frontend/editor/src/core/tools/Annotate.tsx b/frontend/editor/src/core/tools/Annotate.tsx
index b35cb4b6c7..82cc21caa2 100644
--- a/frontend/editor/src/core/tools/Annotate.tsx
+++ b/frontend/editor/src/core/tools/Annotate.tsx
@@ -6,7 +6,7 @@ import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import { useNavigation } from "@app/contexts/NavigationContext";
import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import { BaseToolProps } from "@app/types/tool";
import { useSignature } from "@app/contexts/SignatureContext";
import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";
diff --git a/frontend/editor/src/core/tools/ChangePermissions.tsx b/frontend/editor/src/core/tools/ChangePermissions.tsx
index a398873924..e81e1eae3b 100644
--- a/frontend/editor/src/core/tools/ChangePermissions.tsx
+++ b/frontend/editor/src/core/tools/ChangePermissions.tsx
@@ -10,7 +10,7 @@ import { useChangePermissionsTips } from "@app/components/tooltips/useChangePerm
import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
import { BaseToolProps, ToolComponent } from "@app/types/tool";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
const ChangePermissions = (props: BaseToolProps) => {
const { t } = useTranslation();
@@ -35,10 +35,7 @@ const ChangePermissions = (props: BaseToolProps) => {
usePdfAccess(base.selectedFiles[0]);
const protectedInput =
base.selectedFiles.length > 0 &&
- base.selectedFiles.every((file) => {
- const access = getPdfAccess(file);
- return access?.encrypted && access.hasOwnerPassword !== false;
- });
+ base.selectedFiles.every((file) => getPdfAccess(file)?.encrypted);
const ownerVerified =
protectedInput &&
base.selectedFiles.every(
diff --git a/frontend/editor/src/core/tools/RemovePassword.test.tsx b/frontend/editor/src/core/tools/RemovePassword.test.tsx
new file mode 100644
index 0000000000..57e24b9277
--- /dev/null
+++ b/frontend/editor/src/core/tools/RemovePassword.test.tsx
@@ -0,0 +1,169 @@
+import type { ReactNode } from "react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import RemovePassword from "@app/tools/RemovePassword";
+import apiClient from "@app/services/apiClient";
+import {
+ clearPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+} from "@app/services/pdfAccessService";
+import { createStirlingFile, type StirlingFile } from "@app/types/fileContext";
+
+const state = vi.hoisted(() => ({
+ files: [] as StirlingFile[],
+ updateParameter: vi.fn(),
+ execute: vi.fn(),
+ requestOwner: vi.fn(),
+ ownerPassword: "owner",
+}));
+vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileContext: () => ({
+ actions: { requestPdfOwnerAccess: state.requestOwner },
+ }),
+}));
+vi.mock("@app/hooks/tools/removePassword/useRemovePasswordOperation", () => ({
+ useRemovePasswordOperation: vi.fn(),
+}));
+vi.mock("@app/components/tooltips/useRemovePasswordTips", () => ({
+ useRemovePasswordTips: () => ({}),
+}));
+vi.mock("@app/hooks/tools/shared/useBaseTool", () => ({
+ useBaseTool: () => ({
+ selectedFiles: state.files,
+ hasFiles: true,
+ hasResults: false,
+ operation: { isLoading: false },
+ handleExecute: state.execute,
+ params: {
+ parameters: { password: "reader", ownerPassword: state.ownerPassword },
+ updateParameter: state.updateParameter,
+ },
+ }),
+}));
+vi.mock("@app/components/tools/shared/createToolFlow", () => ({
+ createToolFlow: (config: {
+ steps: { content: ReactNode }[];
+ executeButton: { paramsValid: boolean; onClick: () => Promise<void> };
+ }) => (
+ <>
+ {config.steps[0].content}
+ <button
+ disabled={!config.executeButton.paramsValid}
+ onClick={config.executeButton.onClick}
+ >
+ Execute
+ </button>
+ </>
+ ),
+}));
+
+const post = vi.mocked(apiClient.post);
+const local: PdfAccess = {
+ password: "reader",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ requiresOpeningPassword: true,
+ permissions: -4,
+ pageCount: 1,
+};
+const renderTool = () =>
+ render(
+ <MantineProvider>
+ <RemovePassword />
+ </MantineProvider>,
+ );
+
+beforeEach(() => {
+ clearPdfAccess();
+ post.mockReset();
+ state.updateParameter.mockReset();
+ state.execute.mockReset();
+ state.requestOwner.mockReset();
+ state.ownerPassword = "owner";
+ state.files = [createStirlingFile(new File(["pdf"], "protected.pdf"))];
+ rememberPdfAccess(state.files[0], local);
+});
+
+describe("Remove Password protection status", () => {
+ it.each([true, false])(
+ "requests the owner locally to retain restrictions; accepted: %s",
+ async (accepted) => {
+ state.ownerPassword = "";
+ state.requestOwner.mockResolvedValue(accepted);
+ rememberPdfAccess(state.files[0], {
+ ...local,
+ requiresOpeningPassword: undefined,
+ });
+ renderTool();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Execute" }));
+ });
+ expect(state.requestOwner).toHaveBeenCalledOnce();
+ expect(state.execute).toHaveBeenCalledTimes(accepted ? 1 : 0);
+ expect(post).not.toHaveBeenCalled();
+ },
+ );
+ it("accepts selections when local owner-password information is unknown without uploading", async () => {
+ renderTool();
+ expect(screen.getByLabelText("Password to open")).toBeEnabled();
+ expect(screen.getByLabelText("Permissions password")).toBeEnabled();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Execute" }));
+ });
+ expect(state.execute).toHaveBeenCalledOnce();
+ expect(state.updateParameter).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("accepts both selections when no protection information is cached", () => {
+ clearPdfAccess();
+ renderTool();
+ expect(screen.getByLabelText("Password to open")).toBeEnabled();
+ expect(screen.getByLabelText("Permissions password")).toBeEnabled();
+ expect(state.updateParameter).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("disables only roles already known to be absent", () => {
+ rememberPdfAccess(state.files[0], {
+ ...local,
+ requiresOpeningPassword: false,
+ });
+ renderTool();
+ expect(screen.getByLabelText("Password to open")).toBeDisabled();
+ expect(screen.getByLabelText("Permissions password")).toBeEnabled();
+ expect(screen.getByText("Not set")).toBeInTheDocument();
+ expect(state.updateParameter).toHaveBeenCalledWith("password", "");
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("keeps removal selectable for a mixture of unencrypted and protected files", () => {
+ rememberPdfAccess(state.files[0], { ...local, encrypted: false });
+ const other = createStirlingFile(new File(["second"], "second.pdf"));
+ rememberPdfAccess(other, local);
+ state.files.push(other);
+ renderTool();
+ expect(screen.getByLabelText("Permissions password")).toBeEnabled();
+ expect(screen.queryByText("Not set")).not.toBeInTheDocument();
+ expect(state.updateParameter).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("updates both controls when frontend access changes", () => {
+ renderTool();
+ act(() => {
+ rememberPdfAccess(state.files[0], { ...local, encrypted: false });
+ });
+ expect(screen.getByLabelText("Password to open")).toBeDisabled();
+ expect(screen.getByLabelText("Permissions password")).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Execute" })).toBeDisabled();
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/tools/RemovePassword.tsx b/frontend/editor/src/core/tools/RemovePassword.tsx
index 410c5f098d..5ab59e9517 100644
--- a/frontend/editor/src/core/tools/RemovePassword.tsx
+++ b/frontend/editor/src/core/tools/RemovePassword.tsx
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import { useRemovePasswordParameters } from "@app/hooks/tools/removePassword/useRemovePasswordParameters";
import { useRemovePasswordOperation } from "@app/hooks/tools/removePassword/useRemovePasswordOperation";
@@ -8,16 +8,13 @@ import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
import { BaseToolProps, ToolComponent } from "@app/types/tool";
import { PasswordInput, Stack, Text } from "@mantine/core";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
-import { ensurePdfAccess } from "@app/services/pdfSessionUnlock";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import { useFileContext } from "@app/contexts/FileContext";
const RemovePassword = (props: BaseToolProps) => {
const { t } = useTranslation();
const removePasswordTips = useRemovePasswordTips();
const { actions } = useFileContext();
- const [removalSummary, setRemovalSummary] = useState("");
- const [checkingProtection, setCheckingProtection] = useState(false);
const base = useBaseTool(
"removePassword",
@@ -26,39 +23,20 @@ const RemovePassword = (props: BaseToolProps) => {
props,
);
usePdfAccess(base.selectedFiles[0]);
- useEffect(() => {
- let cancelled = false;
- setCheckingProtection(true);
- void Promise.allSettled(base.selectedFiles.map(ensurePdfAccess)).then(
- () => {
- if (!cancelled) setCheckingProtection(false);
- },
- );
- return () => {
- cancelled = true;
- };
- }, [base.selectedFiles]);
- const protectionKnown = base.selectedFiles.every(
- (file) => !!getPdfAccess(file),
- );
- const openingCount = base.selectedFiles.filter(
- (file) => getPdfAccess(file)?.requiresOpeningPassword === true,
- ).length;
- const ownerCount = base.selectedFiles.filter((file) => {
+ const openingStates = base.selectedFiles.map((file) => {
const access = getPdfAccess(file);
- return access?.encrypted && access.hasOwnerPassword !== false;
- }).length;
- const openingSet = protectionKnown && openingCount > 0;
- const ownerSet = protectionKnown && ownerCount > 0;
- const passwordDescription = (count: number) => {
+ return access?.encrypted === false
+ ? false
+ : access?.requiresOpeningPassword;
+ });
+ const openingSet = openingStates.some((set) => set !== false);
+ const ownerSet = base.selectedFiles.some(
+ (file) => getPdfAccess(file)?.encrypted !== false,
+ );
+ const passwordDescription = (states: (boolean | undefined)[]) => {
if (!base.hasFiles) return undefined;
- if (!protectionKnown)
- return checkingProtection
- ? t("removePassword.checkingProtection", "Checking protection…")
- : t(
- "removePassword.protectionUnavailable",
- "Unable to check protection",
- );
+ if (states.some((set) => set === undefined)) return undefined;
+ const count = states.filter(Boolean).length;
if (count === 0) return t("removePassword.notSet", "Not set");
if (count < base.selectedFiles.length)
return t(
@@ -74,7 +52,7 @@ const RemovePassword = (props: BaseToolProps) => {
const { password, ownerPassword } = base.params.parameters;
const updateParameter = base.params.updateParameter;
useEffect(() => {
- if (base.hasResults || base.operation.isLoading || !protectionKnown) return;
+ if (base.hasResults || base.operation.isLoading) return;
if (!openingSet && password) updateParameter("password", "");
if (!ownerSet && ownerPassword) updateParameter("ownerPassword", "");
}, [
@@ -85,7 +63,6 @@ const RemovePassword = (props: BaseToolProps) => {
updateParameter,
base.hasResults,
base.operation.isLoading,
- protectionKnown,
]);
const handleExecute = async () => {
@@ -93,8 +70,8 @@ const RemovePassword = (props: BaseToolProps) => {
for (const file of base.selectedFiles) {
const access = getPdfAccess(file);
if (
- access?.requiresOpeningPassword &&
- access.hasOwnerPassword !== false &&
+ access?.encrypted &&
+ access.requiresOpeningPassword !== false &&
!access.ownerAuthenticated
) {
const verified = await actions.requestPdfOwnerAccess(
@@ -109,37 +86,6 @@ const RemovePassword = (props: BaseToolProps) => {
}
}
}
- setRemovalSummary(
- base.selectedFiles.length > 1
- ? t(
- "removePassword.batchRemoved",
- "Entered passwords removed where set. Blank fields kept unchanged.",
- )
- : ownerPassword
- ? password
- ? t(
- "removePassword.bothRemoved",
- "Both passwords and restrictions removed.",
- )
- : openingSet
- ? t(
- "removePassword.ownerRemoved",
- "Permissions password and restrictions removed. Opening password kept.",
- )
- : t(
- "removePassword.ownerOnlyRemoved",
- "Permissions password and restrictions removed.",
- )
- : ownerSet
- ? t(
- "encryptedPdfUnlock.openingPasswordRemoved",
- "Opening password removed. Restrictions retained.",
- )
- : t(
- "removePassword.openingOnlyRemoved",
- "Opening password removed.",
- ),
- );
await base.handleExecute();
};
@@ -170,7 +116,7 @@ const RemovePassword = (props: BaseToolProps) => {
"encryptedPdfUnlock.openingPassword",
"Password to open",
)}
- description={passwordDescription(openingCount)}
+ description={passwordDescription(openingStates)}
value={openingSet ? password : ""}
onChange={(event) =>
updateParameter("password", event.currentTarget.value)
@@ -184,7 +130,11 @@ const RemovePassword = (props: BaseToolProps) => {
"encryptedPdfUnlock.ownerPassword",
"Permissions password",
)}
- description={passwordDescription(ownerCount)}
+ description={
+ base.hasFiles && !ownerSet
+ ? t("removePassword.notSet", "Not set")
+ : undefined
+ }
value={ownerSet ? (ownerPassword ?? "") : ""}
onChange={(event) =>
updateParameter("ownerPassword", event.currentTarget.value)
@@ -205,7 +155,7 @@ const RemovePassword = (props: BaseToolProps) => {
paramsValid: (openingSet && !!password) || (ownerSet && !!ownerPassword),
},
review: {
- protectionSummary: removalSummary,
+ protectionSummary: null,
isVisible: base.hasResults,
operation: base.operation,
title: t("removePassword.results.title", "Updated PDFs"),
@@ -215,7 +165,6 @@ const RemovePassword = (props: BaseToolProps) => {
});
};
-// Static method to get the operation hook for automation
RemovePassword.tool = () => useRemovePasswordOperation;
export default RemovePassword as ToolComponent;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
index 4984b0a0b6..5c9d6dedaa 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -7,15 +7,11 @@ import { Alert, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { downloadFile } from "@app/services/downloadService";
-import {
- assertPdfSessionEditable,
- unlockPdfForSession,
- verifyEditedPdfProtection,
-} from "@app/services/pdfSessionUnlock";
+import { assertPdfSessionEditable } from "@app/services/pdfSessionUnlock";
import {
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
import { useFileContext, useFileSelection } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflowActions } from "@app/contexts/ToolWorkflowContext";
@@ -186,7 +182,9 @@ export default function PdfTextEditor(_props: BaseToolProps) {
assertEditorOcrAllowed(store.document, sourceId, t);
const sourceAccess = getPdfAccess(sourceId);
if (toolId === "pdfTextEditor" && sourceAccess?.encrypted) {
- await verifyEditedPdfProtection(edited, sourceAccess);
+ assertPdfSessionEditable(sourceAccess);
+ // PDFium native text exports preserve encryption and credentials; regression tests cover each supported cipher.
+ rememberPdfAccess(edited, sourceAccess);
}
if (sourceId && parentStub) {
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(
@@ -593,11 +591,6 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const opened = store.getState();
if (!opened.hasDocument || opened.error || opened.passwordPrompt)
return null;
- if (password !== undefined) {
- const access = await unlockPdfForSession(file, password);
- if (!mountedRef.current || !store.isCurrentLoad(token)) return null;
- rememberPdfAccess(file, access);
- }
return addFiles([file], {
selectFiles: false,
});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/encryptedExport.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/encryptedExport.test.ts
new file mode 100644
index 0000000000..17614a53cb
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/encryptedExport.test.ts
@@ -0,0 +1,155 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { PDFDocument, PDFHeader, StandardFonts } from "@cantoo/pdf-lib";
+import { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { EditTextCommand } from "@app/tools/pdfTextEditor/commands/EditTextCommand";
+import { PdfiumSave } from "@app/tools/pdfTextEditor/pdfium/PdfiumSave";
+import { PdfiumTextReader } from "@app/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";
+import { readPdfiumAccess } from "@app/utils/pdfiumAccess";
+import { readEncryptionDictionary as protection } from "@app/tests/helpers/pdf-encryption";
+
+vi.mock(
+ "@app/tools/pdfTextEditor/charcode/CharcodeStrategy",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@app/tools/pdfTextEditor/charcode/CharcodeStrategy")
+ >()),
+ getActiveCharcodeStrategy: () => "helvetica",
+ }),
+);
+
+const opened: EditorDocument[] = [];
+const owner = "owner-test";
+
+async function open(bytes: Uint8Array, password: string) {
+ const doc = await EditorDocument.open(bytes, password);
+ opened.push(doc);
+ return doc;
+}
+
+async function savedBytes(doc: EditorDocument) {
+ const { blob } = await exportToBlob(doc, "encrypted.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+describe.each([
+ { name: "RC4 40-bit", minor: 3, revision: 2 },
+ { name: "RC4 128-bit", minor: 4, revision: 3 },
+ { name: "AES 128-bit", minor: 6, revision: 4 },
+ { name: "AES 256-bit", minor: 7, revision: 6 },
+])("$name text exports", ({ minor, revision }) => {
+ it.each([
+ { role: "reader", reader: "reader-test", credential: "reader-test" },
+ { role: "owner", reader: "reader-test", credential: owner },
+ { role: "owner-only", reader: "", credential: owner },
+ ])(
+ "preserves both credentials and restrictions across repeated $role saves",
+ async ({ reader, credential }) => {
+ const pdf = await PDFDocument.create();
+ pdf.context.header = PDFHeader.forVersion(1, minor);
+ const font = await pdf.embedFont(StandardFonts.Helvetica);
+ pdf
+ .addPage([300, 300])
+ .drawText("Original text", { font, size: 12, x: 20, y: 200 });
+ let bytes: Uint8Array;
+ if (revision === 6) {
+ const plain = await open(await pdf.save(), "");
+ expect(
+ plain.module.EPDF_SetEncryption(
+ plain.docPtr,
+ reader,
+ owner,
+ -4 & ~16,
+ ),
+ ).toBe(true);
+ bytes = PdfiumSave.serialize(plain);
+ } else {
+ pdf.encrypt({
+ userPassword: reader,
+ ownerPassword: owner,
+ permissions: { modifying: true, copying: false },
+ });
+ bytes = await pdf.save({ useObjectStreams: false });
+ }
+ const originalProtection = await protection(bytes);
+ expect(originalProtection.ID).toBeDefined();
+ const doc = await open(bytes, credential);
+ const originalAccess = readPdfiumAccess(
+ doc.module,
+ doc.docPtr,
+ credential,
+ );
+ expect(originalAccess).toMatchObject({
+ encrypted: true,
+ encryptionRevision: revision,
+ });
+ expect(await savedBytes(doc)).toEqual(bytes);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = doc.page(0).runs[0];
+ expect(run.text).toBe("Original text");
+
+ for (const nextText of ["First edit", "Second edit"]) {
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }).apply(
+ doc,
+ );
+ const saved = await savedBytes(doc);
+ expect(await protection(saved)).toEqual(originalProtection);
+ for (const password of [reader, owner]) {
+ const reopened = await open(saved, password);
+ expect(
+ readPdfiumAccess(reopened.module, reopened.docPtr, password),
+ ).toMatchObject({
+ encrypted: true,
+ permissions: originalAccess.permissions,
+ encryptionRevision: revision,
+ ownerAuthenticated: password === owner,
+ });
+ PdfiumTextReader.populate(reopened, reopened.page(0));
+ expect(
+ reopened
+ .page(0)
+ .runs.map((item) => item.text)
+ .join(" "),
+ ).toContain(nextText);
+ }
+ await expect(
+ EditorDocument.open(saved, "wrong-password"),
+ ).rejects.toThrow();
+ if (reader)
+ await expect(EditorDocument.open(saved, "")).rejects.toThrow();
+ }
+ },
+ );
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx
index cfd58a3a15..c18576c1b9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx
@@ -8,22 +8,27 @@ import {
waitFor,
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import apiClient from "@app/services/apiClient";
import {
+ inspectLocalPdfAccess,
clearPdfAccess,
getPdfAccess,
rememberPdfAccess,
type PdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
+
import { PermissionsPasswordButton } from "@app/tools/pdfTextEditor/components/PermissionsPasswordButton";
vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+vi.mock("@app/services/pdfAccessService", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/services/pdfAccessService")>()),
+ inspectLocalPdfAccess: vi.fn(),
+}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, fallback?: string) => fallback ?? key,
}),
}));
-const post = vi.mocked(apiClient.post);
+const inspect = vi.mocked(inspectLocalPdfAccess);
const reader: PdfAccess = {
encrypted: true,
password: "reader-password",
@@ -31,14 +36,12 @@ const reader: PdfAccess = {
ownerAuthenticated: false,
signed: false,
permissions: 0,
- canModify: false,
- canAssemble: false,
pageCount: 1,
honorOwnerPasswords: true,
};
beforeEach(() => {
- post.mockReset();
+ inspect.mockReset();
});
afterEach(() => {
cleanup();
@@ -86,7 +89,7 @@ describe("editor permissions verification", () => {
it("rejects an opening credential and resumes only after owner verification", async () => {
const { file, onVerified } = setup();
- post.mockResolvedValueOnce({ data: reader });
+ inspect.mockResolvedValueOnce(reader);
fireEvent.click(
screen.getByRole("button", { name: "Enter permissions password" }),
);
@@ -103,13 +106,11 @@ describe("editor permissions verification", () => {
expect(onVerified).not.toHaveBeenCalled();
expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);
- post.mockResolvedValueOnce({
- data: {
- ...reader,
- openingAuthenticated: false,
- ownerAuthenticated: true,
- canModify: true,
- },
+ inspect.mockResolvedValueOnce({
+ ...reader,
+ password: "owner-password",
+ openingAuthenticated: false,
+ ownerAuthenticated: true,
});
fireEvent.change(
screen.getByLabelText("Permissions password", { exact: true }),
@@ -126,8 +127,8 @@ describe("editor permissions verification", () => {
it("discards a verification response after the action unmounts", async () => {
const { file, onVerified } = setup();
- let complete!: (response: { data: PdfAccess }) => void;
- post.mockImplementationOnce(
+ let complete!: (response: PdfAccess) => void;
+ inspect.mockImplementationOnce(
() =>
new Promise((resolve) => {
complete = resolve;
@@ -142,9 +143,7 @@ describe("editor permissions verification", () => {
);
fireEvent.click(screen.getByRole("button", { name: "Continue" }));
cleanup();
- await act(async () =>
- complete({ data: { ...reader, ownerAuthenticated: true } }),
- );
+ await act(async () => complete({ ...reader, ownerAuthenticated: true }));
expect(onVerified).not.toHaveBeenCalled();
expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);
});
@@ -152,7 +151,7 @@ describe("editor permissions verification", () => {
it.each([
{ signed: true },
{ encrypted: false },
- { canModify: true },
+ { permissions: -4 },
{ ownerAuthenticated: true },
{ honorOwnerPasswords: false },
])("does not request owner verification for %j", (access) => {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx
index 43840a1897..f49378c37b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx
@@ -1,13 +1,14 @@
import { useEffect, useRef, useState } from "react";
-import axios, { type CancelTokenSource } from "axios";
import { useTranslation } from "react-i18next";
import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";
import { usePdfAccess } from "@app/hooks/usePdfAccess";
-import { rememberPdfAccess } from "@app/services/pdfPasswordStore";
import {
- hasPdfPermissionOverride,
- unlockPdfForSession,
-} from "@app/services/pdfSessionUnlock";
+ rememberPdfAccess,
+ inspectLocalPdfAccess,
+} from "@app/services/pdfAccessService";
+import { pdfAllows } from "@app/services/pdfPermissions";
+import { PdfPermissionFlag } from "@embedpdf/models";
+
import { Button } from "@app/ui/Button";
import { handlePasswordError } from "@app/utils/toolErrorHandler";
@@ -25,38 +26,37 @@ export function PermissionsPasswordButton({
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
- const pending = useRef<CancelTokenSource | null>(null);
+ const pending = useRef<AbortController | null>(null);
useEffect(() => {
setOpened(false);
setPassword("");
setError(null);
setBusy(false);
- return () => pending.current?.cancel();
+ return () => pending.current?.abort();
}, [file]);
if (
!file ||
!access?.encrypted ||
access.signed ||
- access.canModify ||
- hasPdfPermissionOverride(access)
+ pdfAllows(access, PdfPermissionFlag.ModifyContents)
)
return null;
const verify = async () => {
if (busy || !password) return;
- const cancellation = axios.CancelToken.source();
+ const cancellation = new AbortController();
pending.current = cancellation;
setBusy(true);
setError(null);
try {
- const verified = await unlockPdfForSession(
+ const verified = await inspectLocalPdfAccess(
file,
password,
- cancellation.token,
+ cancellation.signal,
);
- cancellation.token.throwIfRequested();
+ if (cancellation.signal.aborted) return;
if (!verified.ownerAuthenticated) {
setError(
t(
@@ -71,7 +71,7 @@ export function PermissionsPasswordButton({
setPassword("");
onVerified(file);
} catch (failure) {
- if (!axios.isCancel(failure)) {
+ if (!cancellation.signal.aborted) {
const message = await handlePasswordError(
failure,
t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),
@@ -80,10 +80,10 @@ export function PermissionsPasswordButton({
"Unable to verify this password. Please try again.",
),
);
- if (!cancellation.token.reason) setError(message);
+ if (!cancellation.signal.aborted) setError(message);
}
} finally {
- if (!cancellation.token.reason) setBusy(false);
+ if (!cancellation.signal.aborted) setBusy(false);
}
};
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index bc6d63a916..f5937dc2b7 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -10,13 +10,9 @@ import type { PageSnapshot } from "@app/tools/pdfTextEditor/types";
import {
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
-import {
- assertPdfSessionEditable,
- ensurePdfAccess,
- unlockPdfForSession,
-} from "@app/services/pdfSessionUnlock";
-import { detectSaveRisks } from "@app/tools/pdfTextEditor/util/documentRisks";
+} from "@app/services/pdfAccessService";
+import { assertPdfSessionEditable } from "@app/services/pdfSessionUnlock";
+import { readPdfiumAccess } from "@app/utils/pdfiumAccess";
const EAGER_PAGE_LIMIT = 5;
@@ -29,7 +25,6 @@ export function useDocumentLoader(store: EditorStore) {
return useCallback(
async (file: File, password?: string): Promise<void> => {
const documentPassword = password ?? getPdfAccess(file)?.password;
- // Each load claims a token.
const token = store.beginLoad();
store.setLoading(true);
store.setProgress({
@@ -38,7 +33,6 @@ export function useDocumentLoader(store: EditorStore) {
total: 0,
});
try {
- assertPdfSessionEditable(getPdfAccess(file));
await yieldToBrowser();
const bytes = new Uint8Array(await file.arrayBuffer());
if (!store.isCurrentLoad(token)) return;
@@ -50,24 +44,15 @@ export function useDocumentLoader(store: EditorStore) {
await yieldToBrowser();
const doc = await EditorDocument.open(bytes, documentPassword);
try {
- const access =
- password === undefined
- ? await ensurePdfAccess(file)
- : await unlockPdfForSession(file, password);
if (!store.isCurrentLoad(token)) {
doc.dispose();
return;
}
+ const access = rememberPdfAccess(
+ file,
+ readPdfiumAccess(doc.module, doc.docPtr, documentPassword ?? ""),
+ );
assertPdfSessionEditable(access);
- const risks = detectSaveRisks(doc);
- if (risks.encrypted !== access.encrypted)
- throw new Error("Unable to verify PDF security");
- assertPdfSessionEditable({
- ...access,
- encrypted: risks.encrypted,
- signed: risks.signatures > 0,
- });
- rememberPdfAccess(file, access);
} catch (error) {
doc.dispose();
throw error;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
index ed1231ef83..5b93a6b2a2 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
@@ -8,7 +8,7 @@ import {
bindPdfAccess,
clearPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
const mocks = vi.hoisted(() => ({
get: vi.fn(),
@@ -84,8 +84,6 @@ function protectSource() {
signed: false,
ownerAuthenticated: true,
permissions: -4,
- canModify: true,
- canAssemble: true,
pageCount: 1,
});
bindPdfAccess(file, "source-id" as FileId);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts
index 6968b277a3..28716a3984 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts
@@ -1,5 +1,5 @@
import type { TFunction } from "i18next";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
import { detectSaveRisks } from "@app/tools/pdfTextEditor/util/documentRisks";
import type { FileId } from "@app/types/file";
diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.ts
index edbb94373e..709e8018ab 100644
--- a/frontend/editor/src/core/types/fileContext.ts
+++ b/frontend/editor/src/core/types/fileContext.ts
@@ -9,7 +9,7 @@ import {
bindPdfAccess,
getPdfAccess,
rememberPdfAccess,
-} from "@app/services/pdfPasswordStore";
+} from "@app/services/pdfAccessService";
import type { DiskUnavailableReason } from "@app/services/desktopFileLink";
// Re-export FileId for convenience
@@ -36,6 +36,8 @@ export interface ProcessedFileMetadata {
totalPages?: number;
lastProcessed?: number;
isEncrypted?: boolean;
+ /** Verified opening-password requirement; absence means it has not been checked. */
+ requiresOpeningPassword?: boolean;
thumbnailUrl?: string;
[key: string]: unknown;
}
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index ac2fda45af..a0b96806ef 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -80,6 +80,10 @@ export interface AddPasswordRequest {
* The password to be added to the PDF file (Restricts the opening of the document itself.)
*/
password?: string;
+ /**
+ * Change permissions while retaining existing passwords and encryption. A supplied ownerPassword replaces the permissions password.
+ */
+ preserveExisting?: boolean;
/**
* Whether document assembly is prevented
*/
@@ -112,6 +116,10 @@ export interface AddPasswordRequest {
* Whether faithful printing is prevented
*/
preventPrintingFaithful?: boolean;
+ /**
+ * Credential for authenticating an existing protected source, separate from the new passwords. Omit to retain legacy add-password behaviour.
+ */
+ sourcePassword?: string;
}
export interface AddStampRequest {
/**
@@ -916,12 +924,6 @@ export interface PDFExtractImagesRequest {
*/
format?: "png" | "jpeg" | "gif";
}
-export interface PDFPasswordRequest {
- /**
- * The password of the PDF file
- */
- password?: string;
-}
export type PDFVerificationRequest = Record<string, never>;
export interface PDFWithPageNums {
/**
@@ -1261,6 +1263,28 @@ export interface RemoveBlankPagesRequest {
*/
whitePercent?: number;
}
+export interface RemovePasswordRequest {
+ /**
+ * Permissions password to remove. Supplying this field enables selective removal; leave blank to retain the permissions password.
+ */
+ ownerPassword?: string;
+ /**
+ * The password of the PDF file
+ */
+ password?: string;
+ /**
+ * Explicitly remove all passwords and restrictions, subject to the server owner-password policy. The password or sourcePassword authenticates the source; selective removal fields do not apply.
+ */
+ removeAll?: boolean;
+ /**
+ * Opening password to retain when removing only the permissions password. Supplying this field enables selective removal.
+ */
+ retainedOpeningPassword?: string;
+ /**
+ * Credential for opening the source, without selecting it for removal. Supplying this field enables selective removal; password then selects the opening password to remove and ownerPassword selects the permissions password to remove. Blank selection fields keep their passwords.
+ */
+ sourcePassword?: string;
+}
export interface RenameAttachmentRequest {
/**
* The current name of the attachment to rename
@@ -1789,7 +1813,7 @@ export interface ToolApiParams {
"/api/v1/security/redact": ManualRedactPdfRequest;
"/api/v1/security/redact-execute": RedactExecuteRequest;
"/api/v1/security/remove-cert-sign": SecurityRemoveCertSignRequest;
- "/api/v1/security/remove-password": PDFPasswordRequest;
+ "/api/v1/security/remove-password": RemovePasswordRequest;
"/api/v1/security/sanitize-pdf": SanitizePdfRequest;
"/api/v1/security/timestamp-pdf": TimestampPdfRequest;
"/api/v1/security/validate-compliance": SecurityValidateComplianceRequest;
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index b7d22ed595..26b1dd0e84 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -746,7 +746,7 @@ export const TOOL_IO: ToolIOTable = {
arity: "SISO",
},
"/api/v1/security/add-password": {
- accepts: ["PDF"],
+ accepts: ["PDF", "PDF_ENCRYPTED"],
produces: "PDF_ENCRYPTED",
arity: "SISO",
cases: [
@@ -754,6 +754,7 @@ export const TOOL_IO: ToolIOTable = {
when: [
{ param: "password", matches: [""], default: "" },
{ param: "ownerPassword", matches: [""], default: "" },
+ { param: "preserveExisting", matches: ["false"], default: "false" },
],
produces: "PDF",
arity: "SISO",
@@ -799,6 +800,13 @@ export const TOOL_IO: ToolIOTable = {
accepts: ["PDF", "PDF_ENCRYPTED"],
produces: "PDF",
arity: "SISO",
+ cases: [
+ {
+ when: [{ param: "password", matches: [""], default: "" }],
+ produces: "ANY",
+ arity: "SISO",
+ },
+ ],
},
"/api/v1/security/sanitize-pdf": {
accepts: ["PDF"],
diff --git a/frontend/editor/src/core/utils/combineAbortSignals.test.ts b/frontend/editor/src/core/utils/combineAbortSignals.test.ts
new file mode 100644
index 0000000000..454eaa9385
--- /dev/null
+++ b/frontend/editor/src/core/utils/combineAbortSignals.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { combineAbortSignals } from "@app/utils/combineAbortSignals";
+
+const nativeAny = AbortSignal.any;
+beforeEach(() => {
+ Object.defineProperty(AbortSignal, "any", { value: undefined });
+});
+afterEach(() => {
+ Object.defineProperty(AbortSignal, "any", { value: nativeAny });
+});
+
+it.each([false, true])(
+ "propagates cancellation when already aborted: %s",
+ (alreadyAborted) => {
+ const first = new AbortController();
+ const second = new AbortController();
+ const removals = [first, second].map(({ signal }) =>
+ vi.spyOn(signal, "removeEventListener"),
+ );
+ if (alreadyAborted) second.abort("closed");
+ const combined = combineAbortSignals([first.signal, second.signal]);
+ if (!alreadyAborted) second.abort("closed");
+ expect(combined.signal.aborted).toBe(true);
+ expect(combined.signal.reason).toBe("closed");
+ first.abort("later");
+ expect(combined.signal.reason).toBe("closed");
+ for (const remove of removals)
+ expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
+ },
+);
+
+it("disposes successful operations without cancelling them or retaining listeners", () => {
+ const source = new AbortController();
+ const remove = vi.spyOn(source.signal, "removeEventListener");
+ const combined = combineAbortSignals([source.signal]);
+ combined.dispose();
+ expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
+ source.abort();
+ expect(combined.signal.aborted).toBe(false);
+});
diff --git a/frontend/editor/src/core/utils/combineAbortSignals.ts b/frontend/editor/src/core/utils/combineAbortSignals.ts
new file mode 100644
index 0000000000..b626586f94
--- /dev/null
+++ b/frontend/editor/src/core/utils/combineAbortSignals.ts
@@ -0,0 +1,22 @@
+/** Combines cancellation without requiring AbortSignal.any; dispose after completion to release listeners. */
+export function combineAbortSignals(signals: readonly AbortSignal[]): {
+ signal: AbortSignal;
+ dispose: () => void;
+} {
+ if (typeof AbortSignal.any === "function")
+ return { signal: AbortSignal.any([...signals]), dispose: () => {} };
+ const controller = new AbortController();
+ const dispose = () => {
+ for (const signal of signals) signal.removeEventListener("abort", abort);
+ };
+ const abort = () => {
+ const source = signals.find((signal) => signal.aborted);
+ if (!source) return;
+ dispose();
+ controller.abort(source.reason);
+ };
+ for (const signal of signals)
+ signal.addEventListener("abort", abort, { once: true });
+ abort();
+ return { signal: controller.signal, dispose };
+}
diff --git a/frontend/editor/src/core/utils/pdfEncryptionProbe.test.ts b/frontend/editor/src/core/utils/pdfEncryptionProbe.test.ts
new file mode 100644
index 0000000000..5a7afea101
--- /dev/null
+++ b/frontend/editor/src/core/utils/pdfEncryptionProbe.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi } from "vitest";
+import {
+ containsEncryptMarker,
+ looksEncryptedFromTrailer,
+} from "@app/utils/pdfEncryptionProbe";
+
+/** PDF-shaped bytes with `trailer` written at the very end. */
+function bytesEndingWith(trailer: string, size: number): Uint8Array {
+ const bytes = new Uint8Array(size).fill(0x20); // padding
+ const tail = new TextEncoder().encode(trailer);
+ bytes.set(tail, size - tail.length);
+ return bytes;
+}
+
+describe("PDF encryption marker probe", () => {
+ it("detects /Encrypt in a trailer dictionary", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R /Encrypt 8 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("leaves an unencrypted document alone", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("does not match longer keys that merely start the same way", () => {
+ const bytes = bytesEndingWith("<< /EncryptionAware true >>\n%%EOF\n", 512);
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("survives binary bytes around the marker", () => {
+ // Under UTF-8 these become replacement characters and consume the marker.
+ const prefix = new Uint8Array([0xff, 0xfe, 0x80, 0x00, 0x9d]);
+ const marker = new TextEncoder().encode(" /Encrypt 8 0 R >>");
+ const bytes = new Uint8Array(prefix.length + marker.length);
+ bytes.set(prefix);
+ bytes.set(marker, prefix.length);
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("reports nothing for an empty read", () => {
+ expect(containsEncryptMarker(new Uint8Array(0))).toBe(false);
+ });
+});
+
+describe("bounded encryption reads", () => {
+ it.each(["head", "tail", "absent"])(
+ "checks %s without reading the whole file",
+ async (location) => {
+ const bytes = new Uint8Array(256 * 1024).fill(0x20);
+ if (location !== "absent") {
+ const marker = new TextEncoder().encode(" /Encrypt 8 0 R ");
+ bytes.set(
+ marker,
+ location === "head" ? 0 : bytes.length - marker.length,
+ );
+ }
+ const file = new File([bytes], "document.pdf");
+ const readAll = vi.spyOn(file, "arrayBuffer");
+ const slices = vi
+ .spyOn(file, "slice")
+ .mockImplementation((start, end) => {
+ const part = bytes.slice(start, end);
+ expect(part.length).toBeLessThanOrEqual(64 * 1024);
+ return { arrayBuffer: async () => part.buffer } as Blob;
+ });
+ expect(await looksEncryptedFromTrailer(file)).toBe(location !== "absent");
+ expect(readAll).not.toHaveBeenCalled();
+ expect(slices).toHaveBeenCalledTimes(location === "tail" ? 1 : 2);
+ },
+ );
+});
diff --git a/frontend/editor/src/core/utils/pdfEncryptionProbe.ts b/frontend/editor/src/core/utils/pdfEncryptionProbe.ts
new file mode 100644
index 0000000000..fd73fe8145
--- /dev/null
+++ b/frontend/editor/src/core/utils/pdfEncryptionProbe.ts
@@ -0,0 +1,19 @@
+const ENCRYPT_PROBE_BYTES = 64 * 1024;
+
+/** Binary decoding preserves bytes around the marker; the boundary excludes longer names. */
+export function containsEncryptMarker(bytes: Uint8Array): boolean {
+ return /\/Encrypt\b/.test(new TextDecoder("latin1").decode(bytes));
+}
+
+/**
+ * Reads at most 64 KiB from each end for trailer hints, including linearized PDFs.
+ * A missing marker does not prove a PDF unencrypted; opening must verify access with a parser.
+ */
+export async function looksEncryptedFromTrailer(file: Blob): Promise<boolean> {
+ const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
+ const tail = await file.slice(tailStart).arrayBuffer();
+ if (containsEncryptMarker(new Uint8Array(tail))) return true;
+ if (tailStart === 0) return false;
+ const head = await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer();
+ return containsEncryptMarker(new Uint8Array(head));
+}
diff --git a/frontend/editor/src/core/utils/pdfiumAccess.test.ts b/frontend/editor/src/core/utils/pdfiumAccess.test.ts
new file mode 100644
index 0000000000..af13c3a053
--- /dev/null
+++ b/frontend/editor/src/core/utils/pdfiumAccess.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { PdfPermissionFlag as Permission } from "@embedpdf/models";
+import { readPdfiumAccess } from "@app/utils/pdfiumAccess";
+import { pdfAllows, canPrintPdf } from "@app/services/pdfPermissions";
+
+function moduleFor(
+ permissions: number,
+ owner = false,
+ revision = 6,
+ signatures = 0,
+) {
+ return {
+ EPDF_IsEncrypted: () => true,
+ EPDF_IsOwnerUnlocked: () => owner,
+ FPDF_GetDocUserPermissions: () => permissions,
+ FPDF_GetSecurityHandlerRevision: () => revision,
+ FPDF_GetSignatureCount: () => signatures,
+ FPDF_GetPageCount: () => 3,
+ } as unknown as WrappedPdfiumModule;
+}
+
+describe("PDFium access decisions", () => {
+ it("does not confuse unrestricted reader permissions with owner authentication", () => {
+ const access = readPdfiumAccess(moduleFor(-4), 1, "reader");
+ expect(access.ownerAuthenticated).toBe(false);
+ expect(access.openingAuthenticated).toBe(true);
+ });
+
+ it("preserves stored restrictions when the owner is authenticated", () => {
+ const access = readPdfiumAccess(moduleFor(0, true), 1, "owner");
+ expect(access.permissions).toBe(0);
+ expect(access.ownerAuthenticated).toBe(true);
+ expect(access.openingAuthenticated).toBeUndefined();
+ expect(pdfAllows(access, Permission.CopyContents)).toBe(true);
+ });
+
+ it.each([2, 3, 4, 6])(
+ "interprets revision %i assembly and printing rules",
+ (revision) => {
+ const access = readPdfiumAccess(
+ moduleFor(
+ Permission.Print | Permission.ModifyContents,
+ false,
+ revision,
+ ),
+ 1,
+ "reader",
+ );
+ expect(pdfAllows(access, Permission.AssembleDocument)).toBe(
+ revision === 2,
+ );
+ expect(canPrintPdf(access)).toBe(revision === 2);
+ expect(pdfAllows(access, Permission.CopyContents)).toBe(false);
+ },
+ );
+
+ it("reads signature presence and rejects an unreadable signature count", () => {
+ expect(
+ readPdfiumAccess(moduleFor(-4, false, 6, 1), 1, "reader").signed,
+ ).toBe(true);
+ expect(() =>
+ readPdfiumAccess(moduleFor(-4, false, 6, -1), 1, "reader"),
+ ).toThrow("verify PDF security");
+ });
+});
diff --git a/frontend/editor/src/core/utils/pdfiumAccess.ts b/frontend/editor/src/core/utils/pdfiumAccess.ts
new file mode 100644
index 0000000000..7e529f0d76
--- /dev/null
+++ b/frontend/editor/src/core/utils/pdfiumAccess.ts
@@ -0,0 +1,32 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { PdfAccess } from "@app/services/pdfAccessService";
+
+/** Reads the authenticated document without reopening it or changing its protection. */
+export function readPdfiumAccess(
+ module: WrappedPdfiumModule,
+ document: number,
+ password: string,
+): PdfAccess {
+ const encrypted = module.EPDF_IsEncrypted(document);
+ const ownerAuthenticated = encrypted && module.EPDF_IsOwnerUnlocked(document);
+ const permissions = module.FPDF_GetDocUserPermissions(document);
+ const encryptionRevision = module.FPDF_GetSecurityHandlerRevision(document);
+ const signatureCount = module.FPDF_GetSignatureCount(document);
+ if (
+ !Number.isInteger(permissions) ||
+ signatureCount < 0 ||
+ (encrypted && encryptionRevision < 2)
+ )
+ throw new Error("Unable to verify PDF security");
+ return {
+ password,
+ encrypted,
+ ownerAuthenticated,
+ permissions,
+ encryptionRevision,
+ signed: signatureCount > 0,
+ pageCount: module.FPDF_GetPageCount(document),
+ requiresOpeningPassword: password === "" ? false : undefined,
+ openingAuthenticated: encrypted && !ownerAuthenticated ? true : undefined,
+ };
+}
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.test.ts b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
index 4aa77b7a85..b03cafd2d4 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.test.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
@@ -1,61 +1,9 @@
import { describe, it, expect, vi, afterEach } from "vitest";
-import { containsEncryptMarker } from "@app/utils/thumbnailUtils";
import {
PdfiumOpenError,
FPDF_ERR_PASSWORD,
} from "@app/services/pdfiumService";
-/**
- * The only signal that a PDF too large to fully parse is password-protected.
- * Tested over raw bytes because jsdom's Blob does not return its own contents
- * from arrayBuffer(), so the slicing wrapper cannot be exercised here.
- */
-
-/** PDF-shaped bytes with `trailer` written at the very end. */
-function bytesEndingWith(trailer: string, size: number): Uint8Array {
- const bytes = new Uint8Array(size).fill(0x20); // padding
- const tail = new TextEncoder().encode(trailer);
- bytes.set(tail, size - tail.length);
- return bytes;
-}
-
-describe("containsEncryptMarker — trailer probe for large PDFs", () => {
- it("detects /Encrypt in a trailer dictionary", () => {
- const bytes = bytesEndingWith(
- "trailer\n<< /Size 9 /Root 1 0 R /Encrypt 8 0 R >>\nstartxref\n1234\n%%EOF\n",
- 4096,
- );
- expect(containsEncryptMarker(bytes)).toBe(true);
- });
-
- it("leaves an unencrypted document alone", () => {
- const bytes = bytesEndingWith(
- "trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n1234\n%%EOF\n",
- 4096,
- );
- expect(containsEncryptMarker(bytes)).toBe(false);
- });
-
- it("does not match longer keys that merely start the same way", () => {
- const bytes = bytesEndingWith("<< /EncryptionAware true >>\n%%EOF\n", 512);
- expect(containsEncryptMarker(bytes)).toBe(false);
- });
-
- it("survives binary bytes around the marker", () => {
- // Under UTF-8 these become replacement characters and consume the marker.
- const prefix = new Uint8Array([0xff, 0xfe, 0x80, 0x00, 0x9d]);
- const marker = new TextEncoder().encode(" /Encrypt 8 0 R >>");
- const bytes = new Uint8Array(prefix.length + marker.length);
- bytes.set(prefix);
- bytes.set(marker, prefix.length);
- expect(containsEncryptMarker(bytes)).toBe(true);
- });
-
- it("reports nothing for an empty read", () => {
- expect(containsEncryptMarker(new Uint8Array(0))).toBe(false);
- });
-});
-
/**
* thumbnailUtils identifies password-protected PDFs from the error that
* openRawDocumentSafe throws. That guard used to regex the error *message* for
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.ts
index 8b24979ebe..a969192404 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts
@@ -11,7 +11,8 @@ import {
} from "@app/utils/pdfiumPageRender";
import { jpegExifOrientation } from "@app/utils/jpegOrientation";
import { getDocumentBytes } from "@app/services/documentBytesCache";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
+import { looksEncryptedFromTrailer } from "@app/utils/pdfEncryptionProbe";
export interface ThumbnailWithMetadata {
thumbnail: string; // Always returns a thumbnail (placeholder if needed)
@@ -39,8 +40,7 @@ function reportThumbnailFailure(file: File, error: unknown): void {
console.warn(`Thumbnail generation failed for ${file.name}:`, error);
}
-/** PDFs at or above this size never get a full-buffer client-side parse
- * (renderer OOM) - only the linearized-prefix attempt below. */
+/** Thumbnail parsing above this limit uses a bounded prefix to avoid exhausting renderer memory. */
export const LARGE_PDF_PARSE_LIMIT = 100 * 1024 * 1024;
/** Linearized PDFs keep page 1 + hint tables in the first bytes, so a small
@@ -58,9 +58,6 @@ const IMAGE_HEADER_PROBE_BYTES = 256 * 1024;
* metadata segment; the first probe covers the common case. */
const IMAGE_HEADER_PROBE_LIMIT = 4 * 1024 * 1024;
-/** Window at each end of the file searched for an /Encrypt entry. */
-const ENCRYPT_PROBE_BYTES = 64 * 1024;
-
/** Pages read between yields while collecting whole-document metadata. */
const METADATA_YIELD_INTERVAL = 50;
@@ -87,26 +84,6 @@ async function collectAllPageMetadata(
}
}
-/** Decoded latin1 because the input is binary - UTF-8 replacement characters
- * can swallow the marker. \b excludes longer keys like /Encryption. */
-export function containsEncryptMarker(bytes: Uint8Array): boolean {
- return /\/Encrypt\b/.test(new TextDecoder("latin1").decode(bytes));
-}
-
-/** /Encrypt is referenced from a trailer, never from the page data the prefix
- * parse sees. Linearized PDFs (most large ones) keep their first-page trailer at
- * the head and the main one at the tail, so both windows have to be probed.
- * Heuristic: a false positive offers unlock on a file that did not need it, a
- * false negative leaves it unopenable. */
-export async function looksEncryptedFromTrailer(file: File): Promise<boolean> {
- const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
- const tail = await file.slice(tailStart).arrayBuffer();
- if (containsEncryptMarker(new Uint8Array(tail))) return true;
- if (tailStart === 0) return false;
- const head = await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer();
- return containsEncryptMarker(new Uint8Array(head));
-}
-
interface PdfiumRenderResult {
thumbnail: string;
pageCount: number;
diff --git a/frontend/editor/src/core/utils/toolErrorHandler.ts b/frontend/editor/src/core/utils/toolErrorHandler.ts
index da9b41adb8..72354190cb 100644
--- a/frontend/editor/src/core/utils/toolErrorHandler.ts
+++ b/frontend/editor/src/core/utils/toolErrorHandler.ts
@@ -128,6 +128,8 @@ export const handlePasswordError = async (
incorrectPasswordMessage: string,
fallbackMessage: string,
): Promise<string> => {
+ if (error instanceof Error && "code" in error && error.code === 4)
+ return incorrectPasswordMessage;
const axiosError = axios.isAxiosError(error) ? error : undefined;
const status = axiosError?.response?.status;
diff --git a/frontend/editor/src/core/utils/toolIOCompat.ts b/frontend/editor/src/core/utils/toolIOCompat.ts
index e5c747ade1..4974a3f23b 100644
--- a/frontend/editor/src/core/utils/toolIOCompat.ts
+++ b/frontend/editor/src/core/utils/toolIOCompat.ts
@@ -16,7 +16,7 @@ import {
} from "@app/types/toolIO";
import { detectFileExtension, getFileFormats } from "@app/utils/fileUtils";
import type { StirlingFileStub } from "@app/types/fileContext";
-import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { getPdfAccess } from "@app/services/pdfAccessService";
import { supportsSessionUnlock } from "@app/services/pdfSessionUnlock";
export type ToolDiagnosticSeverity = "ERROR" | "WARN" | "INFO";
diff --git a/frontend/editor/src/core/workers/pdfAccessWorker.test.ts b/frontend/editor/src/core/workers/pdfAccessWorker.test.ts
new file mode 100644
index 0000000000..0e4a4a6ad6
--- /dev/null
+++ b/frontend/editor/src/core/workers/pdfAccessWorker.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { PdfAccessRequest } from "@app/workers/pdfAccessWorker";
+
+const init = vi.hoisted(() => vi.fn());
+vi.mock("@embedpdf/pdfium", () => ({ init }));
+vi.mock("@app/utils/pdfiumAccess", () => ({
+ readPdfiumAccess: () => ({ encrypted: false }),
+}));
+
+const scope = {
+ onmessage: undefined as
+ | ((event: { data: PdfAccessRequest }) => Promise<void>)
+ | undefined,
+ postMessage: vi.fn(),
+};
+const ready = {
+ PDFiumExt_Init: vi.fn(),
+ FPDF_LoadMemDocument: vi.fn(() => 1),
+ FPDF_CloseDocument: vi.fn(),
+ pdfium: {
+ HEAPU8: new Uint8Array(128),
+ wasmExports: { malloc: () => 1, free: vi.fn() },
+ },
+};
+const request: PdfAccessRequest = {
+ file: new Blob(["PDF"]),
+ password: "",
+ wasmUrl: "/pdfium.wasm",
+ wasmModule: new WebAssembly.Module(
+ new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]),
+ ),
+};
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.stubGlobal("self", scope);
+ vi.stubGlobal("fetch", vi.fn());
+ await import("@app/workers/pdfAccessWorker");
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it("instantiates the shared module without fetching WASM again", async () => {
+ init.mockImplementation(
+ ({ instantiateWasm }) =>
+ new Promise((resolve) => {
+ instantiateWasm({}, () => resolve(ready));
+ }),
+ );
+ await scope.onmessage!({ data: request });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(scope.postMessage).toHaveBeenCalledWith({
+ access: { encrypted: false },
+ });
+ expect(ready.pdfium.wasmExports.free).toHaveBeenCalledWith(1);
+});
+
+it("reports a compiled module initialization failure instead of hanging", async () => {
+ vi.spyOn(WebAssembly, "instantiate").mockRejectedValue(
+ new Error("Import mismatch"),
+ );
+ init.mockImplementation(
+ ({ instantiateWasm }) =>
+ new Promise((resolve) => {
+ instantiateWasm({}, () => resolve(ready));
+ }),
+ );
+ await scope.onmessage!({ data: request });
+ expect(scope.postMessage).toHaveBeenCalledWith({
+ error: "Unable to inspect PDF security locally",
+ });
+ expect(ready.FPDF_LoadMemDocument).not.toHaveBeenCalled();
+});
+
+it("falls back to the WASM asset when compilation is unavailable", async () => {
+ const bytes = new ArrayBuffer(8);
+ vi.mocked(fetch).mockResolvedValue({
+ ok: true,
+ arrayBuffer: async () => bytes,
+ } as Response);
+ init.mockResolvedValue(ready);
+ await scope.onmessage!({ data: { ...request, wasmModule: null } });
+ expect(fetch).toHaveBeenCalledExactlyOnceWith("/pdfium.wasm");
+ expect(init).toHaveBeenCalledExactlyOnceWith({ wasmBinary: bytes });
+ expect(scope.postMessage).toHaveBeenCalledWith({
+ access: { encrypted: false },
+ });
+});
diff --git a/frontend/editor/src/core/workers/pdfAccessWorker.ts b/frontend/editor/src/core/workers/pdfAccessWorker.ts
new file mode 100644
index 0000000000..6e2faddacc
--- /dev/null
+++ b/frontend/editor/src/core/workers/pdfAccessWorker.ts
@@ -0,0 +1,89 @@
+import { init, type PdfiumModule } from "@embedpdf/pdfium";
+import { readPdfiumAccess } from "@app/utils/pdfiumAccess";
+import type { PdfAccess } from "@app/services/pdfAccessService";
+
+/** A worker owns one inspection; termination releases its entire WASM heap. */
+export interface PdfAccessRequest {
+ file: Blob;
+ password: string;
+ wasmUrl: string;
+ wasmModule: WebAssembly.Module | null;
+}
+
+export type PdfAccessResponse =
+ | { access: PdfAccess }
+ | { error: string; code?: number };
+
+self.onmessage = async ({ data }: MessageEvent<PdfAccessRequest>) => {
+ try {
+ let rejectInstantiation!: (error: unknown) => void;
+ const instantiationFailed = new Promise<never>((_, reject) => {
+ rejectInstantiation = reject;
+ });
+ const options: Partial<PdfiumModule> & {
+ wasmBinary?: ArrayBuffer;
+ instantiateWasm?: (
+ imports: WebAssembly.Imports,
+ ready: (
+ instance: WebAssembly.Instance,
+ module: WebAssembly.Module,
+ ) => void,
+ ) => void;
+ } = {};
+ const precompiled = data.wasmModule;
+ if (precompiled) {
+ options.instantiateWasm = (imports, ready) => {
+ void WebAssembly.instantiate(precompiled, imports)
+ .then((instance) => ready(instance, precompiled))
+ .catch(rejectInstantiation);
+ };
+ } else {
+ const response = await fetch(data.wasmUrl);
+ if (!response.ok) throw new Error("Unable to load PDF security reader");
+ options.wasmBinary = await response.arrayBuffer();
+ }
+ const module = await Promise.race([init(options), instantiationFailed]);
+ module.PDFiumExt_Init();
+ const bytes = new Uint8Array(await data.file.arrayBuffer());
+ const pointer = module.pdfium.wasmExports.malloc(bytes.length);
+ if (!pointer) throw new Error("Unable to allocate memory for this PDF");
+ try {
+ // malloc can grow WASM memory, so read its current view after allocation.
+ const runtime = module.pdfium as typeof module.pdfium & {
+ HEAPU8: Uint8Array;
+ };
+ runtime.HEAPU8.set(bytes, pointer);
+ const document = module.FPDF_LoadMemDocument(
+ pointer,
+ bytes.length,
+ data.password,
+ );
+ if (!document) {
+ self.postMessage({
+ error: "Unable to open PDF",
+ code: module.FPDF_GetLastError(),
+ } satisfies PdfAccessResponse);
+ return;
+ }
+ try {
+ const access = readPdfiumAccess(module, document, data.password);
+ if (access.encrypted && data.password !== "") {
+ const empty = module.FPDF_LoadMemDocument(pointer, bytes.length, "");
+ if (empty) module.FPDF_CloseDocument(empty);
+ else if (module.FPDF_GetLastError() !== 4)
+ throw new Error("Unable to verify the PDF opening password");
+ access.requiresOpeningPassword = !empty;
+ }
+ self.postMessage({ access } satisfies PdfAccessResponse);
+ } finally {
+ module.FPDF_CloseDocument(document);
+ }
+ } finally {
+ module.pdfium.wasmExports.free(pointer);
+ }
+ } catch {
+ self.postMessage({
+ error: "Unable to inspect PDF security locally",
+ } satisfies PdfAccessResponse);
+ }
+};