#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Honor PDF permissions by default with an administrator bypass setting (#8466)
ConnorYoha7e593728dd9
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex fba98cf2c1..7365e0c759 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -976,6 +976,7 @@ public class ApplicationProperties {@Datapublic static class Security {private boolean enableLogin;+ private boolean honorOwnerPasswords = true;private boolean ssoAutoLogin;private InitialLogin initialLogin = new InitialLogin();private OAUTH2 oauth2 = new OAUTH2();diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.javaindex 2c207d522d..22312af85f 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java@@ -251,6 +251,9 @@ public class ConfigController {boolean enableLogin =applicationProperties.getSecurity().isEnableLogin() && userService != null;configData.put("enableLogin", enableLogin);+ configData.put(+ "honorOwnerPasswords",+ applicationProperties.getSecurity().isHonorOwnerPasswords());configData.put("showSettingsWhenNoLogin",applicationProperties.getSystem().isShowSettingsWhenNoLogin());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.javaindex 9fd06587f6..210b30b745 100644--- 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@@ -5,20 +5,29 @@ 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;@@ -26,14 +35,13 @@ import stirling.software.common.util.WebResponseUtils;import stirling.software.jpdfium.doc.PdfSecurity;import stirling.software.jpdfium.exception.JPDFiumException;-/**- * Stateless helpers for interactive unlocking. Neither endpoint retains credentials or documents.- */+/** Stateless helpers for interactive unlocking. No endpoint retains credentials or documents. */@SecurityApi@RequiredArgsConstructorpublic 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@@ -48,19 +56,28 @@ public class PdfSessionSecurityController {int encryptionRevision,boolean canModify,boolean canAssemble,- int pageCount) {}+ 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(), request.getPassword(), true)) {+ pdfDocumentFactory.load(request.getFileInput(), password, true)) {AccessPermission permission = document.getCurrentAccessPermission();return new SecurityInfo(document.isEncrypted(),!document.getSignatureDictionaries().isEmpty(),- permission.isOwnerPermission(),+ PdfSessionPermissions.isOwnerAuthenticated(document),document.isEncrypted()? document.getEncryption().getPermissions(): permission.getPermissionBytes(),@@ -68,8 +85,269 @@ public class PdfSessionSecurityController {document.isEncrypted() ? document.getEncryption().getRevision() : 0,permission.canModify(),permission.canAssembleDocument(),- document.getNumberOfPages());+ 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;}/**@@ -126,4 +404,19 @@ public class PdfSessionSecurityController {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/service/PdfPasswordRoles.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfPasswordRoles.javanew file mode 100644index 0000000000..64c8c7c121--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/service/PdfPasswordRoles.java@@ -0,0 +1,59 @@+package stirling.software.SPDF.service;++import java.io.IOException;++import org.apache.pdfbox.cos.COSDictionary;+import org.apache.pdfbox.cos.COSString;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;+import org.apache.pdfbox.pdmodel.encryption.PDEncryption;+import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;+import org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler;++/** Identifies password roles without changing the loaded document's authentication. */+public final class PdfPasswordRoles {+ private PdfPasswordRoles() {}++ /** Tests the opening credential independently, including when both passwords are identical. */+ public static boolean isOpeningPassword(PDDocument document, String password)+ throws IOException {+ if (!document.isEncrypted()) return false;+ var encryption =+ new PDEncryption(new COSDictionary(document.getEncryption().getCOSObject()));+ if (encryption.getRevision() < 5) {+ var ids = document.getDocument().getDocumentID();+ byte[] id = ids == null ? new byte[0] : ((COSString) ids.getObject(0)).getBytes();+ return new StandardSecurityHandler()+ .isUserPassword(+ password,+ encryption.getUserKey(),+ encryption.getOwnerKey(),+ encryption.getPermissions(),+ id,+ encryption.getRevision(),+ encryption.getLength() / 8,+ encryption.isEncryptMetaData());+ }+ // PDFBox tries the owner first. Mask only that entry in an isolated dictionary so its+ // normal password encoding, normalization and user authentication remain authoritative.+ encryption.setOwnerKey(new byte[encryption.getOwnerKey().length]);+ try {+ new StandardSecurityHandler()+ .prepareForDecryption(+ encryption,+ document.getDocument().getDocumentID(),+ new StandardDecryptionMaterial(password));+ return true;+ } catch (InvalidPasswordException incorrect) {+ return false;+ }+ }++ /** An opening-only PDF may use the same credential for both PDF security roles. */+ public static boolean hasSeparateOwnerPassword(PDDocument document, String password)+ throws IOException {+ return document.isEncrypted()+ && !(PdfSessionPermissions.isOwnerAuthenticated(document)+ && isOpeningPassword(document, password));+ }+}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfPermissionSecurityHandler.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfPermissionSecurityHandler.javanew file mode 100644index 0000000000..f0b3766873--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/service/PdfPermissionSecurityHandler.java@@ -0,0 +1,116 @@+package stirling.software.SPDF.service;++import java.io.IOException;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.nio.charset.StandardCharsets;+import java.security.GeneralSecurityException;++import javax.crypto.Cipher;+import javax.crypto.spec.SecretKeySpec;++import org.apache.pdfbox.cos.COSArray;+import org.apache.pdfbox.cos.COSString;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.encryption.AccessPermission;+import org.apache.pdfbox.pdmodel.encryption.DecryptionMaterial;+import org.apache.pdfbox.pdmodel.encryption.PDEncryption;+import org.apache.pdfbox.pdmodel.encryption.ProtectionPolicy;+import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;+import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;+import org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler;++/** Changes permission bits while retaining both credentials and the encryption revision. */+public final class PdfPermissionSecurityHandler extends SecurityHandler<ProtectionPolicy> {+ private PdfPermissionSecurityHandler(PDDocument document, byte[] key) throws IOException {+ var encryption = document.getEncryption();+ var previous = encryption.getSecurityHandler();+ setProtectionPolicy(new StandardProtectionPolicy("", "", new AccessPermission()));+ setEncryptionKey(key);+ setAES(previous.isAES());+ setDecryptMetadata(encryption.isEncryptMetaData());+ setStringFilterName(encryption.getStringFilterName());+ setStreamFilterName(encryption.getStreamFilterName());+ }++ /**+ * Requires an authenticated, unsigned document and a credential that opened its original bytes.+ */+ public static void changePermissions(+ PDDocument document, String password, AccessPermission permissions) throws IOException {+ var encryption = document.getEncryption();+ SecurityHandler<?> original = encryption.getSecurityHandler();+ if (!(original instanceof StandardSecurityHandler handler)) {+ throw new IOException("Only password-based PDF protection is supported");+ }+ byte[] key = handler.getEncryptionKey();+ int revision = encryption.getRevision();+ int permissionBytes = permissions.getPermissionBytes();+ if (revision >= 5 && revision <= 6) {+ try {+ // ISO 32000 algorithm 10 binds P to the existing file key; neither password entry+ // needs to change when only permissions change in AES-256 encryption.+ var cipher = Cipher.getInstance("AES/ECB/NoPadding");+ var secret = new SecretKeySpec(key, "AES");+ cipher.init(Cipher.DECRYPT_MODE, secret);+ byte[] perms = cipher.doFinal(encryption.getPerms());+ ByteBuffer.wrap(perms).order(ByteOrder.LITTLE_ENDIAN).putInt(permissionBytes);+ cipher.init(Cipher.ENCRYPT_MODE, secret);+ encryption.setPerms(cipher.doFinal(perms));+ } catch (GeneralSecurityException e) {+ throw new IOException("Unable to preserve PDF credentials", e);+ }+ } else if (revision >= 2 && revision <= 4) {+ byte[] reader = password.getBytes(StandardCharsets.ISO_8859_1);+ if (PdfSessionPermissions.isOwnerAuthenticated(document)) {+ reader =+ handler.getUserPassword(+ reader,+ encryption.getOwnerKey(),+ revision,+ encryption.getLength() / 8);+ }+ byte[] id =+ ((COSString) document.getDocument().getDocumentID().getObject(0)).getBytes();+ encryption.setUserKey(+ handler.computeUserPassword(+ reader,+ encryption.getOwnerKey(),+ permissionBytes,+ id,+ revision,+ encryption.getLength() / 8,+ encryption.isEncryptMetaData()));+ key =+ handler.computeEncryptedKey(+ reader,+ encryption.getOwnerKey(),+ encryption.getUserKey(),+ null,+ null,+ permissionBytes,+ id,+ revision,+ encryption.getLength() / 8,+ encryption.isEncryptMetaData(),+ false);+ } else {+ throw new IOException("Unsupported PDF encryption revision");+ }+ encryption.setPermissions(permissionBytes);+ encryption.setSecurityHandler(new PdfPermissionSecurityHandler(document, key));+ }++ /**+ * The dictionary and file key are already prepared; regenerating them would replace passwords.+ */+ @Override+ public void prepareDocumentForEncryption(PDDocument document) {}++ /** This handler only writes an already authenticated document. */+ @Override+ public void prepareForDecryption(+ PDEncryption encryption, COSArray id, DecryptionMaterial material) throws IOException {+ throw new IOException("Use the standard security handler to authenticate PDFs");+ }+}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.javanew file mode 100644index 0000000000..8b329ac994--- /dev/null+++ b/app/core/src/main/java/stirling/software/SPDF/service/PdfSessionPermissions.java@@ -0,0 +1,110 @@+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;+import org.springframework.http.HttpStatus;+import org.springframework.web.server.ResponseStatusException;++/** Permission decisions for original documents loaded read-only by the interactive workflow. */+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;+ SecurityHandler<?> handler = document.getEncryption().getSecurityHandler();+ if (!(handler instanceof StandardSecurityHandler)) {+ throw new IOException("Only password-based PDF protection is supported");+ }+ // PDFBox marks user-authenticated permissions read-only, even when every bit is allowed.+ // The owner-authenticated branch returns mutable permissions; permission bits alone cannot+ // identify which credential matched (StandardSecurityHandler.prepareForDecryption).+ return !document.getCurrentAccessPermission().isReadOnly();+ }++ /**+ * Rejects unsupported operations and restrictions before temporary decrypted bytes are created.+ */+ public static void requireOperation(+ PDDocument document, String endpoint, boolean honorOwnerPasswords) throws IOException {+ var permission = document.getCurrentAccessPermission();+ boolean permitted =+ switch (endpoint) {+ case "/api/v1/general/rotate-pdf",+ "/api/v1/general/remove-pages",+ "/api/v1/general/rearrange-pages",+ "/api/v1/general/merge-pdfs" ->+ document.isEncrypted() && document.getEncryption().getRevision() == 2+ ? permission.canModify()+ : permission.canAssembleDocument();+ case "/api/v1/general/split-pages",+ "/api/v1/general/split-pdf-by-sections",+ "/api/v1/general/split-by-size-or-count",+ "/api/v1/general/split-pdf-by-chapters",+ "/api/v1/general/split-for-poster-print",+ "/api/v1/misc/auto-split-pdf" ->+ permission.canExtractContent();+ case "/api/v1/misc/compress-pdf" -> permission.canModify();+ default ->+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST,+ "This operation cannot preserve PDF protection");+ };+ if (!document.isEncrypted()) return;+ if (!document.getSignatureDictionaries().isEmpty()) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Signed protected PDFs support viewing only");+ }+ if (honorOwnerPasswords && !isOwnerAuthenticated(document) && !permitted) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "This operation requires the permissions password");+ }+ }++ /**+ * The server policy controls owner authentication; signature-preservation limits always apply.+ */+ public static void requireOwner(PDDocument document, boolean honorOwnerPasswords)+ throws IOException {+ if (honorOwnerPasswords && document.isEncrypted() && !isOwnerAuthenticated(document)) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN,+ "Changing PDF protection requires the permissions password");+ }+ if (!document.getSignatureDictionaries().isEmpty()) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Changing protection on signed PDFs is not supported");+ }+ }+}diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex bf0f9c9752..b4c7ebc0c1 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -11,6 +11,7 @@#############################################################################################################security:+ honorOwnerPasswords: true # Require the permissions password for restricted PDF actions; opening passwords are always required.enableLogin: true # set to 'true' to enable loginssoAutoLogin: falseloginAttemptCount: 5 # lock user account after 5 tries; when using e.g. Fail2Ban you can deactivate the function with -1diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.javaindex 7e702e4fb3..3c18d0863d 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@@ -66,6 +66,12 @@ class ToolIODeclarationCoverageTest {// 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",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/PdfSessionSecurityControllerTest.javaindex 121f587e01..f7381c3538 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/PdfSessionSecurityControllerTest.java@@ -24,8 +24,11 @@ import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;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.common.model.ApplicationProperties;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.util.TempFile;import stirling.software.common.util.TempFileManager;@@ -38,6 +41,7 @@ class PdfSessionSecurityControllerTest {@TempDir Path directory;private PdfSessionSecurityController controller;private CustomPDFDocumentFactory factory;+ private ApplicationProperties properties;@BeforeEachvoid setUp() throws Exception {@@ -69,7 +73,8 @@ class PdfSessionSecurityControllerTest {}).when(tempFiles).deleteTempFile(any(java.io.File.class));- controller = new PdfSessionSecurityController(factory, tempFiles);+ properties = new ApplicationProperties();+ controller = new PdfSessionSecurityController(factory, tempFiles, properties);}private byte[] pdf(boolean encrypted, int bits) throws IOException {@@ -100,10 +105,457 @@ class PdfSessionSecurityControllerTest {}}+ @Test+ void honorsOwnerPasswordsByDefaultAndReportsPolicyWithoutChangingAuthentication()+ throws Exception {+ var original = pdf(true, 256);+ var info = controller.inspect(request(original, USER));+ assertTrue(info.honorOwnerPasswords());+ assertFalse(info.ownerAuthenticated());+ assertThrows(+ ResponseStatusException.class,+ () -> controller.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());+ }++ @ParameterizedTest+ @CsvSource({"40", "128", "256"})+ 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,+ () ->+ controller.prepare(+ request(original, "wrong"), "/api/v1/general/split-pages"));+ assertThrows(+ InvalidPasswordException.class,+ () -> controller.removeProtection(request(original, "")));+ try (var stream =+ controller+ .prepare(request(original, USER), "/api/v1/general/split-pages")+ .getBody()+ .getInputStream();+ var working = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(working.isEncrypted());+ }+ try (var stream =+ controller+ .removeProtection(request(original, USER))+ .getBody()+ .getInputStream();+ var copy = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(copy.isEncrypted());+ }+ assertTrue(controller.inspect(request(original, USER)).encrypted());+ }++ @Test+ void bypassRetainsUnknownOwnerUnlessAReplacementIsExplicit() throws Exception {+ properties.getSecurity().setHonorOwnerPasswords(false);+ var original = pdf(true, 256);+ var update = new AddPasswordRequest();+ update.setFileInput(upload(original));+ update.setPassword(USER);+ update.setPreventModify(true);+ try (var stream = controller.changePermissions(update, USER).getBody().getInputStream()) {+ byte[] bytes = stream.readAllBytes();+ assertFalse(controller.inspect(request(bytes, USER)).ownerAuthenticated());+ assertTrue(controller.inspect(request(bytes, OWNER)).ownerAuthenticated());+ }+ update.setOwnerPassword("replacement-owner");+ try (var stream = controller.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());+ }+ }+private MockMultipartFile upload(byte[] bytes) {return new MockMultipartFile("fileInput", "document.pdf", "application/pdf", bytes);}+ private byte[] protectedPdf(String reader, String owner, int bits, AccessPermission permissions)+ throws IOException {+ try (var document = new PDDocument();+ var output = new ByteArrayOutputStream()) {+ document.addPage(new PDPage());+ document.getDocumentInformation().setTitle("Protected content");+ var policy = new StandardProtectionPolicy(owner, reader, permissions);+ policy.setEncryptionKeyLength(bits);+ document.protect(policy);+ document.save(output);+ return output.toByteArray();+ }+ }++ private PDFPasswordRequest request(byte[] bytes, String password) {+ var request = new PDFPasswordRequest();+ request.setFileInput(upload(bytes));+ request.setPassword(password);+ 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()) {+ var bytes = stream.readAllBytes();+ var reader = controller.inspect(request(bytes, ""));+ assertTrue(reader.encrypted());+ assertFalse(reader.canModify());+ assertFalse(reader.requiresOpeningPassword());+ assertTrue(controller.inspect(request(bytes, OWNER)).ownerAuthenticated());+ }+ }++ @ParameterizedTest+ @CsvSource({"40", "128", "256"})+ void changingPermissionsCannotSilentlyRemoveAnOpeningPassword(int bits) throws Exception {+ var update = new AddPasswordRequest();+ 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()) {+ var bytes = stream.readAllBytes();+ assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(bytes));+ try (var output = Loader.loadPDF(bytes, USER)) {+ assertEquals(+ 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());+ }+ }++ @ParameterizedTest+ @CsvSource({"40,true", "128,true", "256,true", "40,false", "128,false", "256,false"})+ void blankRemovalFieldsKeepTheirPasswordsRegardlessOfCachedCredentials(int bits, boolean honor)+ throws Exception {+ properties.getSecurity().setHonorOwnerPasswords(honor);+ byte[] original = pdf(true, bits);+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, ""), "", OWNER, USER));+ try (var stream =+ controller+ .removePasswords(request(original, USER), "", OWNER, USER)+ .getBody()+ .getInputStream()) {+ byte[] result = stream.readAllBytes();+ var reader = controller.inspect(request(result, ""));+ assertFalse(reader.requiresOpeningPassword());+ assertTrue(reader.hasOwnerPassword());+ assertFalse(reader.ownerAuthenticated());+ assertFalse(reader.canPrint());+ assertTrue(controller.inspect(request(result, OWNER)).ownerAuthenticated());+ }+ try (var stream =+ controller+ .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));+ assertTrue(reader.requiresOpeningPassword());+ assertFalse(reader.hasOwnerPassword());+ assertTrue(reader.canPrint());+ }+ try (var stream =+ controller+ .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());+ }++ @ParameterizedTest+ @CsvSource({"true", "false"})+ void removalValidatesEachSelectedRoleAndNeverReplacesAnUnknownPassword(boolean honor)+ throws Exception {+ properties.getSecurity().setHonorOwnerPasswords(honor);+ byte[] original = pdf(true, 256);+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, OWNER), OWNER, USER, USER));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, USER), USER, USER, USER));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, USER), "", USER, USER));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, ""), OWNER, OWNER, ""));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.removePasswords(request(original, "wrong"), OWNER, USER, USER));+ }++ @ParameterizedTest+ @CsvSource({"40", "128", "256"})+ void removalSupportsFilesWithOnlyOnePassword(int bits) throws Exception {+ byte[] openingOnly = protectedPdf(USER, "", bits, new AccessPermission());+ try (var stream =+ controller+ .removePasswords(request(openingOnly, USER), "", USER, USER)+ .getBody()+ .getInputStream();+ var result = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(result.isEncrypted());+ }+ byte[] ownerOnly = protectedPdf("", OWNER, bits, new AccessPermission());+ try (var stream =+ controller+ .removePasswords(request(ownerOnly, ""), OWNER, "", "")+ .getBody()+ .getInputStream();+ var result = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(result.isEncrypted());+ }+ }++ @ParameterizedTest+ @CsvSource({"40", "128", "256"})+ void changingOnlyPermissionsRetainsUnknownPasswordsAndEncryptedContent(int bits)+ throws Exception {+ properties.getSecurity().setHonorOwnerPasswords(false);+ var permissions = new AccessPermission();+ permissions.setCanPrint(false);+ byte[] original = protectedPdf(USER, OWNER, bits, permissions);+ var update = new AddPasswordRequest();+ update.setFileInput(upload(original));+ update.setPreventModify(true);+ for (String credential : new String[] {USER, OWNER}) {+ try (var stream =+ controller.changePermissions(update, credential).getBody().getInputStream()) {+ byte[] result = stream.readAllBytes();+ try (var reader = Loader.loadPDF(result, USER);+ var owner = Loader.loadPDF(result, OWNER)) {+ assertEquals("Protected content", reader.getDocumentInformation().getTitle());+ assertEquals("Protected content", owner.getDocumentInformation().getTitle());+ assertFalse(reader.getCurrentAccessPermission().canModify());+ assertTrue(reader.getCurrentAccessPermission().canPrint());+ }+ assertFalse(controller.inspect(request(result, USER)).ownerAuthenticated());+ assertTrue(controller.inspect(request(result, OWNER)).ownerAuthenticated());+ }+ }+ }++ @ParameterizedTest+ @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());+ 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());+ }++ @ParameterizedTest+ @CsvSource({"128", "256"})+ void ownerOnlyDocumentsOpenWithoutGrantingOwnerAccess(int bits) throws Exception {+ var permissions = new AccessPermission();+ permissions.setCanAssembleDocument(false);+ permissions.setCanExtractContent(false);+ byte[] original = protectedPdf("", OWNER, bits, permissions);+ var info = controller.inspect(request(original, ""));+ assertTrue(info.encrypted());+ assertFalse(info.ownerAuthenticated());+ assertFalse(info.canAssemble());+ assertFalse(info.canExtract());+ assertThrows(+ ResponseStatusException.class,+ () -> controller.prepare(request(original, ""), "/api/v1/general/rotate-pdf"));+ try (var stream =+ controller+ .prepare(request(original, OWNER), "/api/v1/general/rotate-pdf")+ .getBody()+ .getInputStream();+ var working = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(working.isEncrypted());+ }+ assertTrue(controller.inspect(request(original, "")).encrypted());+ }++ @Test+ void preparationChecksTheOperationRatherThanAssemblyForEveryTool() throws Exception {+ var permissions = new AccessPermission();+ permissions.setCanExtractContent(false);+ permissions.setCanModify(false);+ byte[] original = protectedPdf(USER, OWNER, 256, permissions);+ assertThrows(+ ResponseStatusException.class,+ () -> controller.prepare(request(original, USER), "/api/v1/general/split-pages"));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.prepare(request(original, USER), "/api/v1/misc/compress-pdf"));+ assertThrows(+ ResponseStatusException.class,+ () -> controller.prepare(request(original, OWNER), "/api/v1/security/auto-redact"));+ try (var stream =+ controller+ .prepare(request(original, USER), "/api/v1/general/rotate-pdf")+ .getBody()+ .getInputStream();+ var working = Loader.loadPDF(stream.readAllBytes())) {+ assertFalse(working.isEncrypted());+ }+ }++ @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();+ 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());+ }++ @Test+ void changingProtectionRequiresSourceOwnerAndSeparateNewPasswords() throws Exception {+ var change = new AddPasswordRequest();+ change.setFileInput(upload(pdf(true, 256)));+ 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()) {+ byte[] result = stream.readAllBytes();+ assertFalse(controller.inspect(request(result, "new-reader")).canPrint());+ assertTrue(controller.inspect(request(result, "new-owner")).ownerAuthenticated());+ assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(result, USER));+ }+ change.setOwnerPassword("");+ assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, OWNER));+ change.setOwnerPassword("new-reader");+ assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, OWNER));+ }++ @Test+ void rejectsDistinctPasswordsThatBecomeEquivalentInLegacyEncryption() throws Exception {+ var change = new AddPasswordRequest();+ change.setFileInput(upload(pdf(false, 128)));+ change.setKeyLength(128);+ change.setPassword("a".repeat(32) + "reader");+ change.setOwnerPassword("a".repeat(32) + "owner");+ change.setPreventPrinting(true);+ assertThrows(ResponseStatusException.class, () -> controller.setProtection(change, ""));+ try (var remaining = Files.list(directory)) {+ assertEquals(0, remaining.count());+ }+ }+@Testvoid inspectAuthenticatesWithoutModifyingTheOriginal() throws Exception {byte[] original = pdf(true, 256);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.javaindex eaaeb25f85..c8997b2301 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/controller/api/AdminSettingsController.java@@ -933,6 +933,10 @@ public class AdminSettingsController {String lowerField = fieldName.toLowerCase();String lowerPath = fullPath.toLowerCase();+ if ("honorownerpasswords".equals(lowerField)) {+ return false;+ }+// Don't mask premium.key specificallyif ("key".equals(lowerField) && "premium.key".equals(lowerPath)) {return false;diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.javaindex 0d8212ca32..6c618b1729 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/controller/api/AdminSettingsControllerTest.java@@ -366,6 +366,23 @@ class AdminSettingsControllerTest {@DisplayName("getSettingsSection")class GetSettingsSection {+ @Test+ void ownerPasswordPolicyRemainsBooleanIncludingPendingFalse() {+ putPending("security.honorOwnerPasswords", false);+ @SuppressWarnings("unchecked")+ Map<String, Object> body =+ (Map<String, Object>) controller.getSettingsSection("security", true).getBody();+ assertThat(body.get("honorOwnerPasswords")).isEqualTo(true);+ assertThat(((Map<?, ?>) body.get("_pending")).get("honorOwnerPasswords"))+ .isEqualTo(false);+ applicationProperties.getSecurity().setHonorOwnerPasswords(false);+ @SuppressWarnings("unchecked")+ Map<String, Object> active =+ (Map<String, Object>)+ controller.getSettingsSection("security", false).getBody();+ assertThat(active.get("honorOwnerPasswords")).isEqualTo(false);+ }+@Test@DisplayName("returns 400 for invalid section name")void invalidSection() {diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex b32dbf52d5..181e5ab33c 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -301,7 +301,6 @@ title = "Page Number Results"[addPassword]desc = "Encrypt your PDF document with a password."-submit = "Encrypt"tags = "encrypt,password,lock,secure,protect,security,encryption,safeguard,confidential,private,restrict access"title = "Add Password"@@ -314,17 +313,6 @@ label = "Encryption Key Length"[addPassword.error]failed = "An error occurred while encrypting the PDF."-[addPassword.passwords]-stepTitle = "Passwords & Encryption"--[addPassword.passwords.owner]-label = "Owner Password"-placeholder = "Enter owner password"--[addPassword.passwords.user]-label = "User Password"-placeholder = "Enter user password"-[addPassword.results]title = "Encrypted PDFs"@@ -339,13 +327,13 @@ title = "Encryption Levels"title = "Password Protection Overview"[addPassword.tooltip.passwords]-bullet1 = "User Password: Required to open the PDF"-bullet2 = "Owner Password: Controls document permissions (not supported by all PDF viewers)"-text = "User passwords restrict opening the document, while owner passwords control what can be done with the document once opened. You can set both or just one."+bullet1 = "Password to open: Required to view the PDF"+bullet2 = "Permissions password: Protects restrictions on printing, copying and editing. Some apps or viewers may ignore these restrictions."+text = "Set either password or both. Opening the PDF does not verify the permissions password."title = "Password Types"[addPassword.tooltip.permissions]-text = "These permissions control what users can do with the PDF. Most effective when combined with an owner password."+text = "Choose which actions to restrict. A separate permissions password is required to change these restrictions."title = "Change Permissions"[addStamp]@@ -1629,6 +1617,7 @@ title = "Restart Required"[admin.settings.security]authentication = "Authentication"description = "Configure authentication, login behavior, and security policies."+pdfPermissions = "PDF permissions"title = "Security"[admin.settings.security.audit]@@ -1677,6 +1666,10 @@ label = "Disable CSRF Protection"description = "Require users to log in before accessing the application"label = "Enable Login"+[admin.settings.security.honorOwnerPasswords]+description = "Require the permissions password for restricted actions. Turning this off still requires passwords needed to open PDFs."+label = "Honor PDF permissions"+[admin.settings.security.htmlUrlSecurity]advanced = "Advanced Settings"description = "Configure URL access restrictions for HTML processing to prevent SSRF attacks"@@ -3173,7 +3166,6 @@ unknown = "Unknown"[changePermissions]desc = "Change document restrictions and permissions."loading = "Loading current permissions..."-multipleFiles = "Select a single PDF to automatically load its current permissions. These settings will apply to all selected PDFs."submit = "Change Permissions"tags = "permissions,restrictions,rights,access control,allow,deny,printing,copying,editing,modify permissions,security settings,user rights"title = "Change Permissions"@@ -3204,7 +3196,7 @@ label = "Prevent annotation modification"label = "Prevent printing"[changePermissions.permissions.preventPrintingFaithful]-label = "Prevent printing different formats"+label = "Prevent high-quality printing"[changePermissions.results]title = "Modified PDFs"@@ -3216,7 +3208,7 @@ text = "Changes document permissions, allowing/disallowing access to different ftitle = "Change Permissions"[changePermissions.tooltip.warning]-text = "To make these permissions unchangeable, use the Add Password tool to set an owner password."+text = "Compatible PDF applications honour these permissions. Keep a separate permissions password to control changes to the restrictions."[chat.actions]copy = "Copy message"@@ -3654,6 +3646,7 @@ continue = "Continue"copied = "Copied!"copy = "Copy"copyCode = "Copy code"+copyFailed = "Copy failed"dismiss = "Dismiss"done = "Done"enterValue = "Enter value"@@ -4491,26 +4484,67 @@ description = "Select the Edit Table of Contents tool to load its workspace."title = "Open the tool to start editing"[encryptedPdfUnlock]-copyCreated = "Unprotected copy created"+actionIgnored = "{{action}} restriction ignored"+actionUnlocked = "{{action}} unlocked for this session"+advanced = "Advanced"+allowed = "Allowed"+annotations = "Annotations"+authoriseAction = "This PDF requires permission to use {{action}}."+changeOwnerPassword = "Change permissions password"+chooseOwnerPassword = "Choose a different password"+continue = "Continue"+copyFailed = "Unable to create the copy. Your PDF is unchanged."+copying = "Copying content"+editing = "Editing"+enterPassword = "Enter password"+ignoredByServer = "Permissions are ignored by this server's settings. The PDF's protection is unchanged."incorrectPassword = "Incorrect password"+lowQualityPrintUnsupported = "This PDF allows low-quality printing only, which this viewer does not support."+lowResolutionOnly = "Low resolution only"+manageProtection = "Manage protection"missingFile = "The selected file is no longer available."-originalProtected = "The original PDF stays protected."-passwordHint = "Enter the PDF password to continue."+mixedProtection = "These PDFs have separate protection settings. Process them individually."+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."+ownerTitle = "Enter permissions password"+passwordRetained = "Kept unchanged"+passwordsMustDiffer = "The two passwords must be different."+permissionsUnlocked = "Permissions unlocked for this session"prepareFailed = "Unable to prepare this protected PDF for processing."-removePasswordHelp = "Open Remove Password to create an unprotected copy."+printing = "Printing"+printRestricted = "Printing is restricted. Verify permissions in Manage protection."+protectedPdf = "Protected PDF"+protectionRetained = "Protection retained"+protectionSaved = "Protection saved"+removePasswordHelp = "Open Remove Password to choose which passwords to remove."+removeProtection = "Create an unprotected copy"+replaceProtection = "These settings replace the PDF's current protection."required = "Enter the password to continue."+requiredStatus = "Required"+requiredToApply = "Required to apply changes"restoreFailed = "Unable to preserve PDF protection. No unprotected result was saved."-restrictedOperation = "This PDF restricts this operation. Reopen it with the owner password to continue."-sessionDetails = "Unlock for this session. The PDF stays protected. Remove Password creates an unprotected copy."+restrictActions = "Restrict actions"+restricted = "Restricted"+restrictedActions = "restricted actions"+restrictedOperation = "This action requires the permissions password."+retainOwnerVerification = "Verify the permissions password to keep it unchanged while removing the opening password. This will not remove it."+saveProtection = "Save protection"+securityChangeFailed = "Unable to change protection. Check the permissions password and the new security settings."+sessionDetails = "Open for this session. The PDF stays protected."sessionDetailsLabel = "About session unlocking"sessionFailed = "Unable to unlock this PDF. Please try again."-sessionSuccessBody = "Unlocked for this session. Password protection is retained."-sessionSuccessBodyWithName = "Unlocked {{fileName}} for this session. Password protection is retained."-sessionSuccessTitle = "PDF unlocked"-sessionTitle = "Unlock PDF"-signedReadOnly = "This PDF has digital signatures. Session unlocking supports viewing it, but processing signed PDFs is not supported yet."-skip = "Skip for now"-title = "Remove password to continue"+sessionSuccessBody = "Protection retained."+sessionSuccessBodyWithName = "Protection retained for {{fileName}}."+sessionSuccessTitle = "PDF opened"+sessionTitle = "Open PDF"+signedReadOnly = "This signed PDF can be viewed, but cannot be edited here."+title = "Enter PDF password"toolUnavailable = "This tool doesn't support encrypted PDFs. Remove the password first."toolUnavailableDetails = "Why {{name}} is unavailable"unlock = "Unlock"@@ -4518,10 +4552,14 @@ unlockAll = "Use for all ({{count}})"unlockAllPartialFail = "Wrong password for: {{names}}"unlockAllSuccess_one = "Unlocked {{count}} file."unlockAllSuccess_other = "Unlocked {{count}} files."-unlockPrompt = "Unlock PDF to continue"-unsupportedTool = "This tool does not yet support session-unlocked PDFs. Use Remove Password explicitly to create an unprotected copy."+unlockedForSession = "Unlocked for this session using your permissions password."+unlockPrompt = "Open PDF to continue"+unprotectedCopyConsequence = "The copy will have no passwords or restrictions. The original stays protected."+unsupportedTool = "This tool cannot yet preserve this PDF's protection."+verifiedForSession = "Verified for this session"+verifyPermissions = "Verify permissions for this session"viewerLocked = "This PDF is password-protected"-viewerUnlock = "Unlock"+viewerUnlock = "Open PDF"[encryptedPdfUnlock.password]label = "PDF password"@@ -5794,7 +5832,7 @@ tags = "delete,extract,exclude,remove pages,delete pages,remove page,delete pagetitle = "Remove Pages"[home.removePassword]-desc = "Remove password protection from your PDF document."+desc = "Remove the opening password, permissions password, or both."tags = "unlock,remove password,unlock PDF,decrypt,remove encryption,unprotect,open protected PDF,password removal,unlock protected,disable password,remove security,remove owner password"title = "Remove Password"@@ -7350,7 +7388,7 @@ nothingSelectedHint = "Click any text, image or shape on the page to edit it herocrDocumentChanged = "The document changed while OCR was running. Run OCR again to include your latest changes."ocrInvalidResult = "OCR did not return a PDF. Please try again."ocrNoLanguages = "No OCR languages are installed on the server."-ocrProtected = "OCR cannot keep this PDF's password protection. Use Remove Password to create an unprotected copy first."+ocrProtected = "OCR cannot yet preserve this PDF's protection. The protected original remains available for viewing."ocrRunning = "Recognizing text..."ocrUnavailable = "OCR is unavailable on this server."oneImage = "Image"@@ -11421,7 +11459,19 @@ text = "Specify which pages to remove from your PDF. You can select individual ptitle = "Page Selection"[removePassword]-desc = "Remove password protection from your PDF document."+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"tags = "secure,Decrypt,security,unpassword,delete password"title = "Remove Password"@@ -11432,13 +11482,9 @@ failed = "An error occurred while removing the password from the PDF."[removePassword.password]label = "Current Password"placeholder = "Enter current password"-stepTitle = "Remove Password"[removePassword.results]-title = "Decrypted PDFs"--[removePassword.tooltip]-description = "Removing password protection requires the password that was used to encrypt the PDF. This will decrypt the document, making it accessible without a password."+title = "Updated PDFs"[reorganizePages]submit = "Reorganize Pages"diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.jsonindex a555772293..66c7dbce18 100644--- a/frontend/editor/public/og-metadata.json+++ b/frontend/editor/public/og-metadata.json@@ -28,7 +28,7 @@"removePassword": {"image": "/og_images/remove-password.png","title": "Remove PDF Password - Stirling PDF",- "description": "Remove password protection from PDF documents"+ "description": "Remove the opening password, permissions password, or both."},"removePages": {"image": "/og_images/remove.png",diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.jsonindex 77d0cdcf9e..976b387d46 100644--- a/frontend/editor/public/og-metadata.saas.json+++ b/frontend/editor/public/og-metadata.saas.json@@ -29,7 +29,7 @@"removePassword": {"image": "/og_images/remove-password.png","title": "Remove PDF Password - Stirling PDF",- "description": "Remove password protection from PDF documents"+ "description": "Remove the opening password, permissions password, or both."},"removePages": {"image": "/og_images/remove.png",diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.tsindex 0e4d909853..aa8e45d9b2 100644--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { rememberUnprotectedPdf } from "@app/tests/utils/testFileHelpers";import { FileId } from "@app/types/file";import { StirlingFileStub } from "@app/types/fileContext";import { PDFDocument } from "@app/types/pageEditor";@@ -88,7 +89,7 @@ const workspace: TrackWorkspace = {const lookup = {getStub: (id: FileId) =>({ id, name: `${id}.pdf` }) as unknown as StirlingFileStub,- getFile: (id: FileId) => new File([id], `${id}.pdf`),+ getFile: (id: FileId) => rememberUnprotectedPdf(new File([id], `${id}.pdf`)),};const exportedPageIds = (call: number): string[] =>@@ -167,7 +168,10 @@ describe("buildTrackFile with images and protected PDFs", () => {expect((form as FormData).get("sourceFile")).toBe(protectedPdf);expect(await readText(built!.file)).toBe("protected result");expect(built!.file.name).toBe(anchor === A ? "photo.pdf" : "locked.pdf");- expect(getPdfAccess(built!.file)).toEqual(access);+ expect(getPdfAccess(built!.file)).toEqual({+ ...access,+ openingPassword: access.password,+ });},);});diff --git a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsxindex a1e60528ff..b7d58db127 100644--- a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx+++ b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx@@ -1,10 +1,10 @@import { Modal, Stack, Text, PasswordInput, Group } from "@mantine/core";import { Tooltip } from "@app/components/shared/Tooltip";+import { ProtectedPdfFileCard } from "@app/components/shared/ProtectedPdfFileCard";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";import { useTranslation } from "react-i18next";-import { type KeyboardEventHandler } from "react";import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";interface EncryptedPdfUnlockModalProps {@@ -13,22 +13,21 @@ interface EncryptedPdfUnlockModalProps {password: string;errorMessage?: string | null;isProcessing: boolean;- /** How many other locked files are queued behind this one. Omit where there is only ever one. */remainingCount?: number;- /** Confirm wording, where the caller's own reads better than the default. */confirmLabel?: string;- /** Session unlocking preserves the original; notification retries may instead remove protection. */sessionUnlock?: boolean;+ ownerUnlock?: boolean;+ actionLabel?: string;+ preservationReason?: string;testIdPrefix?: string;onPasswordChange: (value: string) => void;onUnlock: () => void;- /** Creates an unprotected copy using the entered password, without changing the original. */onRemovePassword?: () => void;- /** Only needed alongside a non-zero {@link EncryptedPdfUnlockModalProps.remainingCount}. */onUnlockAll?: () => void;onSkip: () => void;}+/** Removal is offered only by callers that can preserve the PDF's other protection. */const EncryptedPdfUnlockModal = ({opened,fileName,@@ -38,6 +37,9 @@ const EncryptedPdfUnlockModal = ({remainingCount = 0,confirmLabel,sessionUnlock = false,+ ownerUnlock = false,+ actionLabel,+ preservationReason,testIdPrefix,onPasswordChange,onUnlock,@@ -46,14 +48,11 @@ const EncryptedPdfUnlockModal = ({onSkip,}: EncryptedPdfUnlockModalProps) => {const { t } = useTranslation();-- const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (event) => {- if (event.key === "Enter" && !isProcessing && password.length > 0) {- event.preventDefault();- onUnlock();- }- };-+ const title = ownerUnlock+ ? t("encryptedPdfUnlock.ownerTitle", "Enter permissions password")+ : sessionUnlock+ ? t("encryptedPdfUnlock.sessionTitle", "Open PDF")+ : t("encryptedPdfUnlock.title", "Enter PDF password");return (<Modalopened={opened}@@ -62,16 +61,12 @@ const EncryptedPdfUnlockModal = ({}}title={<Group component="span" gap={6} wrap="nowrap">- <span>- {sessionUnlock- ? t("encryptedPdfUnlock.sessionTitle", "Unlock PDF")- : t("encryptedPdfUnlock.title", "Remove password to continue")}- </span>- {sessionUnlock && (+ <span>{title}</span>+ {sessionUnlock && !ownerUnlock && (<Tooltipcontent={t("encryptedPdfUnlock.sessionDetails",- "Unlock for this session. The PDF stays protected. Remove Password creates an unprotected copy.",+ "Open for this session. The PDF stays protected.",)}position="top"maxWidth={280}@@ -94,56 +89,53 @@ const EncryptedPdfUnlockModal = ({</Group>}centered- size="sm"+ size={remainingCount > 0 && onUnlockAll ? 500 : "sm"}padding="md"radius="md"styles={{ body: { paddingTop: "var(--mantine-spacing-md)" } }}withCloseButton={!isProcessing}- closeButtonProps={{- "aria-label": t("close", "Close"),- }}- data-testid={testIdPrefix ? `${testIdPrefix}-modal` : undefined}closeOnClickOutside={!isProcessing}closeOnEscape={!isProcessing}+ closeButtonProps={{ "aria-label": t("close", "Close") }}zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}+ data-testid={testIdPrefix ? `${testIdPrefix}-modal` : undefined}><Stack gap="md">- <Group- gap="sm"- wrap="nowrap"- p="sm"- style={{- background: "var(--c-surface-raised)",- borderRadius: "var(--mantine-radius-md)",- }}- >- <Icon- name="lock"- size={20}- style={{ color: "var(--c-text-muted)", flexShrink: 0 }}- />- <Text size="sm" fw={500} style={{ overflowWrap: "anywhere" }}>- {fileName}- </Text>- </Group>- {!sessionUnlock && (- <Text size="sm" c="dimmed">- {t(- "encryptedPdfUnlock.passwordHint",- "Enter the PDF password to continue.",- )}+ <ProtectedPdfFileCard fileName={fileName} />+ {(preservationReason || actionLabel) && (+ <Text size="sm">+ {preservationReason ||+ t(+ "encryptedPdfUnlock.authoriseAction",+ "This PDF requires permission to use {{action}}.",+ { action: actionLabel },+ )}</Text>)}-<PasswordInput- label={t("encryptedPdfUnlock.password.label", "PDF password")}- placeholder={t(- "encryptedPdfUnlock.password.placeholder",- "Enter the PDF password",- )}+ label={+ ownerUnlock+ ? t("encryptedPdfUnlock.ownerPassword", "Permissions password")+ : sessionUnlock+ ? t("encryptedPdfUnlock.openingPassword", "Password to open")+ : t("encryptedPdfUnlock.password.label", "PDF password")+ }+ placeholder={+ !sessionUnlock+ ? t(+ "encryptedPdfUnlock.password.placeholder",+ "Enter the PDF password",+ )+ : undefined+ }value={password}onChange={(event) => onPasswordChange(event.currentTarget.value)}- onKeyDown={handleKeyDown}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !isProcessing && password.length > 0) {+ event.preventDefault();+ onUnlock();+ }+ }}disabled={isProcessing}size="md"radius="md"@@ -153,48 +145,38 @@ const EncryptedPdfUnlockModal = ({data-autofocusdata-testid={testIdPrefix ? `${testIdPrefix}-input` : undefined}/>-- <Group justify="flex-end" gap="sm">- {!sessionUnlock && (- <Button- variant="secondary"- accent="neutral"- onClick={onSkip}- disabled={isProcessing}- data-testid={testIdPrefix ? `${testIdPrefix}-cancel` : undefined}- >- {t("encryptedPdfUnlock.skip", "Skip for now")}- </Button>- )}+ <Group justify="flex-end" gap="sm" wrap="nowrap">{remainingCount > 0 && onUnlockAll && (<Buttonvariant="secondary"onClick={onUnlockAll}loading={isProcessing}- disabled={password.length === 0}+ disabled={!password}>{t("encryptedPdfUnlock.unlockAll", "Use for all ({{count}})", {count: remainingCount + 1,})}</Button>)}- {sessionUnlock && onRemovePassword && (+ {sessionUnlock && !ownerUnlock && onRemovePassword && (<Buttonvariant="secondary"onClick={onRemovePassword}- disabled={isProcessing || password.length === 0}+ disabled={isProcessing || !password}>{t("removePassword.submit", "Remove Password")}</Button>)}<Button- variant="primary"onClick={onUnlock}loading={isProcessing}- disabled={password.length === 0}+ disabled={!password}data-testid={testIdPrefix ? `${testIdPrefix}-submit` : undefined}>- {confirmLabel ?? t("encryptedPdfUnlock.unlock", "Unlock")}+ {confirmLabel ??+ (ownerUnlock+ ? t("encryptedPdfUnlock.continue", "Continue")+ : t("encryptedPdfUnlock.openPdf", "Open PDF"))}</Button></Group></Stack>diff --git a/frontend/editor/src/core/components/shared/ProtectedPdfFileCard.tsx b/frontend/editor/src/core/components/shared/ProtectedPdfFileCard.tsxnew file mode 100644index 0000000000..2c35cf47ad--- /dev/null+++ b/frontend/editor/src/core/components/shared/ProtectedPdfFileCard.tsx@@ -0,0 +1,26 @@+import { Group, Text } from "@mantine/core";+import { Icon } from "@app/ui/Icon";++/** Shared file identity for opening and managing a protected PDF. */+export function ProtectedPdfFileCard({ fileName }: { fileName?: string }) {+ return (+ <Group+ gap="sm"+ wrap="nowrap"+ p="sm"+ style={{+ background: "var(--c-surface-raised)",+ borderRadius: "var(--mantine-radius-md)",+ }}+ >+ <Icon+ name="lock"+ size={20}+ style={{ color: "var(--c-text-muted)", flexShrink: 0 }}+ />+ <Text size="sm" fw={500} style={{ overflowWrap: "anywhere" }}>+ {fileName}+ </Text>+ </Group>+ );+}diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsxindex 9b5c1b05fa..a5eea78a6a 100644--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx@@ -1,3 +1,6 @@+import { usePdfAccess } from "@app/hooks/usePdfAccess";+import { pdfAllows } from "@app/services/pdfSessionUnlock";+import { PdfPermissionFlag } from "@embedpdf/models";import React, {useCallback,useEffect,@@ -336,6 +339,22 @@ export default function WorkbenchBar({],);+ const printAccess = usePdfAccess(activeFileId);+ const canPrint =+ pdfAllows(printAccess, PdfPermissionFlag.Print) &&+ pdfAllows(printAccess, PdfPermissionFlag.PrintHighQuality);+ const printDisabledReason =+ printAccess?.encrypted && !canPrint+ ? pdfAllows(printAccess, PdfPermissionFlag.Print)+ ? t(+ "encryptedPdfUnlock.lowQualityPrintUnsupported",+ "This PDF allows low-quality printing only, which this viewer does not support.",+ )+ : t(+ "encryptedPdfUnlock.printRestricted",+ "Printing is restricted. Verify permissions in Manage protection.",+ )+ : undefined;const handlePrint = useCallback(() => {viewerContext?.printActions?.print?.();}, [viewerContext]);@@ -400,7 +419,8 @@ export default function WorkbenchBar({downloadLabel: downloadTooltip,downloadIconName: icons.download,saveAsIconName: icons.saveAs,- onPrint: handlePrint,+ onPrint: canPrint ? handlePrint : undefined,+ printDisabledReason,onExport: handleExportAll,onClose: handleClose,};diff --git a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsxindex 216399957f..43a461c594 100644--- a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx+++ b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx@@ -26,6 +26,7 @@ export default function WorkbenchBarDesktopActions({downloadIconName,saveAsIconName,onPrint,+ printDisabledReason,onExport,onClose,enforcingProgress,@@ -54,12 +55,14 @@ export default function WorkbenchBarDesktopActions({hover={false}className="workbench-bar-action-icon"onClick={onPrint}- disabled={exportDisabled}+ disabled={exportDisabled || !onPrint}aria-label={t("workbenchBar.print", "Print PDF")}><Icon name="printer" size={"1rem"} /></ActionIcon>,- tooltipFor(t("workbenchBar.print", "Print PDF")),+ tooltipFor(+ printDisabledReason ?? t("workbenchBar.print", "Print PDF"),+ ),)}{/* Saving, and closing what was saved: only where a document is open. */}diff --git a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsxindex a2aafe9302..33f8d981e7 100644--- a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx+++ b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx@@ -17,6 +17,7 @@ export default function WorkbenchBarMobileActions({downloadIconName,saveAsIconName,onPrint,+ printDisabledReason,onExport,onClose,}: WorkbenchBarActionsProps) {@@ -46,8 +47,9 @@ export default function WorkbenchBarMobileActions({{showPrint && (<Menu.ItemleftSection={<Icon name="printer" size={"1.1rem"} />}- disabled={exportDisabled}+ disabled={exportDisabled || !onPrint}onClick={onPrint}+ title={printDisabledReason}>{t("workbenchBar.print", "Print PDF")}</Menu.Item>diff --git a/frontend/editor/src/core/components/shared/workbenchBar/types.ts b/frontend/editor/src/core/components/shared/workbenchBar/types.tsindex 17c219e35f..0717b97cf8 100644--- a/frontend/editor/src/core/components/shared/workbenchBar/types.ts+++ b/frontend/editor/src/core/components/shared/workbenchBar/types.ts@@ -17,7 +17,8 @@ export interface WorkbenchBarActionsProps {downloadLabel: string;downloadIconName: IconName;saveAsIconName?: IconName;- onPrint: () => void;+ onPrint?: () => void;+ printDisabledReason?: string;onExport: (forceNewFile?: boolean) => void;onClose: () => void;}diff --git a/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.test.tsx b/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.test.tsxindex 626092c70d..97ab04936c 100644--- a/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.test.tsx+++ b/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.test.tsx@@ -34,10 +34,10 @@ describe("AddPasswordSettings", () => {// Should render user and owner password fields labelsexpect(- screen.getByText("mock-addPassword.passwords.user.label"),+ screen.getByText("mock-encryptedPdfUnlock.openingPassword"),).toBeInTheDocument();expect(- screen.getByText("mock-addPassword.passwords.owner.label"),+ screen.getByText("mock-encryptedPdfUnlock.newOwnerPassword"),).toBeInTheDocument();});@@ -69,7 +69,7 @@ describe("AddPasswordSettings", () => {// Check that main section titles are renderedexpect(- screen.getByText("mock-addPassword.passwords.user.label"),+ screen.getByText("mock-encryptedPdfUnlock.openingPassword"),).toBeInTheDocument();expect(screen.getByText("mock-addPassword.encryption.keyLength.label"),@@ -88,7 +88,7 @@ describe("AddPasswordSettings", () => {// This test is complex with Mantine's PasswordInput, just verify the component rendersexpect(- screen.getByText("mock-addPassword.passwords.user.label"),+ screen.getByText("mock-encryptedPdfUnlock.openingPassword"),).toBeInTheDocument();});@@ -174,12 +174,12 @@ describe("AddPasswordSettings", () => {// Verify that translation keys are being calledexpect(mockT).toHaveBeenCalledWith(- "addPassword.passwords.user.label",- "User Password",+ "encryptedPdfUnlock.openingPassword",+ "Password to open",);expect(mockT).toHaveBeenCalledWith(- "addPassword.passwords.owner.label",- "Owner Password",+ "encryptedPdfUnlock.newOwnerPassword",+ "New permissions password",);});diff --git a/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.tsx b/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.tsxindex 9c8010d419..c9d65907a6 100644--- a/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.tsx+++ b/frontend/editor/src/core/components/tools/addPassword/AddPasswordSettings.tsx@@ -1,4 +1,4 @@-import { Stack, PasswordInput, Select } from "@mantine/core";+import { Stack, PasswordInput, Select, Text } from "@mantine/core";import { useTranslation } from "react-i18next";import { AddPasswordParameters } from "@app/hooks/tools/addPassword/useAddPasswordParameters";import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";@@ -10,44 +10,62 @@ interface AddPasswordSettingsProps {value: AddPasswordParameters[K],) => void;disabled?: boolean;+ showOwnerPassword?: boolean;}const AddPasswordSettings = ({parameters,onParameterChange,disabled = false,+ showOwnerPassword = true,}: AddPasswordSettingsProps) => {const { t } = useTranslation();return (<Stack gap="md">- {/* Password Settings */}<Stack gap="sm"><PasswordInput- label={t("addPassword.passwords.user.label", "User Password")}- placeholder={t(- "addPassword.passwords.user.placeholder",- "Enter user password",+ size="xs"+ label={+ showOwnerPassword+ ? t("encryptedPdfUnlock.openingPassword", "Password to open")+ : undefined+ }+ aria-label={t(+ "encryptedPdfUnlock.openingPassword",+ "Password to open",)}+ placeholder={t("encryptedPdfUnlock.enterPassword", "Enter password")}value={parameters.password}onChange={(e) => onParameterChange("password", e.target.value)}disabled={disabled}/>- <PasswordInput- label={t("addPassword.passwords.owner.label", "Owner Password")}- placeholder={t(- "addPassword.passwords.owner.placeholder",- "Enter owner password",- )}- value={parameters.ownerPassword}- onChange={(e) => onParameterChange("ownerPassword", e.target.value)}- disabled={disabled}- />+ {showOwnerPassword && (+ <PasswordInput+ size="xs"+ label={t(+ "encryptedPdfUnlock.newOwnerPassword",+ "New permissions password",+ )}+ placeholder={t(+ "encryptedPdfUnlock.chooseOwnerPassword",+ "Choose a different password",+ )}+ value={parameters.ownerPassword}+ onChange={(e) => onParameterChange("ownerPassword", e.target.value)}+ disabled={disabled}+ />+ )}</Stack>- {/* Encryption Settings */}- <Stack gap="sm">+ <details>+ <summary>+ <Text component="span" size="xs">+ {t("encryptedPdfUnlock.advanced", "Advanced")}+ </Text>+ </summary><Select+ size="xs"label={t("addPassword.encryption.keyLength.label","Encryption Key Length",@@ -87,7 +105,7 @@ const AddPasswordSettings = ({zIndex: Z_INDEX_AUTOMATE_DROPDOWN,}}/>- </Stack>+ </details></Stack>);};diff --git a/frontend/editor/src/core/components/tools/changePermissions/ChangePermissionsSettings.tsx b/frontend/editor/src/core/components/tools/changePermissions/ChangePermissionsSettings.tsxindex 3a953f130c..d473759246 100644--- a/frontend/editor/src/core/components/tools/changePermissions/ChangePermissionsSettings.tsx+++ b/frontend/editor/src/core/components/tools/changePermissions/ChangePermissionsSettings.tsx@@ -13,8 +13,6 @@ interface ChangePermissionsSettingsProps {isLoading?: boolean;/** Extraction failed for the selected PDF; manual settings remain usable. */hasReadError?: boolean;- /** Batch selection skips detection and applies these settings to every selected file. */- multipleFiles?: boolean;}const ChangePermissionsSettings = ({@@ -23,20 +21,11 @@ const ChangePermissionsSettings = ({disabled = false,isLoading = false,hasReadError = false,- multipleFiles = false,}: ChangePermissionsSettingsProps) => {const { t } = useTranslation();return (<Stack gap="sm">- {multipleFiles && (- <Text size="sm">- {t(- "changePermissions.multipleFiles",- "Select a single PDF to automatically load its current permissions. These settings will apply to all selected PDFs.",- )}- </Text>- )}{isLoading && (<Text size="sm" role="status">{t("changePermissions.loading", "Loading current permissions…")}@@ -52,7 +41,14 @@ const ChangePermissionsSettings = ({)}<Stack gap="xs">{(- Object.keys(parameters) as Array<keyof ChangePermissionsParameters>+ Object.keys(parameters).filter((key) =>+ key.startsWith("prevent"),+ ) as Array<+ Exclude<+ keyof ChangePermissionsParameters,+ "ownerPassword" | "password"+ >+ >).map((key) => (<Checkboxkey={key}diff --git a/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx b/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsxnew file mode 100644index 0000000000..fd7ef6a7dd--- /dev/null+++ b/frontend/editor/src/core/components/tools/shared/PdfProtectionResult.tsx@@ -0,0 +1,30 @@+import { Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { usePdfAccess } from "@app/hooks/usePdfAccess";+import { getPdfAccess } from "@app/services/pdfPasswordStore";++/** Reports protection changes only for outputs whose security was verified. */+export function PdfProtectionResult({+ files,+ summary,+}: {+ files: File[];+ summary?: string;+}) {+ const { t } = useTranslation();+ usePdfAccess(undefined);+ if (+ !files.length ||+ !files.every((file) => {+ const access = getPdfAccess(file);+ return access && (summary || access.encrypted);+ })+ )+ return null;+ return (+ <Text size="xs" role="status">+ {summary ??+ t("encryptedPdfUnlock.protectionRetained", "Protection retained")}+ </Text>+ );+}diff --git a/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx b/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsxindex 7b07e3d7b3..8326ca67e0 100644--- a/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx+++ b/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx@@ -14,7 +14,7 @@ function RemovePasswordAction() {<Tooltipcontent={t("encryptedPdfUnlock.removePasswordHelp",- "Open Remove Password to create an unprotected copy.",+ "Open Remove Password to choose which passwords to remove.",)}position="top"maxWidth={230}diff --git a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsxindex e1a763e147..dd1bff02e3 100644--- a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx+++ b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx@@ -1,5 +1,5 @@import React from "react";-import { Stack } from "@mantine/core";+import { Stack, Text } from "@mantine/core";import {createToolSteps,ToolStepProvider,@@ -15,6 +15,7 @@ import type { TooltipTip } from "@app/types/tips";import type { ExecuteDisabledReason } from "@app/hooks/tools/shared/toolOperationTypes";import classes from "@app/components/tools/shared/createToolFlow.module.css";import { ToolFileEligibility } from "@app/contexts/ToolFileEligibilityContext";+import { PdfProtectionResult } from "@app/components/tools/shared/PdfProtectionResult";export interface FilesStepConfig {selectedFiles: StirlingFile[];@@ -70,6 +71,7 @@ export interface ExecuteButtonConfig {}export interface ReviewStepConfig<TParams = unknown> {+ protectionSummary?: string;isVisible: boolean;operation: ToolOperationHook<TParams>;title: string;@@ -196,7 +198,19 @@ export function createToolFlow<TParams = unknown>();})()}+ {!config.review.isVisible && config.review.operation.errorMessage && (+ <Text role="alert" size="sm" c="var(--c-danger)">+ {config.review.operation.errorMessage}+ </Text>+ )}+{/* Review Step */}+ {config.review.isVisible && (+ <PdfProtectionResult+ files={config.review.operation.files}+ summary={config.review.protectionSummary}+ />+ )}{steps.createReviewStep({isVisible: config.review.isVisible,operation: config.review.operation,diff --git a/frontend/editor/src/core/components/tooltips/useAddPasswordPermissionsTips.ts b/frontend/editor/src/core/components/tooltips/useAddPasswordPermissionsTips.tsindex 83004cb54c..a695a02211 100644--- a/frontend/editor/src/core/components/tooltips/useAddPasswordPermissionsTips.ts+++ b/frontend/editor/src/core/components/tooltips/useAddPasswordPermissionsTips.ts@@ -12,7 +12,7 @@ export const useAddPasswordPermissionsTips = (): TooltipContent => {{description: t("addPassword.tooltip.permissions.text",- "These permissions control what users can do with the PDF. Most effective when combined with an owner password.",+ "Choose which actions to restrict. A separate permissions password is required to change these restrictions.",),},],diff --git a/frontend/editor/src/core/components/tooltips/useAddPasswordTips.ts b/frontend/editor/src/core/components/tooltips/useAddPasswordTips.tsindex 29321ff558..ae29326bcb 100644--- a/frontend/editor/src/core/components/tooltips/useAddPasswordTips.ts+++ b/frontend/editor/src/core/components/tooltips/useAddPasswordTips.ts@@ -16,16 +16,16 @@ export const useAddPasswordTips = (): TooltipContent => {title: t("addPassword.tooltip.passwords.title", "Password Types"),description: t("addPassword.tooltip.passwords.text",- "User passwords restrict opening the document, while owner passwords control what can be done with the document once opened. You can set both or just one.",+ "Set either password or both. Opening the PDF does not verify the permissions password.",),bullets: [t("addPassword.tooltip.passwords.bullet1",- "User Password: Required to open the PDF",+ "Password to open: Required to view the PDF",),t("addPassword.tooltip.passwords.bullet2",- "Owner Password: Controls document permissions (not supported by all PDF viewers)",+ "Permissions password: Protects restrictions on printing, copying and editing. Some apps or viewers may ignore these restrictions.",),],},diff --git a/frontend/editor/src/core/components/tooltips/useChangePermissionsTips.ts b/frontend/editor/src/core/components/tooltips/useChangePermissionsTips.tsindex 9bd20bc207..3d530a1899 100644--- a/frontend/editor/src/core/components/tooltips/useChangePermissionsTips.ts+++ b/frontend/editor/src/core/components/tooltips/useChangePermissionsTips.ts@@ -19,7 +19,7 @@ export const useChangePermissionsTips = (): TooltipContent => {title: t("warning.tooltipTitle", "Warning"),description: t("changePermissions.tooltip.warning.text",- "To make these permissions unchangeable, use the Add Password tool to set an owner password.",+ "Compatible PDF applications honour these permissions. Keep a separate permissions password to control changes to the restrictions.",),},],diff --git a/frontend/editor/src/core/components/tooltips/useRemovePasswordTips.ts b/frontend/editor/src/core/components/tooltips/useRemovePasswordTips.tsindex 6148e9c8be..51cb125d26 100644--- a/frontend/editor/src/core/components/tooltips/useRemovePasswordTips.ts+++ b/frontend/editor/src/core/components/tooltips/useRemovePasswordTips.ts@@ -11,8 +11,8 @@ export const useRemovePasswordTips = (): TooltipContent => {tips: [{description: t(- "removePassword.tooltip.description",- "Removing password protection requires the current password that was used to encrypt the PDF. This will decrypt the document, making it accessible without a password.",+ "removePassword.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.",),},],diff --git a/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsxindex a425cd290b..f307b03108 100644--- a/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx@@ -1,5 +1,4 @@import { useEffect, useMemo } from "react";-import { canPrintPdf } from "@app/services/pdfPermissions";import { useViewer } from "@app/contexts/ViewerContext";import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";import {@@ -11,9 +10,8 @@ import {function hasPermissionFlag(permissions: number,flag: PdfPermissionFlag,- isEncrypted: boolean,): boolean {- if (!isEncrypted || permissions === PdfPermissionFlag.AllowAll) {+ if (permissions === PdfPermissionFlag.AllowAll) {return true;}return (permissions & flag) !== 0;@@ -22,80 +20,77 @@ function hasPermissionFlag(interface DocumentPermissionsAPIBridgeProps {isEncrypted?: boolean;isOwnerUnlocked?: boolean;+ honorOwnerPasswords?: boolean;permissions?: number;}export function DocumentPermissionsAPIBridge({isEncrypted = false,isOwnerUnlocked = false,+ honorOwnerPasswords = true,permissions = PdfPermissionFlag.AllowAll,}: DocumentPermissionsAPIBridgeProps) {const { registerBridge } = useViewer();const documentReady = useDocumentReady();+ const effectivePermissions =+ !isEncrypted || isOwnerUnlocked || !honorOwnerPasswords+ ? PdfPermissionFlag.AllowAll+ : permissions;+const state = useMemo<DocumentPermissionsState>(() => ({isEncrypted,isOwnerUnlocked,permissions,- canPrint: canPrintPdf({- encrypted: isEncrypted,- ownerAuthenticated: isOwnerUnlocked,- permissions,- }),+ canPrint: hasPermissionFlag(+ effectivePermissions,+ PdfPermissionFlag.Print,+ ),canModifyContents: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.ModifyContents,- isEncrypted,),canCopyContents: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.CopyContents,- isEncrypted,),canModifyAnnotations: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.ModifyAnnotations,- isEncrypted,),canFillForms: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.FillForms,- isEncrypted,),canExtractForAccessibility: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.ExtractForAccessibility,- isEncrypted,),canAssembleDocument: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.AssembleDocument,- isEncrypted,),canPrintHighQuality: hasPermissionFlag(- permissions,+ effectivePermissions,PdfPermissionFlag.PrintHighQuality,- isEncrypted,),}),- [isEncrypted, isOwnerUnlocked, permissions],+ [isEncrypted, isOwnerUnlocked, permissions, effectivePermissions],);const api = useMemo<DocumentPermissionsAPIWrapper>(() => ({hasPermission: (flag: PdfPermissionFlag) =>- hasPermissionFlag(permissions, flag, isEncrypted),+ hasPermissionFlag(effectivePermissions, flag),hasAllPermissions: (flags: PdfPermissionFlag[]) =>- flags.every((flag) =>- hasPermissionFlag(permissions, flag, isEncrypted),- ),+ flags.every((flag) => hasPermissionFlag(effectivePermissions, flag)),getEffectivePermission: (flag: PdfPermissionFlag) => {if (isOwnerUnlocked) return true;- return hasPermissionFlag(permissions, flag, isEncrypted);+ return hasPermissionFlag(effectivePermissions, flag);},}),- [permissions, isOwnerUnlocked, isEncrypted],+ [effectivePermissions, isOwnerUnlocked],);useEffect(() => {diff --git a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsxindex 67cb97d6be..e8b8cc022e 100644--- a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx+++ b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx@@ -6,6 +6,7 @@ interface PendingDocument {name: string;fileKey: string;password?: string;+ honorOwnerPasswords?: boolean;}interface DocumentSwapBridgeProps {@@ -45,6 +46,9 @@ export function DocumentSwapBridge({buffer: pending.buffer,name: pending.name,password: pending.password,+ permissions: {+ enforceDocumentPermissions: pending.honorOwnerPasswords !== false,+ },autoActivate: false,}).toPromise(),diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex 9663f81255..d4fa402e47 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -26,6 +26,7 @@ import type {} from "@app/components/viewer/DocumentRestoreBridge";import { useViewer } from "@app/contexts/ViewerContext";import { LocalEmbedPDF } from "@app/components/viewer/LocalEmbedPDF";+import { PdfProtectionStatus } from "@app/components/viewer/PdfProtectionStatus";import { usePdfAccess } from "@app/hooks/usePdfAccess";import { canPrintPdf } from "@app/services/pdfPermissions";import { PdfPreviewUnlockGate } from "@app/components/viewer/PdfPreviewUnlockGate";@@ -660,6 +661,26 @@ const EmbedPdfViewerContent = ({// consume/undo paths below pass it back as a FileId.const currentFileStableId =currentFile && isStirlingFile(currentFile) ? currentFile.fileId : null;+ const previousActiveFileIdsRef = useRef(activeFileIds);+ // Follow removals, but do not overwrite a save's new id before its bytes enter FileContext.+ useEffect(() => {+ const previousActiveFileIds = previousActiveFileIdsRef.current;+ previousActiveFileIdsRef.current = activeFileIds;+ if (+ !previewFile &&+ currentFileStableId &&+ currentFileStableId !== activeFileId &&+ (!activeFileId || previousActiveFileIds.some((id) => id === activeFileId))+ ) {+ setActiveFileId(currentFileStableId);+ }+ }, [+ previewFile,+ currentFileStableId,+ activeFileId,+ activeFileIds,+ setActiveFileId,+ ]);const fileWithUrl = useFileWithUrl(currentFile, currentFileId);// Lineage root of the open document: saves and tool outputs add a child record,@@ -957,7 +978,7 @@ const EmbedPdfViewerContent = ({return;}- const updateHasChanges = () => {+ const updateHasChanges = (historyChanged: boolean) => {const canUndo = historyApi.canUndo?.() ?? false;if (!canUndo && savedHistoryRevisionRef.current === 0) {historyRevisionRef.current = 0;@@ -969,6 +990,7 @@ const EmbedPdfViewerContent = ({}return;}+ if (!historyChanged) return;historyRevisionRef.current += 1;if (suppressHistoryDirtyRef.current) return;// A revision equal to the save point means the annotations match the@@ -989,7 +1011,12 @@ const EmbedPdfViewerContent = ({}};- const unsubscribe = historyApi.subscribe(updateHasChanges);+ // Reconnecting after a permissions check emits the existing history, not a new edit.+ let subscribing = true;+ const unsubscribe = historyApi.subscribe(() => {+ updateHasChanges(!subscribing);+ });+ subscribing = false;return () => {if (typeof unsubscribe === "function") {unsubscribe();@@ -1869,6 +1896,9 @@ const EmbedPdfViewerContent = ({</Center>) : (<>+ {currentFile && isStirlingFile(currentFile) && (+ <PdfProtectionStatus key={currentFile.fileId} file={currentFile} />+ )}{/* EmbedPDF Viewer */}<Boxref={pdfContainerRef}@@ -1907,12 +1937,16 @@ const EmbedPdfViewerContent = ({: undefined}enableAnnotations={- shouldEnableAnnotations && !pdfAccess?.encrypted+ shouldEnableAnnotations && !!pdfAccess && !pdfAccess.encrypted}isSignMode={selectedTool === "sign"}showBakedAnnotations={isAnnotationsVisible}- enableRedaction={shouldEnableRedaction && !pdfAccess?.encrypted}- enableFormFill={shouldEnableFormFill && !pdfAccess?.encrypted}+ enableRedaction={+ shouldEnableRedaction && !!pdfAccess && !pdfAccess.encrypted+ }+ enableFormFill={+ shouldEnableFormFill && !!pdfAccess && !pdfAccess.encrypted+ }formEditingActive={isFormFillToolActive}isManualRedactionMode={isManualRedactMode}signatureApiRef={signatureApiRef}diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex 68384cd58b..b8037f7cdd 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -105,6 +105,11 @@ import { AnnotationMenuEvents } from "@app/components/viewer/AnnotationMenuEventimport { 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 { PdfPermissionFlag } from "@embedpdf/models";import { usePdfAccess } from "@app/hooks/usePdfAccess";import { canPrintPdf } from "@app/services/pdfPermissions";import {@@ -416,6 +421,7 @@ interface PageLayerOptions {formEditingActive: boolean;enableAnnotations: boolean;annotationsReadOnly: boolean;+ canCopy: boolean;enableRedaction: boolean;showBakedAnnotations: boolean;onAnnotationMenuAnchor: (anchor: AnnotationMenuAnchor | null) => void;@@ -453,7 +459,8 @@ function PageTextSelection({documentId,pageIndex,readOnly,-}: PageLayerProps & { readOnly: boolean }) {+ canCopy,+}: PageLayerProps & { readOnly: boolean; canCopy: boolean }) {return (<><div@@ -469,7 +476,11 @@ function PageTextSelection({pageIndex={pageIndex}background="var(--pdf-selection-bg)"selectionMenu={(props) => (- <TextSelectionMenu {...props} readOnly={readOnly} />+ <TextSelectionMenu+ {...props}+ readOnly={readOnly}+ canCopy={canCopy}+ />)}/></div>@@ -610,6 +621,7 @@ function PageLayers({formEditingActive,enableAnnotations,annotationsReadOnly,+ canCopy,enableRedaction,showBakedAnnotations,onAnnotationMenuAnchor,@@ -629,6 +641,7 @@ function PageLayers({documentId={documentId}pageIndex={pageIndex}readOnly={annotationsReadOnly}+ canCopy={canCopy}/><FormFillLayersenabled={enableFormFill}@@ -902,7 +915,7 @@ export function LocalEmbedPDF({const { t } = useTranslation();const { config } = useAppConfig();const pdfAccess = usePdfAccess(file ?? fileId);- const annotationsReadOnly = Boolean(pdfAccess?.encrypted);+ const annotationsReadOnly = !pdfAccess || pdfAccess.encrypted;const showAnnotations = enableAnnotations || annotationsReadOnly;const [pdfUrl, setPdfUrl] = useState<string | null>(() => url ?? null);const [, setAnnotations] = useState<@@ -1039,15 +1052,18 @@ export function LocalEmbedPDF({name: string;fileKey: string;password?: string;+ honorOwnerPasswords?: boolean;} | null>(null);const [pendingDocument, setPendingDocument] = useState<{buffer: ArrayBuffer;name: string;fileKey: string;password?: string;+ honorOwnerPasswords?: boolean;} | null>(null);const initialDocumentOpenedRef = useRef(false);const openedContentKeyRef = useRef<string | null>(null);+ const openedPermissionOverrideRef = useRef(false);// Anchors survive deselection per annotation id, so a delete that happens// while no menu is open (keyboard, sidebar) still has somewhere to appear.const annotationAnchorsByIdRef = useRef<Map<string, AnnotationMenuAnchor>>(@@ -1086,9 +1102,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(() => {- if (fileStableKey && shouldSkipBytes?.(fileStableKey)) {+ if (+ fileStableKey &&+ openedPermissionOverrideRef.current ===+ hasPdfPermissionOverride(pdfAccess) &&+ (openedContentKeyRef.current === fileStableKey ||+ shouldSkipBytes?.(fileStableKey))+ ) {// 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;return;}let cancelled = false;@@ -1100,7 +1123,14 @@ export function LocalEmbedPDF({) => {// A repeat run for the same content (a rename, a FileContext churn) must// not reopen the document.- if (!contentKey || openedContentKeyRef.current === contentKey) return;+ if (+ !contentKey ||+ (openedContentKeyRef.current === contentKey &&+ openedPermissionOverrideRef.current ===+ hasPdfPermissionOverride(pdfAccess))+ )+ return;+ openedPermissionOverrideRef.current = hasPdfPermissionOverride(pdfAccess);openedContentKeyRef.current = contentKey;if (!initialDocumentOpenedRef.current) {initialDocumentOpenedRef.current = true;@@ -1109,6 +1139,7 @@ export function LocalEmbedPDF({name,fileKey: contentKey,password: pdfAccess?.password,+ honorOwnerPasswords: pdfAccess?.honorOwnerPasswords,});return;}@@ -1117,6 +1148,7 @@ export function LocalEmbedPDF({name,fileKey: contentKey,password: pdfAccess?.password,+ honorOwnerPasswords: pdfAccess?.honorOwnerPasswords,});};const fail = (source: string) => (err: unknown) => {@@ -1171,6 +1203,8 @@ export function LocalEmbedPDF({url,shouldSkipBytes,exportFileName,+ pdfAccess?.ownerAuthenticated,+ pdfAccess?.honorOwnerPasswords,onDocumentLoadFailed,]);@@ -1258,6 +1292,10 @@ export function LocalEmbedPDF({buffer: initialSource.buffer,name: initialSource.name,password: initialSource.password,+ permissions: {+ enforceDocumentPermissions:+ initialSource.honorOwnerPasswords !== false,+ },},]: [{ url: initialSource.url, name: initialSource.name }];@@ -1551,6 +1589,7 @@ export function LocalEmbedPDF({formEditingActive,enableAnnotations: showAnnotations,annotationsReadOnly,+ canCopy: pdfAllows(pdfAccess, PdfPermissionFlag.CopyContents),enableRedaction,showBakedAnnotations,onAnnotationMenuAnchor: handleAnnotationMenuAnchor,@@ -1610,7 +1649,9 @@ export function LocalEmbedPDF({/><ZoomAPIBridge /><ScrollAPIBridge />- <SelectionAPIBridge />+ <SelectionAPIBridge+ canCopy={pdfAllows(pdfAccess, PdfPermissionFlag.CopyContents)}+ /><FormCreationInteractionLock /><PanAPIBridge /><SpreadAPIBridge />@@ -1651,9 +1692,10 @@ export function LocalEmbedPDF({canPrint={canPrintPdf(pdfAccess)}/><DocumentPermissionsAPIBridge- isEncrypted={pdfAccess?.encrypted}+ isEncrypted={pdfAccess?.encrypted ?? true}isOwnerUnlocked={pdfAccess?.ownerAuthenticated}- permissions={pdfAccess?.permissions}+ honorOwnerPasswords={pdfAccess?.honorOwnerPasswords}+ permissions={pdfAccess?.permissions ?? 0}/><DocumentReadyWrapperfallback={diff --git a/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx b/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsxnew file mode 100644index 0000000000..6dbfd3d1e9--- /dev/null+++ b/frontend/editor/src/core/components/viewer/PdfProtectionStatus.tsx@@ -0,0 +1,285 @@+import { useState } from "react";+import { Group, Modal, Stack, Text } from "@mantine/core";+import { Tooltip } from "@app/components/shared/Tooltip";+import { ProtectedPdfFileCard } from "@app/components/shared/ProtectedPdfFileCard";+import { PdfPermissionFlag } from "@embedpdf/models";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Icon } from "@app/ui/Icon";+import { useFileActions } from "@app/contexts/FileContext";+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";++/** Persistent document settings; authentication is requested only when an action needs it. */+export function PdfProtectionStatus({ file }: { file: StirlingFile }) {+ const { t } = useTranslation();+ const access = usePdfAccess(file);+ const { actions: fileActions } = useFileActions();+ const { handleToolSelect } = useToolWorkflowActions();+ const [opened, setOpened] = useState(false);+ const [confirmCopy, setConfirmCopy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ if (!access?.encrypted) return null;+ const close = () => {+ setOpened(false);+ setConfirmCopy(false);+ setError(null);+ };+ const permissions = [+ [t("encryptedPdfUnlock.printing", "Printing"), PdfPermissionFlag.Print],+ [+ t("encryptedPdfUnlock.copying", "Copying content"),+ PdfPermissionFlag.CopyContents,+ ],+ [+ t("encryptedPdfUnlock.editing", "Editing"),+ PdfPermissionFlag.ModifyContents,+ ],+ [+ t("encryptedPdfUnlock.annotations", "Annotations"),+ PdfPermissionFlag.ModifyAnnotations,+ ],+ ] as const;+ const createCopy = async () => {+ setOpened(false);+ if (+ !(await fileActions.requestPdfOwnerAccess(+ file.fileId,+ t("encryptedPdfUnlock.removeProtection", "Create an unprotected copy"),+ ))+ ) {+ setOpened(true);+ return;+ }+ setBusy(true);+ try {+ await fileActions.createUnprotectedCopy(file.fileId);+ close();+ } catch {+ setError(+ t(+ "encryptedPdfUnlock.copyFailed",+ "Unable to create the copy. Your PDF is unchanged.",+ ),+ );+ setOpened(true);+ } finally {+ setBusy(false);+ }+ };+ return (+ <>+ <Group justify="space-between" gap="xs" px="sm" py={4}>+ <Group gap={6} role="status">+ <Icon name="lock" size={14} />+ <Text size="xs">+ {access.ownerAuthenticated && access.hasOwnerPassword !== false+ ? t(+ "encryptedPdfUnlock.permissionsUnlocked",+ "Permissions unlocked for this session",+ )+ : t("encryptedPdfUnlock.protectedPdf", "Protected PDF")}+ </Text>+ </Group>+ <Button+ size="sm"+ variant="quiet"+ accent="neutral"+ onClick={() => setOpened(true)}+ >+ {t("encryptedPdfUnlock.manageProtection", "Manage protection")}+ </Button>+ </Group>+ <Modal+ opened={opened}+ onClose={close}+ title={t("encryptedPdfUnlock.manageProtection", "Manage protection")}+ centered+ size="sm"+ padding="md"+ radius="md"+ styles={{ body: { paddingTop: "var(--mantine-spacing-md)" } }}+ closeButtonProps={{ "aria-label": t("close", "Close") }}+ zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}+ >+ <Stack gap="md">+ <ProtectedPdfFileCard fileName={file.name} />+ {confirmCopy ? (+ <>+ <Text size="sm">+ {t(+ "encryptedPdfUnlock.unprotectedCopyConsequence",+ "The copy will have no passwords or restrictions. The original stays protected.",+ )}+ </Text>+ {error && (+ <Text role="alert" c="var(--c-danger)" size="sm">+ {error}+ </Text>+ )}+ <Group justify="flex-end">+ <Button+ variant="secondary"+ onClick={() => setConfirmCopy(false)}+ >+ {t("back", "Back")}+ </Button>+ <Button onClick={() => void createCopy()} loading={busy}>+ {t(+ "encryptedPdfUnlock.removeProtection",+ "Create an unprotected copy",+ )}+ </Button>+ </Group>+ </>+ ) : (+ <>+ <Group justify="space-between">+ <Text size="sm">+ {t("encryptedPdfUnlock.openingPassword", "Password to open")}+ </Text>+ <Text size="sm">+ {access.requiresOpeningPassword === false+ ? t("encryptedPdfUnlock.notRequired", "Not required")+ : t("encryptedPdfUnlock.requiredStatus", "Required")}+ </Text>+ </Group>+ {permissions.map(([label, flag]) => {+ const allowed = (access.permissions & flag) !== 0;+ const lowResolutionOnly =+ allowed &&+ flag === PdfPermissionFlag.Print &&+ access.encryptionRevision !== 2 &&+ !(access.permissions & PdfPermissionFlag.PrintHighQuality);+ return (+ <Group key={label} justify="space-between">+ <Text size="sm">{label}</Text>+ <Group gap={6}>+ {hasPdfPermissionOverride(access) &&+ (!allowed || lowResolutionOnly) && (+ <Tooltip+ content={+ access.honorOwnerPasswords === false &&+ !access.ownerAuthenticated+ ? t(+ "encryptedPdfUnlock.ignoredByServer",+ "Permissions are ignored by this server's settings. The PDF's protection is unchanged.",+ )+ : t(+ "encryptedPdfUnlock.unlockedForSession",+ "Unlocked for this session using your permissions password.",+ )+ }+ position="top"+ maxWidth={240}+ arrow+ containerStyle={{+ zIndex: Z_INDEX_OVER_FULLSCREEN_SURFACE + 1,+ }}+ >+ <ActionIcon+ size="sm"+ variant="quiet"+ accent="neutral"+ aria-label={+ access.honorOwnerPasswords === false &&+ !access.ownerAuthenticated+ ? t(+ "encryptedPdfUnlock.actionIgnored",+ "{{action}} restriction ignored",+ { action: label },+ )+ : t(+ "encryptedPdfUnlock.actionUnlocked",+ "{{action}} unlocked for this session",+ { action: label },+ )+ }+ >+ <Icon name="lock-open" size={14} />+ </ActionIcon>+ </Tooltip>+ )}+ <Text size="sm">+ {lowResolutionOnly+ ? t(+ "encryptedPdfUnlock.lowResolutionOnly",+ "Low resolution only",+ )+ : allowed+ ? t("encryptedPdfUnlock.allowed", "Allowed")+ : t("encryptedPdfUnlock.restricted", "Restricted")}+ </Text>+ </Group>+ </Group>+ );+ })}+ {access.signed && (+ <Text size="sm">+ {t(+ "encryptedPdfUnlock.signedReadOnly",+ "This signed PDF can be viewed, but cannot be edited here.",+ )}+ </Text>+ )}+ {!hasPdfPermissionOverride(access) && (+ <Button+ onClick={async () => {+ close();+ await fileActions.requestPdfOwnerAccess(+ file.fileId,+ t(+ "encryptedPdfUnlock.restrictedActions",+ "restricted actions",+ ),+ );+ }}+ >+ {t(+ "encryptedPdfUnlock.verifyPermissions",+ "Verify permissions for this session",+ )}+ </Button>+ )}+ <Button+ variant="secondary"+ disabled={access.signed}+ onClick={() => {+ close();+ handleToolSelect("changePermissions");+ }}+ >+ {t("changePermissions.submit", "Change Permissions")}+ </Button>+ <Button+ variant="secondary"+ disabled={access.signed}+ onClick={() => {+ close();+ handleToolSelect("removePassword");+ }}+ >+ {t("removePassword.title", "Remove Password")}+ </Button>+ <Button+ variant="quiet"+ disabled={access.signed}+ onClick={() => setConfirmCopy(true)}+ >+ {t(+ "encryptedPdfUnlock.removeProtection",+ "Create an unprotected copy",+ )}+ </Button>+ </>+ )}+ </Stack>+ </Modal>+ </>+ );+}diff --git a/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx b/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsxindex 15f2740b90..f207d2ae29 100644--- a/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx+++ b/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx@@ -48,6 +48,26 @@ it.each([encrypted: true,ownerAuthenticated: false,permissions: PdfPermissionFlag.Print,+ allowed: false,+ },+ {+ encrypted: true,+ ownerAuthenticated: false,+ permissions: PdfPermissionFlag.Print,+ encryptionRevision: 2,+ allowed: true,+ },+ {+ encrypted: true,+ ownerAuthenticated: false,+ permissions: PdfPermissionFlag.Print | PdfPermissionFlag.PrintHighQuality,+ allowed: true,+ },+ {+ encrypted: true,+ ownerAuthenticated: false,+ permissions: 0,+ honorOwnerPasswords: false,allowed: true,},{ encrypted: true, ownerAuthenticated: true, permissions: 0, allowed: true },@@ -96,6 +116,6 @@ it.each([false, true])(expect(bridge.api.getEffectivePermission(PdfPermissionFlag.Print)).toBe(owner,);- expect(bridge.api.hasPermission(PdfPermissionFlag.Print)).toBe(false);+ expect(bridge.api.hasPermission(PdfPermissionFlag.Print)).toBe(owner);},);diff --git a/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx b/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsxindex 943f94b47b..d70e97d0c3 100644--- a/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx@@ -13,7 +13,7 @@ export interface PrintAPIBridgeProps {/*** Connects the PDF print plugin to the shared ViewerContext.*/-export function PrintAPIBridge({ canPrint = true }: PrintAPIBridgeProps) {+export function PrintAPIBridge({ canPrint = false }: PrintAPIBridgeProps) {const { provides: print } = usePrintCapability();const { registerBridge } = useViewer();const documentReady = useDocumentReady();diff --git a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.test.tsx b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.test.tsxnew file mode 100644index 0000000000..73f1a7916b--- /dev/null+++ b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.test.tsx@@ -0,0 +1,142 @@+import { act, cleanup, render } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SelectionAPIBridge } from "@app/components/viewer/SelectionAPIBridge";+import type {+ BridgeRef,+ SelectionAPIWrapper,+ SelectionState,+} from "@app/contexts/viewer/viewerBridges";++const mock = vi.hoisted(() => ({+ activeDocumentId: "first",+ register:+ vi.fn<+ (+ kind: string,+ bridge: BridgeRef<SelectionState, SelectionAPIWrapper> | null,+ ) => void+ >(),+ onSelectionChange:+ vi.fn<(listener: (event: { selection: boolean }) => void) => () => void>(),+ getSelectedText: vi.fn<+ (documentId?: string) => {+ wait: (resolve: (texts: string[]) => void) => void;+ }+ >(),+ copyText: vi.fn(async (text: string) => text.length > 0),+}));++vi.mock("@embedpdf/plugin-selection/react", () => {+ const selection = {+ onSelectionChange: mock.onSelectionChange,+ getSelectedText: mock.getSelectedText,+ };+ const plugin = {};+ return {+ useSelectionCapability: () => ({ provides: selection }),+ useSelectionPlugin: () => ({ plugin }),+ glyphAt: vi.fn(),+ };+});+vi.mock("@embedpdf/core/react", () => ({+ useDocumentState: () => ({ scale: 1 }),+}));+vi.mock("@app/contexts/ViewerContext", () => ({+ useViewer: () => ({ registerBridge: mock.register }),+}));+vi.mock("@app/components/viewer/hooks/useDocumentReady", () => ({+ useDocumentReady: () => true,+}));+vi.mock("@app/components/viewer/useActiveDocumentId", () => ({+ useActiveDocumentId: () => mock.activeDocumentId,+}));+vi.mock("@app/utils/copyText", () => ({ copyText: mock.copyText }));++function selectText() {+ let complete!: (texts: string[]) => void;+ mock.getSelectedText.mockReturnValueOnce({+ wait: (resolve) => {+ complete = resolve;+ },+ });+ act(() => {+ mock.onSelectionChange.mock.calls.at(-1);+ });+ return complete;+}++function currentBridge() {+ return mock.register.mock.calls.at(-1)![1]!;+}++function keyboardCopy() {+ const setData = vi.fn();+ const event = new Event("copy", { bubbles: true, cancelable: true });+ Object.defineProperty(event, "clipboardData", { value: { setData } });+ document.dispatchEvent(event);+ return { setData, prevented: event.defaultPrevented };+}++describe("selection after switching documents", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.activeDocumentId = "first";+ mock.onSelectionChange.mockImplementation(() => () => {});+ });+ afterEach(cleanup);++ it("clears the previous document's text for menu and keyboard copying", async () => {+ const { rerender } = render(<SelectionAPIBridge canCopy />);+ selectText()(["First document"]);+ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(true);+ expect(mock.copyText).toHaveBeenLastCalledWith("First document");+ expect(keyboardCopy().setData).toHaveBeenCalledWith(+ "text/plain",+ "First document",+ );++ mock.activeDocumentId = "second";+ rerender(<SelectionAPIBridge canCopy />);++ expect(currentBridge().state.hasSelection).toBe(false);+ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(false);+ expect(keyboardCopy().setData).not.toHaveBeenCalled();++ selectText()(["Second document"]);+ expect(mock.getSelectedText).toHaveBeenLastCalledWith("second");+ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(true);+ expect(mock.copyText).toHaveBeenLastCalledWith("Second document");+ expect(keyboardCopy().setData).toHaveBeenCalledWith(+ "text/plain",+ "Second document",+ );+ });++ it("ignores a text lookup that finishes after leaving its document", async () => {+ const { rerender } = render(<SelectionAPIBridge canCopy />);+ const completePreviousLookup = selectText();++ mock.activeDocumentId = "second";+ rerender(<SelectionAPIBridge canCopy />);+ completePreviousLookup(["Late text from the first document"]);++ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(false);+ expect(keyboardCopy().setData).not.toHaveBeenCalled();+ });++ it("keeps the same document's selection while enforcing changed copy permission", async () => {+ const { rerender } = render(<SelectionAPIBridge canCopy />);+ selectText()(["Current document"]);++ rerender(<SelectionAPIBridge canCopy={false} />);+ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(false);+ expect(mock.copyText).not.toHaveBeenCalled();+ const denied = keyboardCopy();+ expect(denied.setData).not.toHaveBeenCalled();+ expect(denied.prevented).toBe(true);++ rerender(<SelectionAPIBridge canCopy />);+ await expect(currentBridge().api.copyToClipboard()).resolves.toBe(true);+ expect(mock.copyText).toHaveBeenLastCalledWith("Current document");+ });+});diff --git a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsxindex c3a5da5602..086a97702a 100644--- a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx@@ -8,11 +8,20 @@ import { useDocumentState } from "@embedpdf/core/react";import { useViewer } from "@app/contexts/ViewerContext";import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";+import { copyText } from "@app/utils/copyText";++function isEditableTarget(target: EventTarget | null): boolean {+ return (+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ (target instanceof HTMLElement && target.isContentEditable)+ );+}/*** Connects the PDF selection plugin to the shared ViewerContext.*/-export function SelectionAPIBridge() {+export function SelectionAPIBridge({ canCopy = false }: { canCopy?: boolean }) {const { provides: selection } = useSelectionCapability();const { plugin: selectionPlugin } = useSelectionPlugin();const { registerBridge } = useViewer();@@ -25,6 +34,15 @@ export function SelectionAPIBridge() {const hasSelectionRef = useRef(false);const selectedTextRef = useRef("");+ const textLookupRef = useRef(0);++ useEffect(() => {+ return () => {+ hasSelectionRef.current = false;+ selectedTextRef.current = "";+ textLookupRef.current += 1;+ };+ }, [activeDocumentId]);useEffect(() => {if (!selection || !documentReady) return;@@ -130,7 +148,7 @@ export function SelectionAPIBridge() {const buildApi = () => ({copyToClipboard: () =>- selection.copyToClipboard(activeDocumentId ?? undefined),+ canCopy ? copyText(selectedTextRef.current) : Promise.resolve(false),getFormattedSelection: () =>selection.getFormattedSelection(activeDocumentId ?? undefined),selectAll: async (totalPages: number) => {@@ -159,6 +177,10 @@ export function SelectionAPIBridge() {api: buildApi(),});+ // Cleared before the async lookup so a copy in the gap fails rather than+ // writing the previous selection's text.+ selectedTextRef.current = "";+ const lookup = ++textLookupRef.current;if (hasText) {try {const result = selection.getSelectedText(@@ -166,7 +188,8 @@ export function SelectionAPIBridge() {);result?.wait?.((texts: string[]) => {- selectedTextRef.current = texts.join("\n");+ if (lookup === textLookupRef.current)+ selectedTextRef.current = texts.join("\n");},() => {/* ignore errors */@@ -175,38 +198,20 @@ export function SelectionAPIBridge() {} catch {// Engine access failed}- } else {- selectedTextRef.current = "";}});- // Fallback: subscribe to the plugin's copy event for navigator.clipboard writes- const unsubCopy = selection.onCopyToClipboard(- ({ text }: { text: string }) => {- if (text) {- navigator.clipboard.writeText(text).catch(() => {- /* ignore */- });- }- },- );-+ // Ctrl+C must reach this event uncancelled: writing clipboardData here+ // works over plain HTTP, where navigator.clipboard is absent. Copies from+ // editable fields, including copyText's fallback textarea, keep their own text.const handleCopy = (event: ClipboardEvent) => {+ if (isEditableTarget(event.target)) return;if (!hasSelectionRef.current || !selectedTextRef.current) return;- event.clipboardData?.setData("text/plain", selectedTextRef.current);+ if (canCopy)+ event.clipboardData?.setData("text/plain", selectedTextRef.current);event.preventDefault();};- const handleKeyDown = (event: KeyboardEvent) => {- if (- (event.ctrlKey || event.metaKey) &&- event.key === "c" &&- hasSelectionRef.current- ) {- selection.copyToClipboard(activeDocumentId ?? undefined);- }- };-// Right-click anywhere inside a PDF page: suppress the browser's "Copy// image" menu, and if nothing is currently selected, auto-select the// word under the cursor so the floating Copy menu appears in place.@@ -230,14 +235,11 @@ export function SelectionAPIBridge() {};document.addEventListener("copy", handleCopy);- document.addEventListener("keydown", handleKeyDown);document.addEventListener("contextmenu", handleContextMenu);return () => {unsubChange?.();- unsubCopy?.();document.removeEventListener("copy", handleCopy);- document.removeEventListener("keydown", handleKeyDown);document.removeEventListener("contextmenu", handleContextMenu);registerBridge("selection", null);};@@ -247,6 +249,7 @@ export function SelectionAPIBridge() {activeDocumentId,documentReady,registerBridge,+ canCopy,]);return null;diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsxindex f341fb563f..eec118c6de 100644--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx@@ -1,5 +1,5 @@import { describe, expect, test, vi, beforeEach } from "vitest";-import { render, screen, fireEvent } from "@testing-library/react";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";import { MantineProvider } from "@mantine/core";import { TextSelectionMenu } from "@app/components/viewer/TextSelectionMenu";import { PdfAnnotationSubtype } from "@embedpdf/models";@@ -29,6 +29,13 @@ vi.mock("@embedpdf/plugin-selection/react", () => ({}),}));+const mockViewerCopy = vi.fn();+vi.mock("@app/contexts/ViewerContext", () => ({+ useViewer: () => ({+ selectionActions: { copyToClipboard: mockViewerCopy },+ }),+}));+const mockCreateAnnotation = vi.fn();vi.mock("@embedpdf/plugin-annotation/react", () => ({useAnnotation: () => ({@@ -98,6 +105,7 @@ const TestWrapper = ({ children }: { children: React.ReactNode }) => (describe("TextSelectionMenu", () => {const defaultProps = {+ canCopy: true,rect: { origin: { x: 100, y: 100 }, size: { width: 80, height: 20 } },menuWrapperProps: {style: {},@@ -132,6 +140,54 @@ describe("TextSelectionMenu", () => {]);});+ test("does not copy when document permissions deny extraction", () => {+ render(+ <TestWrapper>+ <TextSelectionMenu {...defaultProps} canCopy={false} />+ </TestWrapper>,+ );+ const copy = screen.getByRole("button", { name: "Copy" });+ expect(copy).toBeDisabled();+ fireEvent.click(copy);+ expect(mockViewerCopy).not.toHaveBeenCalled();+ expect(mockCopyToClipboard).not.toHaveBeenCalled();+ });++ test("confirms a copy only after the clipboard write succeeds", async () => {+ mockViewerCopy.mockResolvedValue(true);+ render(+ <TestWrapper>+ <TextSelectionMenu {...defaultProps} />+ </TestWrapper>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Copy" }));+ await waitFor(() =>+ expect(mockAlert).toHaveBeenCalledWith(+ expect.objectContaining({+ alertType: "neutral",+ title: "Copied to clipboard",+ }),+ ),+ );+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");+ });++ test("reports a failed clipboard write and keeps the selection", async () => {+ mockViewerCopy.mockResolvedValue(false);+ render(+ <TestWrapper>+ <TextSelectionMenu {...defaultProps} />+ </TestWrapper>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Copy" }));+ await waitFor(() =>+ expect(mockAlert).toHaveBeenCalledWith(+ expect.objectContaining({ alertType: "error" }),+ ),+ );+ expect(mockClearSelection).not.toHaveBeenCalled();+ });+test("renders all 7 action buttons when selected", () => {render(<TestWrapper>@@ -170,27 +226,6 @@ describe("TextSelectionMenu", () => {).not.toBeInTheDocument();});- test("calls copyToClipboard, clears selection, and triggers toast popup when Copy button is clicked", () => {- render(- <TestWrapper>- <TextSelectionMenu {...defaultProps} />- </TestWrapper>,- );-- const copyBtn = screen.getByRole("button", { name: "Copy" });- fireEvent.click(copyBtn);-- expect(mockCopyToClipboard).toHaveBeenCalledWith("doc-1");- expect(mockClearSelection).toHaveBeenCalledWith("doc-1");- expect(mockAlert).toHaveBeenCalledWith(- expect.objectContaining({- alertType: "neutral",- title: "Copied to clipboard",- durationMs: 2000,- }),- );- });-test("creates HIGHLIGHT annotation, clears selection and opens Annotate UI when Highlight button is clicked", () => {render(<TestWrapper>diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsxindex d6f989ef2e..e5761a2478 100644--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx@@ -18,6 +18,7 @@ import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId"import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";import { useRedaction } from "@app/contexts/RedactionContext";import { useNavigationActions } from "@app/contexts/NavigationContext";+import { useViewer } from "@app/contexts/ViewerContext";import {defaultParameters,RedactParameters,@@ -30,6 +31,7 @@ import "@app/components/viewer/TextSelectionMenu.css";export type TextSelectionMenuProps = SelectionSelectionMenuProps & {documentId?: string;readOnly?: boolean;+ canCopy?: boolean;};export function TextSelectionMenu(props: TextSelectionMenuProps) {@@ -49,6 +51,7 @@ function TextSelectionMenuInner({placement,documentId,readOnly = false,+ canCopy = false,}: TextSelectionMenuProps & { documentId: string }) {const { t } = useTranslation();const { provides: selection } = useSelectionCapability();@@ -64,6 +67,7 @@ function TextSelectionMenuInner({manualRedactColor,} = useRedaction();const { actions: navActions } = useNavigationActions();+ const { selectionActions } = useViewer();const wrapperRef = useRef<HTMLDivElement>(null);const [position, setPosition] = useState<{@@ -119,17 +123,21 @@ function TextSelectionMenuInner({};}, [selected, showAbove]);+ // Copies through the selection bridge rather than the plugin: the plugin+ // writes only via navigator.clipboard, which does not exist over plain HTTP.const handleCopy = useCallback(() => {- if (documentId) {- selection?.copyToClipboard(documentId);- selection?.clear(documentId);+ if (!documentId || !canCopy) return;+ void selectionActions.copyToClipboard().then((copied) => {+ if (copied) selection?.clear(documentId);alert({- alertType: "neutral",- title: t("common.copied", "Copied to clipboard"),+ alertType: copied ? "neutral" : "error",+ title: copied+ ? t("common.copied", "Copied to clipboard")+ : t("common.copyFailed", "Copy failed"),durationMs: 2000,});- }- }, [selection, documentId, t]);+ });+ }, [selectionActions, selection, documentId, t, canCopy]);const openAnnotateUi = useCallback(() => {handleToolSelectForced?.("annotate");@@ -323,6 +331,7 @@ function TextSelectionMenuInner({type="button"className="embedpdf-text-selection-btn"onClick={handleCopy}+ disabled={!canCopy}aria-label={t("viewer.copyText", "Copy")}><Icon name="copy" size={20} />diff --git a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx b/frontend/editor/src/core/components/viewer/documentLoad.test.tsxindex 0082781ed9..453e79ddd8 100644--- a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx+++ b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx@@ -46,9 +46,16 @@ describe("form save document completion", () => {mocks.active = { status: "loading", error: null };});- it.each([undefined, "session-password"])(- "waits for the saved document's loaded task and ignores unrelated document events (password: %s)",- async (password) => {+ it.each(+ [undefined, "session-password"].flatMap((password) =>+ [undefined, true, false].map((honorOwnerPasswords) => ({+ password,+ honorOwnerPasswords,+ })),+ ),+ )(+ "waits for the saved document's loaded task and ignores unrelated document events (password: $password, honorOwnerPasswords: $honorOwnerPasswords)",+ async ({ password, honorOwnerPasswords }) => {const load = deferred<void>();mocks.open.mockReturnValue({toPromise: async () => ({@@ -62,7 +69,11 @@ describe("form save document completion", () => {void saved.then(completed);result.current.documentReady("A");result.current.documentFailed("A", new Error("unrelated"));- const replacement = { ...pending("B-saved"), password };+ const replacement = {+ ...pending("B-saved"),+ password,+ honorOwnerPasswords,+ };render(<DocumentSwapBridgepending={replacement}@@ -75,6 +86,9 @@ describe("form save document completion", () => {buffer: replacement.buffer,name: replacement.name,password,+ permissions: {+ enforceDocumentPermissions: honorOwnerPasswords !== false,+ },autoActivate: false,});expect(completed).not.toHaveBeenCalled();diff --git a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsxindex 6b72557387..fd4f90efbf 100644--- a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx+++ b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx@@ -14,7 +14,12 @@ import {useFileSelectors,} from "@app/contexts/FileContext";import apiClient from "@app/services/apiClient";-import { getPdfAccess, bindPdfAccess } from "@app/services/pdfPasswordStore";+import {+ getPdfAccess,+ rememberPdfAccess,+ bindPdfAccess,+} from "@app/services/pdfPasswordStore";+import { fileStorage } from "@app/services/fileStorage";import { generateProcessedFileMetadata } from "@app/contexts/file/fileActions";import {@@ -60,23 +65,33 @@ vi.mock("@app/components/shared/EncryptedPdfUnlockModal", () => ({onSkip,onUnlock,onRemovePassword,+ ownerUnlock,+ errorMessage,+ password,onPasswordChange,}: {opened: boolean;onSkip: () => void;onUnlock: () => void;- onRemovePassword: () => void;+ onRemovePassword?: () => void;+ ownerUnlock?: boolean;+ errorMessage?: string | null;+ password: string;onPasswordChange: (password: string) => void;}) =>opened ? (<><button onClick={onSkip}>Cancel opening</button><input- aria-label="PDF password"+ aria-label={ownerUnlock ? "Permissions password" : "PDF password"}+ value={password}onChange={(event) => onPasswordChange(event.target.value)}/><button onClick={onUnlock}>Unlock</button>- <button onClick={onRemovePassword}>Remove Password</button>+ {!ownerUnlock && onRemovePassword && (+ <button onClick={onRemovePassword}>Remove Password</button>+ )}+ {errorMessage && <span role="alert">{errorMessage}</span>}</>) : null,}));@@ -123,6 +138,7 @@ function wrapper({ children }: { children: ReactNode }) {}beforeEach(() => {+ vi.mocked(apiClient.post).mockReset();vi.mocked(generateProcessedFileMetadata).mockResolvedValue({pages: [],totalPages: 1,@@ -141,7 +157,7 @@ describe("protected tool replacements", () => {});afterEach(() => vi.restoreAllMocks());- it.each(["cancel", "unlock", "remove-password"])(+ it.each(["cancel", "unlock"])("retains inputs until %s settles the output",async (decision) => {const { result } = renderHook(@@ -179,28 +195,21 @@ describe("protected tool replacements", () => {return;}vi.mocked(apiClient.post).mockResolvedValueOnce({- data:- decision === "remove-password"- ? new Blob(["plain"])- : {- encrypted: true,- signed: false,- ownerAuthenticated: true,- permissions: -4,- canModify: true,- canAssemble: true,- pageCount: 1,- },+ data: {+ encrypted: true,+ signed: false,+ ownerAuthenticated: true,+ permissions: -4,+ canModify: true,+ canAssemble: true,+ pageCount: 1,+ },});fireEvent.change(screen.getByLabelText("PDF password"), {target: { value: "secret" },});await act(async () => {- fireEvent.click(- screen.getByText(- decision === "unlock" ? "Unlock" : "Remove Password",- ),- );+ fireEvent.click(screen.getByText("Unlock"));await consuming;});const accepted = await consuming;@@ -211,7 +220,7 @@ describe("protected tool replacements", () => {).toMatchObject({derivedFromTool: true,sourceFileIds: [id],- processedFile: { isEncrypted: decision === "unlock" },+ processedFile: { isEncrypted: true },});},);@@ -287,88 +296,261 @@ afterEach(() => {});describe("encrypted bytes opened by another editor", () => {- it("returns an unprotected copy to the opening editor and preserves the original", async () => {- const persist = vi- .spyOn(fileStorage, "persistVersionedOutputs")- .mockResolvedValue();- vi.mocked(apiClient.post).mockResolvedValueOnce({- data: new Blob(["unprotected output"]),- });+ it.each([false, true])(+ "removes the opening password while retaining owner protection: %s",+ async (hasOwnerPassword) => {+ const persist = vi+ .spyOn(fileStorage, "persistVersionedOutputs")+ .mockResolvedValue();+ const { result } = renderHook(+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),+ { wrapper },+ );+ const original = new File(["encrypted original"], "locked.pdf");+ let loading!: ReturnType<typeof result.current.actions.addFiles>;+ await act(async () => {+ loading = result.current.actions.addFiles([original]);+ });+ const security = {+ encrypted: true,+ signed: false,+ 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 });+ if (hasOwnerPassword) {+ fireEvent.change(screen.getByLabelText("PDF password"), {+ target: { value: "reader" },+ });+ await act(async () => {+ fireEvent.click(screen.getByText("Remove Password"));+ });+ expect(screen.getByLabelText("Permissions password")).toBeVisible();+ expect(post).toHaveBeenCalledTimes(1);+ expect(getPdfAccess(original)).toBeUndefined();+ expect(result.current.selectors.getAllFileIds()).toEqual([]);+ post.mockResolvedValueOnce({+ data: {+ ...security,+ openingAuthenticated: false,+ ownerAuthenticated: true,+ },+ });+ }+ post.mockResolvedValueOnce({ data: new Blob(["password removed"]) });+ post.mockResolvedValueOnce({+ data: {+ ...security,+ encrypted: hasOwnerPassword,+ openingAuthenticated: true,+ ownerAuthenticated: false,+ requiresOpeningPassword: false,+ },+ });+ fireEvent.change(+ screen.getByLabelText(+ hasOwnerPassword ? "Permissions password" : "PDF password",+ ),+ { target: { value: hasOwnerPassword ? "owner" : "reader" } },+ );+ await act(async () => {+ fireEvent.click(+ screen.getByText(hasOwnerPassword ? "Unlock" : "Remove Password"),+ );+ await loading;+ });+ const [copy] = await loading;+ expect(copy.name).toBe("locked_password_removed.pdf");+ expect(getPdfAccess(copy)).toMatchObject({+ encrypted: hasOwnerPassword,+ ownerAuthenticated: false,+ password: "",+ permissions: security.permissions,+ });+ const request = post.mock.calls.find(+ ([url]) => url === "/api/v1/security/remove-pdf-passwords",+ )!;+ const form = request[1] as FormData;+ expect(form.get("password")).toBe("reader");+ expect(form.get("sourcePassword")).toBe(+ hasOwnerPassword ? "owner" : "reader",+ );+ expect(form.has("ownerPassword")).toBe(false);+ expect(result.current.selectors.getAllFileIds()).toEqual([copy.fileId]);+ expect(isAwaitingUnlock(id)).toBe(false);+ expect(persist).toHaveBeenCalledWith([id], [copy], expect.any(Array));+ expect(original.size).toBe("encrypted original".length);+ persist.mockRestore();+ },+ );++ it("does not admit or remove a pending PDF when permissions verification is cancelled", async () => {const { result } = renderHook(() => ({ ...useFileActions(), selectors: useFileSelectors() }),{ wrapper },);- const original = new File(["encrypted original"], "locked.pdf");let loading!: ReturnType<typeof result.current.actions.addFiles>;await act(async () => {- loading = result.current.actions.addFiles([original]);+ loading = result.current.actions.addFiles([+ new File(["encrypted"], "locked.pdf"),+ ]);});+ const security = {+ encrypted: true,+ signed: false,+ 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 });fireEvent.change(screen.getByLabelText("PDF password"), {- target: { value: "secret" },+ target: { value: "reader" },});await act(async () => {fireEvent.click(screen.getByText("Remove Password"));});- const [copy] = await loading;- expect(copy.name).toBe("locked_unprotected.pdf");- expect(copy.fileId).not.toBe(id);- expect(result.current.selectors.getAllFileIds()).toEqual([copy.fileId]);- expect(- result.current.selectors.getStirlingFileStub(copy.fileId),- ).toMatchObject({- parentFileId: id,- versionNumber: 2,- toolHistory: [{ toolId: "removePassword" }],+ post.mockResolvedValueOnce({ data: security });+ fireEvent.change(screen.getByLabelText("Permissions password"), {+ target: { value: "reader" },});- expect(persist).toHaveBeenCalledWith(- [id],- [copy],- [expect.objectContaining({ parentFileId: id })],+ await act(async () => {+ fireEvent.click(screen.getByText("Unlock"));+ });+ expect(screen.getByRole("alert")).toHaveTextContent(+ "encryptedPdfUnlock.ownerRequired",);- expect(original.name).toBe("locked.pdf");- expect(original.size).toBe("encrypted original".length);- expect(getPdfAccess(copy)).toBeUndefined();- expect(getPdfAccess(original)).toBeUndefined();+ expect(+ post.mock.calls.every(+ ([url]) => url === "/api/v1/security/inspect-pdf-security",+ ),+ ).toBe(true);+ await act(async () => {+ fireEvent.click(screen.getByText("Cancel opening"));+ await loading;+ });+ await expect(loading).resolves.toEqual([]);+ expect(getPdfAccess(id)).toBeUndefined();+ expect(result.current.selectors.getAllFileIds()).toEqual([]);expect(isAwaitingUnlock(id)).toBe(false);- const [endpoint, form] = vi.mocked(apiClient.post).mock.calls.at(-1)!;- expect(endpoint).toBe("/api/v1/security/remove-password");- expect((form as FormData).get("password")).toBe("secret");- persist.mockRestore();});- it("keeps a failed password removal pending without creating an output", async () => {+ it("creates an unprotected version only from verified owner access", async () => {+ observed.isEncrypted = false;const persist = vi.spyOn(fileStorage, "persistVersionedOutputs").mockResolvedValue();- vi.mocked(apiClient.post).mockRejectedValueOnce(- new Error("Incorrect password"),- );const { result } = renderHook(() => ({ ...useFileActions(), selectors: useFileSelectors() }),{ wrapper },);- let loading!: ReturnType<typeof result.current.actions.addFiles>;await act(async () => {- loading = result.current.actions.addFiles([- new File(["encrypted"], "locked.pdf"),+ await result.current.actions.addFiles([+ new File(["original"], "locked.pdf"),]);});- fireEvent.change(screen.getByLabelText("PDF password"), {- target: { value: "wrong" },+ const file = result.current.selectors.getFile(id)!;+ await expect(+ result.current.actions.createUnprotectedCopy(file.fileId),+ ).rejects.toThrow("encryptedPdfUnlock.ownerRequired");+ rememberPdfAccess(file, {+ password: "owner",+ encrypted: true,+ 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,+ },+ });+ await act(async () =>+ result.current.actions.createUnprotectedCopy(file.fileId),+ );+ const copy = result.current.selectors.getFiles(+ result.current.selectors.getAllFileIds(),+ )[0];+ expect(copy.name).toBe("locked_unprotected.pdf");+ expect(getPdfAccess(copy)?.encrypted).toBe(false);+ expect(persist).toHaveBeenCalledWith(+ [file.fileId],+ [copy],+ [expect.objectContaining({ parentFileId: file.fileId })],+ );+ expect(file.size).toBe("original".length);+ persist.mockRestore();+ });++ it("settles an action's permission request when cancelled or the file is closed", async () => {+ observed.isEncrypted = false;+ const { result } = renderHook(+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),+ { wrapper },+ );await act(async () => {- fireEvent.click(screen.getByText("Remove Password"));+ await result.current.actions.addFiles([+ new File(["original"], "locked.pdf"),+ ]);});- expect(result.current.selectors.getAllFileIds()).toEqual([]);- expect(isAwaitingUnlock(id)).toBe(true);- expect(persist).not.toHaveBeenCalled();- await act(async () => {- fireEvent.click(screen.getByText("Cancel opening"));+ const file = result.current.selectors.getFile(id)!;+ rememberPdfAccess(file, {+ password: "",+ encrypted: true,+ signed: false,+ ownerAuthenticated: false,+ permissions: 0,+ canModify: false,+ canAssemble: false,+ pageCount: 1,});- await expect(loading).resolves.toEqual([]);- persist.mockRestore();+ let pending!: Promise<boolean>;+ act(() => {+ pending = result.current.actions.requestPdfOwnerAccess(+ file.fileId,+ "Compress",+ );+ });+ await act(async () => fireEvent.click(screen.getByText("Cancel opening")));+ await expect(pending).resolves.toBe(false);+ expect(result.current.selectors.getFile(file.fileId)).toBe(file);+ act(() => {+ pending = result.current.actions.requestPdfOwnerAccess(+ file.fileId,+ "Compress",+ );+ });+ await act(async () =>+ result.current.actions.removeFiles([file.fileId], false),+ );+ await expect(pending).resolves.toBe(false);});-it("cancelling while persistence finishes does not return a file to the caller", async () => {let finishWrite!: () => void;observed.afterDispatch = () =>@@ -541,6 +723,7 @@ describe("preview session credentials", () => {expect(getPdfAccess(preview)).toEqual({...previewSecurity,password: " secret ",+ openingPassword: " secret ",});expect(result.current.selectors.getAllFileIds()).toEqual([]);expect(result.current.selectors.getFiles()).toEqual([]);diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsxindex e57073bc2c..b2d8f41b95 100644--- a/frontend/editor/src/core/contexts/FileContext.tsx+++ b/frontend/editor/src/core/contexts/FileContext.tsx@@ -66,7 +66,10 @@ 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 { unlockPdfForSession } from "@app/services/pdfSessionUnlock";+import {+ hasPdfPermissionOverride,+ unlockPdfForSession,+} from "@app/services/pdfSessionUnlock";import {bindPdfAccess,clearPdfAccess,@@ -74,6 +77,7 @@ import {forgetPreviewPdfAccess,getPdfAccess,rememberPdfAccess,+ type PdfAccess,} from "@app/services/pdfPasswordStore";import { reportFilesRemoved } from "@app/services/failureReporting";import {@@ -82,10 +86,7 @@ import {} from "@app/services/pendingUnlocks";import { handlePasswordError } from "@app/utils/toolErrorHandler";import apiClient from "@app/services/apiClient";-import {- buildRemovePasswordFormData,- REMOVE_PASSWORD_ENDPOINT,-} from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";+import { buildRemovePasswordFormData } from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";// Inner provider component that has access to IndexedDBfunction FileContextInner({@@ -134,6 +135,20 @@ function FileContextInner({const [unlockPassword, setUnlockPassword] = useState("");const [unlockError, setUnlockError] = useState<string | null>(null);const [isUnlocking, setIsUnlocking] = useState(false);+ const [openingPasswordToRemove, setOpeningPasswordToRemove] = useState<+ string | null+ >(null);+ const ownerRequests = useRef(+ new Map<+ FileId,+ {+ action: string;+ preservationReason?: string;+ promise: Promise<boolean>;+ resolve: (allowed: boolean) => void;+ }+ >(),+ );const observedFileIdsRef = useRef<Set<FileId>>(new Set());const admissionResults = useRef(new Map<FileId, Promise<boolean | StirlingFile>>(),@@ -271,6 +286,8 @@ function FileContextInner({const cancelPendingAdmissions = useCallback((ids: readonly FileId[]) => {for (const id of ids) {+ ownerRequests.current.get(id)?.resolve(false);+ ownerRequests.current.delete(id);const pending = pendingAdmissions.current.get(id);if (!pending) continue;pendingAdmissions.current.delete(id);@@ -357,6 +374,7 @@ function FileContextInner({useEffect(() => {setUnlockPassword("");setUnlockError(null);+ setOpeningPasswordToRemove(null);}, [activeEncryptedFileId]);// Storage proved a file's bytes unreadable (WebKit losing a blob's backing@@ -376,6 +394,12 @@ function FileContextInner({const handleUnlockSkip = useCallback(() => {if (activeEncryptedFileId) {+ ownerRequests.current.get(activeEncryptedFileId)?.resolve(false);+ ownerRequests.current.delete(activeEncryptedFileId);+ if (getPdfAccess(activeEncryptedFileId)) {+ setActiveEncryptedFileId(null);+ return;+ }const pending = pendingAdmissions.current.get(activeEncryptedFileId);if (pending) {pendingAdmissions.current.delete(activeEncryptedFileId);@@ -618,6 +642,14 @@ function FileContextInner({if (filesRef.current.get(fileId) !== file) {return;}+ if (getPdfAccess(file)?.encrypted && !access.ownerAuthenticated) {+ throw new Error(+ t(+ "encryptedPdfUnlock.ownerRequired",+ "Enter the permissions password to allow restricted actions.",+ ),+ );+ }rememberPdfAccess(file, access);bindPdfAccess(file, fileId);const metadata = await generateProcessedFileMetadata(file);@@ -646,16 +678,17 @@ function FileContextInner({}pendingAdmissions.current.delete(fileId);pending?.resolve(true);+ ownerRequests.current.get(fileId)?.resolve(true);+ ownerRequests.current.delete(fileId);},[t],);- const runPasswordRemoval = useCallback(- async (fileId: FileId, password: string): Promise<void> => {- const file = filesRef.current.get(fileId);+ const admitProtectionCopy = useCallback(+ async (fileId: FileId, file: File, copy: File, copyAccess: PdfAccess) => {const pending = pendingAdmissions.current.get(fileId);const sourceStub = pending?.stub ?? stateRef.current.files.byId[fileId];- if (!file || !sourceStub) {+ if (!sourceStub || filesRef.current.get(fileId) !== file) {throw new Error(t("encryptedPdfUnlock.missingFile",@@ -663,32 +696,14 @@ function FileContextInner({),);}- const response = await apiClient.post<Blob>(- REMOVE_PASSWORD_ENDPOINT,- buildRemovePasswordFormData({ password }, file),- {- responseType: "blob",- suppressErrorToast: true,- },- );- if (filesRef.current.get(fileId) !== file) return;- const copy = new File(- [response.data],- `${file.name.replace(/\.pdf$/i, "")}_unprotected.pdf`,- {- type: "application/pdf",- },- );- const metadata = await generateProcessedFileMetadata(copy);+ rememberPdfAccess(copy, copyAccess);+ const generatedMetadata = await generateProcessedFileMetadata(copy);+ const metadata = {+ ...generatedMetadata,+ pages: generatedMetadata?.pages ?? [],+ isEncrypted: copyAccess.encrypted,+ };if (filesRef.current.get(fileId) !== file) return;- if (metadata?.isEncrypted) {- throw new Error(- t(- "removePassword.error.failed",- "An error occurred while removing the password from the PDF.",- ),- );- }const stub = createChildStub(sourceStub,{ toolId: "removePassword", timestamp: Date.now() },@@ -718,78 +733,189 @@ function FileContextInner({[t, dispatchWithUnlock, indexedDB],);- const handleUnlockSubmit = useCallback(- async (removePassword = false) => {- if (!activeEncryptedFileId || isUnlocking) return;- if (unlockPassword.length === 0) {- setUnlockError(- t("encryptedPdfUnlock.required", "Enter the password to continue."),+ const runUnprotectedCopy = useCallback(+ async (fileId: FileId): Promise<void> => {+ const access = getPdfAccess(fileId);+ if (!access || !hasPdfPermissionOverride(access))+ throw new Error(+ t(+ "encryptedPdfUnlock.ownerRequired",+ "Enter the permissions password to continue.",+ ),);- return;- }+ const file = filesRef.current.get(fileId);+ if (!file)+ throw new Error(+ t(+ "encryptedPdfUnlock.missingFile",+ "The selected file is no longer available.",+ ),+ );+ const response = await apiClient.post<Blob>(+ "/api/v1/security/remove-pdf-protection",+ buildRemovePasswordFormData({ password: access.password }, file),+ { responseType: "blob", suppressErrorToast: true },+ );+ if (filesRef.current.get(fileId) !== file) return;+ const copy = new File(+ [response.data],+ `${file.name.replace(/\.pdf$/i, "")}_unprotected.pdf`,+ { type: "application/pdf" },+ );+ const copyAccess = await unlockPdfForSession(copy, "");+ if (copyAccess.encrypted)+ throw new Error(+ t(+ "encryptedPdfUnlock.securityChangeFailed",+ "Unable to change protection. Check the permissions password and the new security settings.",+ ),+ );+ await admitProtectionCopy(fileId, file, copy, copyAccess);+ },+ [admitProtectionCopy, t],+ );- setIsUnlocking(true);- setUnlockError(null);- try {- if (removePassword) {- await runPasswordRemoval(activeEncryptedFileId, unlockPassword);- } else {- await runSessionUnlock(activeEncryptedFileId, unlockPassword);+ const runUnprotectedCopyRef = useRef(runUnprotectedCopy);+ runUnprotectedCopyRef.current = runUnprotectedCopy;++ const handleRemoveOpeningPassword = useCallback(async () => {+ if (!activeEncryptedFileId || isUnlocking || !unlockPassword) return;+ const fileId = activeEncryptedFileId;+ const file = filesRef.current.get(fileId);+ if (!file) return;+ setIsUnlocking(true);+ setUnlockError(null);+ try {+ const access = await unlockPdfForSession(file, unlockPassword);+ 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) {+ setOpeningPasswordToRemove(unlockPassword);+ setUnlockPassword("");+ return;}- const fileName =- stateRef.current.files.byId[activeEncryptedFileId]?.name;+ } else if (!access.ownerAuthenticated) {+ throw new Error(+ t(+ "encryptedPdfUnlock.ownerRequired",+ "Enter the permissions password to continue.",+ ),+ );+ }+ const form = buildRemovePasswordFormData(+ { password: openingPasswordToRemove ?? unlockPassword },+ file,+ );+ // 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",+ form,+ { responseType: "blob", suppressErrorToast: true },+ );+ if (filesRef.current.get(fileId) !== file) return;+ const copy = new File(+ [response.data],+ `${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.",+ ),+ );+ await admitProtectionCopy(fileId, file, copy, copyAccess);+ setActiveEncryptedFileId(null);+ } catch (error) {+ setUnlockError(+ await handlePasswordError(+ error,+ t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),+ t(+ "removePassword.error.failed",+ "An error occurred while removing the password from the PDF.",+ ),+ ),+ );+ } finally {+ setIsUnlocking(false);+ }+ }, [+ activeEncryptedFileId,+ isUnlocking,+ unlockPassword,+ openingPasswordToRemove,+ admitProtectionCopy,+ t,+ ]);++ const handleUnlockSubmit = useCallback(async () => {+ if (!activeEncryptedFileId || isUnlocking) return;+ if (unlockPassword.length === 0) {+ setUnlockError(+ t("encryptedPdfUnlock.required", "Enter the password to continue."),+ );+ return;+ }++ setIsUnlocking(true);+ setUnlockError(null);+ try {+ const requestedAction = ownerRequests.current.has(activeEncryptedFileId);+ await runSessionUnlock(activeEncryptedFileId, unlockPassword);+ const fileName = stateRef.current.files.byId[activeEncryptedFileId]?.name;+ if (!requestedAction)alert({alertType: "success",- title: removePassword- ? t("encryptedPdfUnlock.copyCreated", "Unprotected copy created")- : t("encryptedPdfUnlock.sessionSuccessTitle", "PDF unlocked"),- body: removePassword+ title: getPdfAccess(activeEncryptedFileId)?.ownerAuthenticated? t(- "encryptedPdfUnlock.originalProtected",- "The original PDF stays protected.",+ "encryptedPdfUnlock.permissionsUnlocked",+ "Permissions unlocked for this session",)- : fileName- ? t("encryptedPdfUnlock.sessionSuccessBodyWithName", {- defaultValue:- "Unlocked {{fileName}} for this session. Password protection is retained.",- fileName,- })- : t(- "encryptedPdfUnlock.sessionSuccessBody",- "Unlocked for this session. Password protection is retained.",- ),+ : t("encryptedPdfUnlock.sessionSuccessTitle", "PDF opened"),+ body: fileName+ ? t("encryptedPdfUnlock.sessionSuccessBodyWithName", {+ defaultValue: "Protection retained for {{fileName}}.",+ fileName,+ })+ : t(+ "encryptedPdfUnlock.sessionSuccessBody",+ "Protection retained.",+ ),expandable: false,isPersistentPopup: false,});- setActiveEncryptedFileId(null);- } catch (error) {- const errorMessage = await handlePasswordError(- error,- t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),- removePassword- ? t(- "removePassword.error.failed",- "An error occurred while removing the password from the PDF.",- )- : t(- "encryptedPdfUnlock.sessionFailed",- "Unable to unlock this PDF. Please try again.",- ),- );- setUnlockError(errorMessage);- } finally {- setIsUnlocking(false);- }- },- [- activeEncryptedFileId,- unlockPassword,- isUnlocking,- runSessionUnlock,- runPasswordRemoval,- t,- ],- );+ setActiveEncryptedFileId(null);+ } catch (error) {+ const errorMessage = await handlePasswordError(+ error,+ t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),+ t(+ "encryptedPdfUnlock.sessionFailed",+ "Unable to verify this password. Please try again.",+ ),+ );+ setUnlockError(errorMessage);+ } finally {+ setIsUnlocking(false);+ }+ }, [activeEncryptedFileId, unlockPassword, isUnlocking, runSessionUnlock, t]);const handleUnlockAll = useCallback(async () => {if (!activeEncryptedFileId) return;@@ -894,10 +1020,10 @@ function FileContextInner({if (signal.aborted) return;const access = await unlockPdfForSession(file, password);if (signal.aborted) return;- rememberPdfAccess(file, access);+ const storedAccess = rememberPdfAccess(file, access);signal.addEventListener("abort",- () => forgetPreviewPdfAccess(file, access),+ () => forgetPreviewPdfAccess(file, storedAccess),{ once: true },);},@@ -941,6 +1067,9 @@ function FileContextInner({dispatch({ type: "REORDER_FILES", payload: { orderedFileIds } });},clearAllFiles: async () => {+ for (const request of ownerRequests.current.values())+ request.resolve(false);+ ownerRequests.current.clear();cancelPendingAdmissions([...pendingAdmissions.current.keys()]);clearPdfAccess();lifecycleManager.cleanupAllFiles();@@ -951,6 +1080,9 @@ function FileContextInner({// IndexedDB should only be cleared when explicitly requested by user},clearAllData: async () => {+ for (const request of ownerRequests.current.values())+ request.resolve(false);+ ownerRequests.current.clear();cancelPendingAdmissions([...pendingAdmissions.current.keys()]);clearPdfAccess();// First clear all files from memory@@ -979,6 +1111,30 @@ function FileContextInner({scheduleCleanup: (fileId: FileId, delay?: number) =>lifecycleManager.scheduleCleanup(fileId, delay, stateRef),openEncryptedUnlockPrompt: promptEncryptedUnlock,+ requestPdfOwnerAccess: (fileId, action, preservationReason) => {+ if (!filesRef.current.has(fileId)) return Promise.resolve(false);+ if (+ preservationReason+ ? getPdfAccess(fileId)?.ownerAuthenticated+ : hasPdfPermissionOverride(getPdfAccess(fileId))+ )+ return Promise.resolve(true);+ const existing = ownerRequests.current.get(fileId);+ if (existing) return existing.promise;+ let resolve!: (allowed: boolean) => void;+ const promise = new Promise<boolean>((settle) => {+ resolve = settle;+ });+ ownerRequests.current.set(fileId, {+ action,+ preservationReason,+ promise,+ resolve,+ });+ promptEncryptedUnlock(fileId);+ return promise;+ },+ createUnprotectedCopy: (fileId) => runUnprotectedCopyRef.current(fileId),unlockPreviewPdf,}),[@@ -1054,6 +1210,9 @@ function FileContextInner({// StrictMode can replay effects after files hydrate; only an actual unmount owns cleanup.queueMicrotask(() => {if (!mountedRef.current) {+ for (const request of ownerRequests.current.values())+ request.resolve(false);+ ownerRequests.current.clear();for (const pending of pendingAdmissions.current.values())pending.resolve(false);pendingAdmissions.current.clear();@@ -1077,6 +1236,26 @@ function FileContextInner({/><EncryptedPdfUnlockModalsessionUnlock+ preservationReason={+ openingPasswordToRemove !== null+ ? t(+ "encryptedPdfUnlock.retainOwnerVerification",+ "Verify the permissions password to keep it unchanged while removing the opening password. This will not remove it.",+ )+ : activeEncryptedFileId+ ? ownerRequests.current.get(activeEncryptedFileId)+ ?.preservationReason+ : undefined+ }+ ownerUnlock={+ openingPasswordToRemove !== null ||+ (!!activeEncryptedFileId && !!getPdfAccess(activeEncryptedFileId))+ }+ actionLabel={+ activeEncryptedFileId+ ? ownerRequests.current.get(activeEncryptedFileId)?.action+ : undefined+ }opened={isUnlockModalOpen}fileName={activeEncryptedStub?.name}password={unlockPassword}@@ -1084,9 +1263,15 @@ function FileContextInner({isProcessing={isUnlocking}remainingCount={encryptedQueue.length}onPasswordChange={setUnlockPassword}- onUnlock={() => void handleUnlockSubmit()}- onRemovePassword={() => void handleUnlockSubmit(true)}- onUnlockAll={handleUnlockAll}+ onUnlock={() =>+ void (openingPasswordToRemove !== null+ ? handleRemoveOpeningPassword()+ : handleUnlockSubmit())+ }+ onRemovePassword={() => void handleRemoveOpeningPassword()}+ onUnlockAll={+ openingPasswordToRemove !== null ? undefined : handleUnlockAll+ }onSkip={handleUnlockSkip}/></FileActionsContext.Provider>diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsxindex a39cf14318..5421fc627a 100644--- a/frontend/editor/src/core/contexts/ViewerContext.tsx+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx@@ -390,15 +390,15 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {bridgeRefs.current.permissions?.state || {isEncrypted: false,isOwnerUnlocked: false,- permissions: PdfPermissionFlag.AllowAll,- canPrint: true,- canModifyContents: true,- canCopyContents: true,- canModifyAnnotations: true,- canFillForms: true,+ permissions: 0,+ canPrint: false,+ canModifyContents: false,+ canCopyContents: false,+ canModifyAnnotations: false,+ canFillForms: false,canExtractForAccessibility: true,- canAssembleDocument: true,- canPrintHighQuality: true,+ canAssembleDocument: false,+ canPrintHighQuality: false,});}, []);@@ -408,13 +408,7 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {if (api?.hasPermission) {return api.hasPermission(flag);}- // Default: allow all permissions - warn in development- if (process.env.NODE_ENV === "development") {- console.warn(- "[ViewerContext] Permissions API not available, defaulting to allow",- );- }- return true;+ return false;}, []);// Action handlers - call APIs directlydiff --git a/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.tsindex 54c605d24c..4db47d63f3 100644--- a/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts+++ b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts@@ -17,7 +17,7 @@ vi.mock("@app/utils/thumbnailUtils", () => ({generateThumbnailForFile: vi.fn(),}));vi.mock("@app/services/fileAnalyzer", () => ({- FileAnalyzer: { isPDFUserPasswordProtected: async () => false },+ FileAnalyzer: { isPDFEncrypted: async () => false },}));import { addFiles } from "@app/contexts/file/fileActions";diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.tsindex cf7fd15080..24a215775a 100644--- a/frontend/editor/src/core/contexts/file/fileActions.ts+++ b/frontend/editor/src/core/contexts/file/fileActions.ts@@ -502,9 +502,11 @@ export async function addFiles(try {fileStub.processedFile = {pages: [],- isEncrypted: await FileAnalyzer.isPDFUserPasswordProtected(file),+ 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(@@ -1014,15 +1016,14 @@ export async function addStirlingFileStubs(if ((stirlingFile.type === "application/pdf" ||/\.pdf$/i.test(stirlingFile.name)) &&- (decision.contentReplaced ||- record.processedFile?.isEncrypted === undefined)+ (decision.contentReplaced || !getPdfAccess(stirlingFile))) {record.processedFile = {pages: [],- isEncrypted:- await FileAnalyzer.isPDFUserPasswordProtected(stirlingFile),+ isEncrypted: await FileAnalyzer.isPDFEncrypted(stirlingFile),};}+ bindPdfAccess(stirlingFile, fileId);dispatch({type: "ADD_FILES",payload: { stirlingFileStubs: [record] },diff --git a/frontend/editor/src/core/contexts/viewer/viewerActions.ts b/frontend/editor/src/core/contexts/viewer/viewerActions.tsindex ae5679c9b6..62029c6832 100644--- a/frontend/editor/src/core/contexts/viewer/viewerActions.ts+++ b/frontend/editor/src/core/contexts/viewer/viewerActions.ts@@ -32,7 +32,8 @@ export interface PanActions {}export interface SelectionActions {- copyToClipboard: () => void;+ /** Resolves false when the document forbids copying or the clipboard write fails. */+ copyToClipboard: () => Promise<boolean>;getFormattedSelection: () => FormattedSelection[] | null;selectAll: (totalPages: number) => Promise<boolean>;selectWordAt: (pageIndex: number, x: number, y: number) => boolean;@@ -252,12 +253,9 @@ export function createViewerActions({};const selectionActions: SelectionActions = {- copyToClipboard: () => {- const api = registry.current.selection?.api;- if (api?.copyToClipboard) {- api.copyToClipboard();- }- },+ copyToClipboard: () =>+ registry.current.selection?.api?.copyToClipboard() ??+ Promise.resolve(false),getFormattedSelection: () => {const api = registry.current.selection?.api;if (api?.getFormattedSelection) {diff --git a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts b/frontend/editor/src/core/contexts/viewer/viewerBridges.tsindex 2cf5a67e63..0f4f80dfcb 100644--- a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts+++ b/frontend/editor/src/core/contexts/viewer/viewerBridges.ts@@ -58,7 +58,7 @@ export interface PanAPIWrapper {}export interface SelectionAPIWrapper {- copyToClipboard: () => void;+ copyToClipboard: () => Promise<boolean>;getFormattedSelection: () => FormattedSelection[];selectAll: (totalPages: number) => Promise<boolean>;selectWordAt: (pageIndex: number, x: number, y: number) => boolean;diff --git a/frontend/editor/src/core/data/settingsSearchIndex.ts b/frontend/editor/src/core/data/settingsSearchIndex.tsindex 354da10358..dca3453cd7 100644--- a/frontend/editor/src/core/data/settingsSearchIndex.ts+++ b/frontend/editor/src/core/data/settingsSearchIndex.ts@@ -265,6 +265,20 @@ export const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [labelFallback: "Audit log",keywords: ["audit", "log", "retention", "events"],},+ {+ section: "adminSecurity",+ anchor: "pdfPermissions",+ labelKey: "admin.settings.security.honorOwnerPasswords.label",+ labelFallback: "Honor PDF permissions",+ keywords: [+ "pdf",+ "owner",+ "password",+ "permissions",+ "restrictions",+ "honorOwnerPasswords",+ ],+ },{section: "adminDatabase",anchor: "adminDatabase",diff --git a/frontend/editor/src/core/data/urlSeoOverrides.json b/frontend/editor/src/core/data/urlSeoOverrides.jsonindex b1762b1d32..159f64aa41 100644--- a/frontend/editor/src/core/data/urlSeoOverrides.json+++ b/frontend/editor/src/core/data/urlSeoOverrides.json@@ -201,7 +201,7 @@},"/remove-password": {"title": "Remove PDF Password",- "description": "Remove password protection from PDF documents"+ "description": "Remove the opening password, permissions password, or both."},"/change-permissions": {"title": "Change PDF Permissions",diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsxindex 3f6d575e30..d365e7afdc 100644--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx@@ -847,11 +847,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {},removePassword: {icon: <Icon name="lock-open-password" size="1.5rem" />,- name: t("home.removePassword.title", "Remove Password"),+ name: t("removePassword.title", "Remove Password"),component: lazy(() => import("@app/tools/RemovePassword")),description: t("home.removePassword.desc",- "Remove password protection from PDF documents",+ "Remove the opening password, permissions password, or both.",),categoryId: ToolCategoryId.STANDARD_TOOLS,subcategoryId: SubcategoryId.REMOVAL,diff --git a/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.test.ts b/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.test.tsindex 1ff96f5f15..3482941100 100644--- a/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.test.ts+++ b/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.test.ts@@ -121,19 +121,25 @@ describe("useAddPasswordParameters", () => {hook.permissions.updateParameter("preventAssembly", true);},},- ])("should validate parameters correctly $description", ({ setup }) => {- const { result } = renderHook(() => useAddPasswordParameters());+ ])(+ "should validate parameters correctly $description",+ ({ setup, description }) => {+ const { result } = renderHook(() => useAddPasswordParameters());- // Default state should be valid- expect(result.current.validateParameters()).toBe(true);+ expect(result.current.validateParameters()).toBe(false);- // Apply the test scenario setup- act(() => {- setup(result.current);- });+ // Apply the test scenario setup+ act(() => {+ setup(result.current);+ });- expect(result.current.validateParameters()).toBe(true);- });+ expect(result.current.validateParameters()).toBe(+ !["with restrictions only", "with passwords and restrictions"].includes(+ description,+ ),+ );+ },+ );test.each(Object.keys(defaultChangePermissionsParameters) as Array<@@ -147,6 +153,8 @@ describe("useAddPasswordParameters", () => {result.current.permissions.updateParameter(param, true);});+ expect(result.current.validateParameters()).toBe(false);+ act(() => result.current.updateParameter("ownerPassword", "permissions"));expect(result.current.validateParameters()).toBe(true);});diff --git a/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.ts b/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.tsindex 97f0b41aa8..38daa46054 100644--- a/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.ts+++ b/frontend/editor/src/core/hooks/tools/addPassword/useAddPasswordParameters.ts@@ -33,12 +33,21 @@ export const defaultParameters: AddPasswordParameters = {/*** Whether these parameters are complete enough to run.- * Add Password requires nothing of its own, so delegate to Change Permissions.+ * Restrictions require separate credentials so opening the document does not grant owner access.*/export function validateAddPasswordParameters(params: AddPasswordFullParameters,): boolean {- return validateChangePermissionsParameters(params.permissions);+ const restricted = Object.entries(params.permissions).some(+ ([key, value]) => key.startsWith("prevent") && value === true,+ );+ return (+ validateChangePermissionsParameters(params.permissions) &&+ (params.password.length > 0 || params.ownerPassword.length > 0) &&+ (!restricted ||+ (params.ownerPassword.length > 0 &&+ params.ownerPassword !== params.password))+ );}export const useAddPasswordParameters = (): AddPasswordParametersHook => {@@ -66,6 +75,7 @@ export const useAddPasswordParameters = (): AddPasswordParametersHook => {return {...baseHook,fullParameters,+ validateParameters: () => validateAddPasswordParameters(fullParameters),permissions,resetParameters,};diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.test.ts b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.test.tsindex bad85097e2..a7d6c456d4 100644--- a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.test.ts+++ b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.test.ts@@ -120,7 +120,7 @@ describe("useChangePermissionsOperation", () => {expect(formData.get(key),`Parameter ${key} should be set correctly`,- ).toBe(testParameters[key].toString());+ ).toBe(String(testParameters[key]));});},);diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.ts b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.tsindex fa249a6162..2b13a20d9b 100644--- a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.ts+++ b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsOperation.ts@@ -15,17 +15,17 @@ import {validateChangePermissionsParameters,} from "@app/hooks/tools/changePermissions/useChangePermissionsParameters";-// Change Permissions reuses the Add Password endpoint but sends only the-// prevent* subset of the request model (no password or keyLength).+// No keyLength distinguishes a permissions-only step from Add Password.const ENDPOINT = "/api/v1/security/add-password" satisfies ToolEndpoint;type AddPasswordApiParams = ToolApiParams[typeof ENDPOINT];-// Convert the tool's UI parameters into the add-password request body. Only the-// prevent* permission flags are sent; password and keyLength are optional on the-// model and left unset, so the endpoint changes permissions without encrypting.export const changePermissionsToApiParams = (parameters: ChangePermissionsParameters,): AddPasswordApiParams => ({+ ...(parameters.password ? { password: parameters.password } : {}),+ ...(parameters.ownerPassword+ ? { ownerPassword: parameters.ownerPassword }+ : {}),preventAssembly: parameters.preventAssembly ?? false,preventExtractContent: parameters.preventExtractContent ?? false,preventExtractForAccessibility:@@ -42,6 +42,10 @@ export const changePermissionsToApiParams = (export const changePermissionsFromApiParams = (apiParams: AddPasswordApiParams,): Partial<ChangePermissionsParameters> => ({+ ...(apiParams.password ? { password: apiParams.password } : {}),+ ...(apiParams.ownerPassword+ ? { ownerPassword: apiParams.ownerPassword }+ : {}),preventAssembly:apiParams.preventAssembly ?? defaultParameters.preventAssembly,preventExtractContent:@@ -80,13 +84,8 @@ export const changePermissionsOperationConfig = defineSingleFileTool({operationType: "changePermissions",endpoint: ENDPOINT, // Change Permissions is a fake endpoint for the Add Password tooldefaultParameters,- // Both tools post to add-password. A permissions-only step carries none of the encryption- // fields, so it is this tool and not Add Password; keyLength, always sent by Add Password,- // is the reliable tell even when a password happens to be blank.- claimsStoredStep: (apiParams) =>- !("password" in apiParams) &&- !("ownerPassword" in apiParams) &&- !("keyLength" in apiParams),+ // Add Password always supplies keyLength, including when its opening password is blank.+ claimsStoredStep: (apiParams) => !("keyLength" in apiParams),});export const useChangePermissionsOperation = () => {diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsParameters.ts b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsParameters.tsindex 039f7214fe..408f6c0004 100644--- a/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsParameters.ts+++ b/frontend/editor/src/core/hooks/tools/changePermissions/useChangePermissionsParameters.ts@@ -5,6 +5,8 @@ import {} from "@app/hooks/tools/shared/useBaseParameters";export interface ChangePermissionsParameters extends BaseParameters {+ ownerPassword?: string;+ password?: string;preventAssembly: boolean;preventExtractContent: boolean;preventExtractForAccessibility: boolean;diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.tsindex 45fc147ec1..32d1dc322b 100644--- a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts+++ b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.test.ts@@ -8,6 +8,7 @@ import {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,@@ -68,6 +69,29 @@ beforeEach(() => {});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([[PdfPermissionFlag.AssembleDocument, "preventAssembly"],[PdfPermissionFlag.CopyContents, "preventExtractContent"],@@ -95,7 +119,7 @@ describe("usePermissionExtraction", () => {[restriction]: true,});expect(getDocumentBytes).toHaveBeenCalledWith(file);- expect(openRawDocument).toHaveBeenCalledWith(bytes);+ expect(openRawDocument).toHaveBeenCalledWith(bytes, undefined);expect(pdfiumModule.FPDF_GetDocUserPermissions).toHaveBeenCalledWith(1);expect(closeDocAndFreeBuffer).toHaveBeenCalledExactlyOnceWith(pdfiumModule,diff --git a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.tsindex c9d3e61bc5..1e9b198381 100644--- a/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts+++ b/frontend/editor/src/core/hooks/tools/changePermissions/usePermissionExtraction.ts@@ -1,4 +1,5 @@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";@@ -58,7 +59,10 @@ export function usePermissionExtraction(if (signal.cancelled) return;const module = await getPdfiumModule();if (signal.cancelled) return;- const docPtr = await openRawDocument(bytes);+ const docPtr = await openRawDocument(+ bytes,+ getPdfAccess(file)?.password,+ );try {if (signal.cancelled) return;// Owner access must not hide the document's stored user restrictions.diff --git a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.tsindex 635df0da4c..f56128fa7e 100644--- a/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts+++ b/frontend/editor/src/core/hooks/tools/removePassword/buildRemovePasswordFormData.ts@@ -35,5 +35,11 @@ export const removePasswordFromApiParams = (export const buildRemovePasswordFormData = (parameters: RemovePasswordParameters,file: File,-): FormData =>- objectToFormData(removePasswordToApiParams(parameters), { fileInput: file });+): FormData => {+ const form = 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.tsindex 8f2953afde..7598db9c62 100644--- a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts+++ b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.test.ts@@ -1,7 +1,15 @@import { describe, expect, test, vi, beforeEach } from "vitest";import { renderHook } from "@testing-library/react";-import { useRemovePasswordOperation } from "@app/hooks/tools/removePassword/useRemovePasswordOperation";+import {+ useRemovePasswordOperation,+ removePasswordOperationConfig,+} from "@app/hooks/tools/removePassword/useRemovePasswordOperation";import type { RemovePasswordParameters } from "@app/hooks/tools/removePassword/useRemovePasswordParameters";+import { createStirlingFile } from "@app/types/fileContext";+import {+ clearPdfAccess,+ rememberPdfAccess,+} from "@app/services/pdfPasswordStore";vi.mock("../shared/useToolOperation", async () => {const actual = await vi.importActual("../shared/useToolOperation"); // Need to keep ToolType etc.@@ -56,9 +64,75 @@ describe("useRemovePasswordOperation", () => {beforeEach(() => {vi.clearAllMocks();+ clearPdfAccess();mockUseToolOperation.mockReturnValue(mockToolOperationReturn);});+ function protectedFile(opening: boolean, owner: boolean) {+ const file = createStirlingFile(+ new File(["PDF"], "test.pdf", { type: "application/pdf" }),+ );+ rememberPdfAccess(file, {+ 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: true, password: "", ownerPassword: "owner" },+ { opening: true, owner: true, password: "reader", ownerPassword: "owner" },+ ])(+ "only submits passwords present on a file (opening=$opening, owner=$owner)",+ ({ opening, owner, password, ownerPassword }) => {+ renderHook(() => useRemovePasswordOperation());+ const form = getToolConfig().buildFormData(+ { password: "reader", ownerPassword: "owner" },+ protectedFile(opening, owner),+ );+ expect(form.get("password")).toBe(password);+ expect(form.get("ownerPassword")).toBe(ownerPassword);+ },+ );++ test.each(["opening", "owner", "both"] as const)(+ "leaves files without the requested %s password unchanged",+ async (remove) => {+ const opening = protectedFile(true, false);+ const owner = protectedFile(false, true);+ const both = protectedFile(true, true);+ const plain = protectedFile(false, false);+ const params = {+ password: remove === "owner" ? "" : "reader",+ ownerPassword: remove === "opening" ? "" : "owner",+ };+ const { result } = renderHook(() => useRemovePasswordOperation());+ await result.current.executeOperation(params, [+ opening,+ owner,+ both,+ plain,+ ]);+ expect(mockToolOperationReturn.executeOperation).toHaveBeenCalledWith(+ params,+ remove === "opening"+ ? [opening, both]+ : remove === "owner"+ ? [owner, both]+ : [opening, owner, both],+ );+ },+ );+test.each([{description: "with valid password",@@ -94,6 +168,14 @@ describe("useRemovePasswordOperation", () => {expect(formData.get("password")).toBe(password);});+ test("legacy automation and unprotected-copy authentication retain owner credentials", () => {+ const form = removePasswordOperationConfig.buildFormData(+ { password: "owner" },+ protectedFile(false, true),+ );+ expect(form.get("password")).toBe("owner");+ });+test("should use correct translation for error messages", () => {renderHook(() => useRemovePasswordOperation());diff --git a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.tsindex e8448bf518..b48af573d2 100644--- a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts+++ b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordOperation.ts@@ -1,4 +1,6 @@import { useTranslation } from "react-i18next";+import type { StirlingFile } from "@app/types/fileContext";+import { getPdfAccess } from "@app/services/pdfPasswordStore";import {useToolOperation,defineSingleFileTool,@@ -30,11 +32,35 @@ export const removePasswordOperationConfig = defineSingleFileTool({defaultParameters,});+// Only selective removal omits absent roles. Legacy automation and unprotected copies+// use the shared form builder's password as authentication, irrespective of its role.+function getRemovePasswordParametersForFile(+ parameters: RemovePasswordParameters,+ file: File,+): RemovePasswordParameters {+ const access = getPdfAccess(file);+ return {+ password:+ access?.encrypted === false || access?.requiresOpeningPassword === false+ ? ""+ : parameters.password,+ ownerPassword:+ access?.encrypted === false || access?.hasOwnerPassword === false+ ? ""+ : parameters.ownerPassword,+ };+}+export const useRemovePasswordOperation = () => {const { t } = useTranslation();- return useToolOperation<RemovePasswordParameters>({+ const operation = useToolOperation<RemovePasswordParameters>({...removePasswordOperationConfig,+ buildFormData: (params: RemovePasswordParameters, file: File) =>+ buildRemovePasswordFormData(+ getRemovePasswordParametersForFile(params, file),+ file,+ ),getErrorMessage: createStandardErrorHandler(t("removePassword.error.failed",@@ -42,4 +68,19 @@ export const useRemovePasswordOperation = () => {),),});+ return {+ ...operation,+ executeOperation: (+ params: RemovePasswordParameters,+ files: StirlingFile[],+ ) =>+ operation.executeOperation(+ params,+ files.filter((file) =>+ validateRemovePasswordParameters(+ getRemovePasswordParametersForFile(params, file),+ ),+ ),+ ),+ };};diff --git a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordParameters.ts b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordParameters.tsindex af920a20f2..13ff3dfa72 100644--- a/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordParameters.ts+++ b/frontend/editor/src/core/hooks/tools/removePassword/useRemovePasswordParameters.ts@@ -6,6 +6,7 @@ import {export interface RemovePasswordParameters extends BaseParameters {password: string;+ ownerPassword?: string;}export type RemovePasswordParametersHook =@@ -20,7 +21,7 @@ export const defaultParameters: RemovePasswordParameters = {export function validateRemovePasswordParameters(params: RemovePasswordParameters,): boolean {- return params.password !== "";+ return params.password !== "" || !!params.ownerPassword;}export const useRemovePasswordParameters = (): RemovePasswordParametersHook => {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.tsindex 7fcb4a9858..210312ed9d 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@@ -1,6 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { renderHook } from "@testing-library/react";+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";// One bad file in a batch must come back named, with its error: the caller reports each one,@@ -21,7 +23,12 @@ const { useToolApiCalls } =await import("@app/hooks/tools/shared/useToolApiCalls");const file = (name: string, id: string): StirlingFile =>- ({ name, fileId: id, size: 10 }) as unknown as StirlingFile;+ Object.assign(+ rememberUnprotectedPdf(+ new File(["test"], name, { type: "application/pdf" }),+ ),+ { fileId: id },+ ) as StirlingFile;function run(files: StirlingFile[]) {const { processFiles } = renderHook(() => useToolApiCalls()).result.current;@@ -42,6 +49,93 @@ beforeEach(() => {});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;+ post.mockImplementationOnce(+ (_endpoint: string, _form: FormData, config: AxiosRequestConfig) => {+ expect(config.cancelToken).toBeDefined();+ return new Promise((resolve) => {+ completeInspection = resolve;+ });+ },+ );+ const { result } = renderHook(() => useToolApiCalls());+ const markFileError = vi.fn();+ const processing = result.current.processFiles(+ undefined,+ [file("a.pdf", "a"), file("b.pdf", "b")],+ {+ endpoint: `/api/v1/security/${operation}`,+ buildFormData: () => {+ const form = new FormData();+ form.set("keyLength", "256");+ return form;+ },+ },+ vi.fn(),+ vi.fn(),+ markFileError,+ );+ const cancelled = expect(processing).rejects.toThrow(+ "Operation was cancelled",+ );+ await vi.waitFor(() => expect(post).toHaveBeenCalledTimes(2));+ result.current.cancelOperation();+ completeInspection({+ data: { encrypted: false, ownerAuthenticated: false, permissions: -4 },+ });+ await cancelled;+ expect(post).toHaveBeenCalledTimes(2);+ expect(markFileError).not.toHaveBeenCalled();+ },+ );++ it.each(["add-password", "remove-password"])(+ "cancels %s without processing the remaining batch or marking files as failed",+ async (operation) => {+ post.mockImplementation(+ (_endpoint: string, _form: FormData, config: AxiosRequestConfig) =>+ new Promise((_resolve, reject) => {+ config.cancelToken?.promise.then(reject);+ }),+ );+ const { result } = renderHook(() => useToolApiCalls());+ const markFileError = vi.fn();+ const processing = result.current.processFiles(+ undefined,+ [file("a.pdf", "a"), file("b.pdf", "b")],+ {+ endpoint: `/api/v1/security/${operation}`,+ buildFormData: () => {+ const form = new FormData();+ form.set("keyLength", "256");+ return form;+ },+ },+ vi.fn(),+ vi.fn(),+ markFileError,+ );+ const cancelled = expect(processing).rejects.toThrow(+ "Operation was cancelled",+ );+ await vi.waitFor(() => expect(post).toHaveBeenCalledOnce());+ result.current.cancelOperation();+ await cancelled;+ expect(post).toHaveBeenCalledOnce();+ expect(markFileError).not.toHaveBeenCalled();+ },+ );+it("stops at a signup gate without labelling the files as failed", async () => {const blocked = {response: { status: 401, data: { error: "SIGNUP_REQUIRED" } },diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.tsindex 4d066bd44d..5b1e5f4ef4 100644--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts@@ -12,7 +12,13 @@ import { isSignupRequiredError } from "@app/utils/toolErrorHandler";import {prepareUnlockedFile,protectUnlockedResults,+ changePdfSecurity,+ unlockPdfForSession,} from "@app/services/pdfSessionUnlock";+import {+ getPdfAccess,+ rememberPdfAccess,+} from "@app/services/pdfPasswordStore";/** An input that did not survive the batch, with the error it failed on. */export interface FailedInput {@@ -55,8 +61,8 @@ export const useToolApiCalls = <TParams = void>() => {const failedFiles: string[] = [];const total = validFiles.length;- // Create cancel token for this operation- cancelTokenRef.current = axios.CancelToken.source();+ const cancellation = axios.CancelToken.source();+ cancelTokenRef.current = cancellation;// 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@@ -84,13 +90,27 @@ export const useToolApiCalls = <TParams = void>() => {onStatus(`Processing ${file.name} (${i + 1}/${total})`);try {+ cancellation.token.throwIfRequested();const workingFile = await prepareUnlockedFile(file, endpoint);const formData = config.buildFormData(params, workingFile);console.debug("[processFiles] POST", { endpoint, name: file.name });- const response = await apiClient.post(endpoint, formData, {- responseType: "blob",- cancelToken: cancelTokenRef.current?.token,- });+ const response =+ endpoint === "/api/v1/security/add-password" ||+ endpoint === "/api/v1/security/remove-password"+ ? {+ data: await changePdfSecurity(+ file,+ formData,+ endpoint,+ cancellation.token,+ ),+ status: 200,+ headers: undefined,+ }+ : await apiClient.post(endpoint, formData, {+ responseType: "blob",+ cancelToken: cancellation.token,+ });console.debug("[processFiles] Response OK", {name: file.name,status: response.status,@@ -104,6 +124,29 @@ export const useToolApiCalls = <TParams = void>() => {config.responseHandler,config.preserveBackendFilename ? response.headers : undefined,);+ if (+ endpoint === "/api/v1/security/add-password" ||+ endpoint === "/api/v1/security/remove-password"+ ) {+ const password =+ endpoint === "/api/v1/security/remove-password"+ ? formData.get("password")+ ? ""+ : String(formData.get("retainedOpeningPassword") ?? "")+ : formData.has("keyLength")+ ? String(formData.get("password") ?? "")+ : (getPdfAccess(file)?.openingPassword ??+ String(+ formData.get("ownerPassword") ||+ getPdfAccess(file)?.password ||+ "",+ ));+ for (const output of responseFiles)+ rememberPdfAccess(+ output,+ await unlockPdfForSession(output, password, cancellation.token),+ );+ }// Guard: some endpoints may return an empty/0-byte file with 200const empty = isEmptyOutput(responseFiles);if (empty) {@@ -123,9 +166,13 @@ export const useToolApiCalls = <TParams = void>() => {}continue;}- processedFiles.push(- ...(await protectUnlockedResults(responseFiles, [file], endpoint)),+ const protectedFiles = await protectUnlockedResults(+ responseFiles,+ [file],+ endpoint,);+ cancellation.token.throwIfRequested();+ processedFiles.push(...protectedFiles);// record source id as successfulsuccessSourceIds.push(file.fileId);console.debug("[processFiles] Success", {@@ -156,6 +203,7 @@ export const useToolApiCalls = <TParams = void>() => {}if (failedFiles.length > 0 && processedFiles.length === 0) {+ if (failedInputs.length === 1) throw failedInputs[0].error;throw new Error(`Failed to process all files: ${failedFiles.join(", ")}`,);diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.tsindex 604377e658..9d8ab79ad3 100644--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts@@ -12,6 +12,7 @@ import { toolAcceptsFile } from "@app/utils/toolIOCompat";import {prepareUnlockedFile,protectUnlockedResults,+ preflightPdfOperation,} from "@app/services/pdfSessionUnlock";import { useToolState } from "@app/hooks/tools/shared/useToolState";import {@@ -325,6 +326,18 @@ export const useToolOperation = <TParams>(try {assertFilesNotBlocked(policyIds);+ const permitted = await preflightPdfOperation(+ validFiles,+ runtimeEndpoint,+ config.toolType !== ToolType.singleFile &&+ config.operationType !== "extractPages",+ (file) =>+ fileActions.requestPdfOwnerAccess(+ file.fileId,+ t(`${config.operationType}.title`, config.operationType),+ ),+ );+ if (!permitted) return;let processedFiles: File[];let successSourceIds: FileId[] = [];let unprocessedSourceIds: FileId[] = [];diff --git a/frontend/editor/src/core/hooks/usePdfAccess.ts b/frontend/editor/src/core/hooks/usePdfAccess.tsindex 6f07299a1d..c745c66e39 100644--- a/frontend/editor/src/core/hooks/usePdfAccess.ts+++ b/frontend/editor/src/core/hooks/usePdfAccess.ts@@ -1,6 +1,8 @@-import { useSyncExternalStore } from "react";+import { useEffect, useSyncExternalStore } from "react";+import { unlockPdfForSession } from "@app/services/pdfSessionUnlock";import {getPdfAccess,+ rememberPdfAccess,pdfAccessRevision,subscribePdfAccess,} from "@app/services/pdfPasswordStore";@@ -12,5 +14,19 @@ 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.tsnew file mode 100644index 0000000000..d28fc3674a--- /dev/null+++ b/frontend/editor/src/core/services/fileAnalyzer.test.ts@@ -0,0 +1,57 @@+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 { 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() }));++beforeEach(() => {+ clearPdfAccess();+ vi.clearAllMocks();+ vi.spyOn(Blob.prototype, "arrayBuffer").mockImplementation(+ function (this: Blob) {+ return new Promise<ArrayBuffer>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ if (reader.result instanceof ArrayBuffer) resolve(reader.result);+ else reject(new Error("Expected PDF bytes"));+ };+ reader.onerror = () => reject(reader.error);+ reader.readAsArrayBuffer(this);+ });+ },+ );+});++afterEach(() => vi.restoreAllMocks());++describe("large PDF encryption detection", () => {+ it.each([LARGE_PDF_PARSE_LIMIT, LARGE_PDF_PARSE_LIMIT * 10])(+ "detects encryption in a %i-byte PDF without parsing or uploading the whole file",+ async (size) => {+ const file = new File(["%PDF-1.7 /Encrypt 1 0 R"], "large.pdf");+ Object.defineProperty(file, "size", { value: size });+ const readAll = vi.spyOn(file, "arrayBuffer");+ const slices = vi.spyOn(file, "slice");++ expect(await FileAnalyzer.isPDFEncrypted(file)).toBe(true);+ expect(ensurePdfAccess).not.toHaveBeenCalled();+ expect(pdfWorkerManager.createDocument).not.toHaveBeenCalled();+ expect(readAll).not.toHaveBeenCalled();+ expect(slices).toHaveBeenCalledTimes(2);+ },+ );++ 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(pdfWorkerManager.createDocument).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/services/fileAnalyzer.ts b/frontend/editor/src/core/services/fileAnalyzer.tsindex 2aed740bf9..a35d922fb3 100644--- a/frontend/editor/src/core/services/fileAnalyzer.ts+++ b/frontend/editor/src/core/services/fileAnalyzer.ts@@ -1,5 +1,7 @@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";@@ -7,8 +9,6 @@ import type { PDFDocumentProxy } from "pdfjs-dist";// 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;--/** A pdf.js worker that dies mid-parse never settles its promise. */const PROBE_TIMEOUT = "pdf-probe-timeout";const PROBE_TIMEOUT_MS = 30_000;@@ -90,22 +90,23 @@ export class FileAnalyzer {return analysis;}- /**- * Quick PDF analysis without full processing- */- /**- * Cheap encryption-only probe for the upload-time detection path.- *- * Looks for a /Encrypt entry in a bounded window at either end of the file- * (where PDF trailers live). If absent, the file is definitely not encrypted- * and we can skip a full pdf.js parse. If present, falls back to pdf.js so we- * can distinguish user-password (blocks open) from owner-password-only (opens- * fine); only the former should prompt.- *- * Runs inside the addFiles mutex, so it must always settle: an unbounded- * parse here stalls every later upload as well as this one.+ /** Detect encryption and admit empty-password documents without prompting.+ * The marker is an upload optimisation, not authorisation; operations inspect original bytes.*/- static async isPDFUserPasswordProtected(file: File): Promise<boolean> {+ 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@@ -168,12 +169,11 @@ export class FileAnalyzer {const pageCount = pdf.numPages;- // If pdf.js opened the document successfully, the user can view it — even if- // the PDF carries encryption dictionaries (owner-password-only case). We only- // flag isEncrypted when pdf.js *fails* to open the file (caught below).return {pageCount,- isEncrypted: false,+ isEncrypted:+ getPdfAccess(file)?.encrypted ??+ (await pdf.getPermissions()) !== null,isCorrupted: false,};} catch (error) {diff --git a/frontend/editor/src/core/services/pdfPasswordStore.ts b/frontend/editor/src/core/services/pdfPasswordStore.tsindex 51ae028438..2c0fc95604 100644--- a/frontend/editor/src/core/services/pdfPasswordStore.ts+++ b/frontend/editor/src/core/services/pdfPasswordStore.ts@@ -3,15 +3,25 @@ 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;}@@ -34,12 +44,21 @@ export function getPdfAccess(return blob ? accessByFile.get(blob) : undefined;}-/** Retain access for the current session, without changing the original file. */-export function rememberPdfAccess(file: Blob, access: PdfAccess): void {- accessByFile.set(file, access);+/** 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. */diff --git a/frontend/editor/src/core/services/pdfPermissions.ts b/frontend/editor/src/core/services/pdfPermissions.tsindex 34d949533a..fc086a4e7a 100644--- a/frontend/editor/src/core/services/pdfPermissions.ts+++ b/frontend/editor/src/core/services/pdfPermissions.ts@@ -1,15 +1,20 @@import type { PdfAccess } from "@app/services/pdfPasswordStore";import { PdfPermissionFlag } from "@app/contexts/viewer/viewerBridges";-/** Owner authentication overrides restrictions; zero permissions on encrypted bytes denies printing. */+/** Applies owner policy and rejects low-quality-only printing, which this viewer cannot produce. */export function canPrintPdf(access:- | Pick<PdfAccess, "encrypted" | "ownerAuthenticated" | "permissions">+ | (Pick<PdfAccess, "encrypted" | "ownerAuthenticated" | "permissions"> &+ Partial<Pick<PdfAccess, "honorOwnerPasswords" | "encryptionRevision">>)| undefined,): boolean {+ if (!access) return false;return (- !access?.encrypted ||+ !access.encrypted ||access.ownerAuthenticated ||- (access.permissions & PdfPermissionFlag.Print) !== 0+ access.honorOwnerPasswords === false ||+ ((access.permissions & PdfPermissionFlag.Print) !== 0 &&+ (access.encryptionRevision === 2 ||+ (access.permissions & PdfPermissionFlag.PrintHighQuality) !== 0)));}diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.test.ts b/frontend/editor/src/core/services/pdfSessionUnlock.test.tsindex df52fcac74..4cadfb5eae 100644--- a/frontend/editor/src/core/services/pdfSessionUnlock.test.ts+++ b/frontend/editor/src/core/services/pdfSessionUnlock.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";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";@@ -17,7 +18,12 @@ import {unlockPdfForSession,verifyEditedPdfProtection,assertPdfSessionEditable,+ preflightPdfOperation,+ changePdfSecurity,+ hasPdfPermissionOverride,+ pdfAllows,} from "@app/services/pdfSessionUnlock";+import { PdfPermissionFlag } from "@embedpdf/models";vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));const post = vi.mocked(apiClient.post);@@ -29,6 +35,7 @@ const access: PdfAccess = {permissions: -4,encryptionKeyLength: 256,encryptionRevision: 6,+ credentialFingerprint: "source-credentials",canModify: true,canAssemble: true,pageCount: 2,@@ -42,6 +49,222 @@ 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" },+ });+ 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);+ });++ it("preserves cancellation classification without retaining password-bearing requests", async () => {+ const file = new File(["encrypted"], "restricted.pdf");+ rememberPdfAccess(file, { ...access, ownerAuthenticated: true });+ const form = new FormData();+ form.set("ownerPassword", "secret");+ const original = Object.assign(new axios.CanceledError("cancelled"), {+ config: { data: form },+ request: { form },+ });+ post.mockRejectedValueOnce(original);+ const cancellation = axios.CancelToken.source();+ const error = await changePdfSecurity(+ file,+ form,+ "/api/v1/security/add-password",+ cancellation.token,+ ).catch((error: unknown) => error);+ expect(axios.isCancel(error)).toBe(true);+ expect(error).not.toHaveProperty("config");+ expect(error).not.toHaveProperty("request");+ expect(error).not.toHaveProperty("cause");+ expect(post.mock.calls[0][2]?.cancelToken).toBe(cancellation.token);+ });++ it.each([undefined, true, false])(+ "uses the server owner policy (%s) without changing authentication",+ async (honorOwnerPasswords) => {+ const file = createStirlingFile(+ new File(["encrypted"], "restricted.pdf"),+ );+ const reader = {+ ...access,+ permissions: 0,+ canModify: false,+ honorOwnerPasswords,+ };+ rememberPdfAccess(file, reader);+ const requestOwner = vi.fn().mockResolvedValue(false);+ const bypass = honorOwnerPasswords === false;+ expect(hasPdfPermissionOverride(reader)).toBe(bypass);+ for (const flag of [+ PdfPermissionFlag.Print,+ PdfPermissionFlag.PrintHighQuality,+ PdfPermissionFlag.CopyContents,+ PdfPermissionFlag.ModifyContents,+ PdfPermissionFlag.ModifyAnnotations,+ PdfPermissionFlag.FillForms,+ PdfPermissionFlag.AssembleDocument,+ PdfPermissionFlag.ExtractForAccessibility,+ ]) {+ expect(pdfAllows(reader, flag)).toBe(bypass);+ }+ expect(+ await preflightPdfOperation([file], rotate, false, requestOwner),+ ).toBe(bypass);+ expect(+ await preflightPdfOperation(+ [file],+ "/api/v1/security/add-password",+ false,+ requestOwner,+ ),+ ).toBe(bypass);+ if (bypass) {+ expect(requestOwner).not.toHaveBeenCalled();+ expect(() => assertPdfSessionEditable(reader)).not.toThrow();+ } else {+ expect(requestOwner).toHaveBeenCalledTimes(2);+ expect(() => assertPdfSessionEditable(reader)).toThrow();+ }+ expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);+ expect(() =>+ assertPdfSessionEditable({ ...reader, signed: true }),+ ).toThrow();+ },+ );++ it("keeps removal selections separate from cached credentials in bypass mode", async () => {+ const file = new File(["encrypted"], "restricted.pdf");+ rememberPdfAccess(file, { ...access, honorOwnerPasswords: false });+ post.mockResolvedValue({ data: new Blob(["result"]) });+ const form = new FormData();+ form.set("password", "");+ form.set("ownerPassword", "selected-owner");+ await changePdfSecurity(file, form, "/api/v1/security/remove-password");+ expect(form.get("password")).toBe("");+ 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(getPdfAccess(file)?.ownerAuthenticated).toBe(false);+ });++ it("retains the opening credential after separately authenticating the owner", () => {+ const file = new File(["encrypted"], "restricted.pdf");+ rememberPdfAccess(file, { ...access, openingAuthenticated: true });+ expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);+ rememberPdfAccess(file, {+ ...access,+ password: "owner",+ ownerAuthenticated: true,+ openingAuthenticated: false,+ });+ expect(getPdfAccess(file)?.openingPassword).toBe(access.password);+ expect(getPdfAccess(file)?.password).toBe("owner");+ });++ it("does not infer removal from a cached owner credential or request an unrelated owner prompt", async () => {+ const file = createStirlingFile(new File(["encrypted"], "restricted.pdf"));+ rememberPdfAccess(file, { ...access, ownerAuthenticated: true });+ const requestOwner = vi.fn();+ expect(+ await preflightPdfOperation(+ [file],+ "/api/v1/security/remove-password",+ false,+ requestOwner,+ ),+ ).toBe(true);+ expect(requestOwner).not.toHaveBeenCalled();+ post.mockResolvedValue({ data: new Blob(["result"]) });+ const form = new FormData();+ form.set("password", "selected-opening");+ await changePdfSecurity(file, form, "/api/v1/security/remove-password");+ expect(form.get("password")).toBe("selected-opening");+ expect(form.has("ownerPassword")).toBe(false);+ });++ it("requests owner authority before a restricted operation and stops on cancellation", async () => {+ const file = createStirlingFile(new File(["encrypted"], "restricted.pdf"));+ rememberPdfAccess(file, { ...access, permissions: 0 });+ const requestOwner = vi.fn().mockResolvedValue(false);+ expect(+ await preflightPdfOperation([file], rotate, false, requestOwner),+ ).toBe(false);+ expect(requestOwner).toHaveBeenCalledWith(file);+ expect(post).not.toHaveBeenCalled();+ requestOwner.mockImplementation(async () => {+ rememberPdfAccess(file, { ...access, ownerAuthenticated: true });+ return true;+ });+ expect(+ await preflightPdfOperation([file], rotate, false, requestOwner),+ ).toBe(true);+ });++ it("rejects an unsupported tool or protected merge before asking for a password", async () => {+ const files = ["first", "second"].map((name) =>+ createStirlingFile(new File(["encrypted"], `${name}.pdf`)),+ );+ files.forEach((file) =>+ rememberPdfAccess(file, { ...access, permissions: 0 }),+ );+ const requestOwner = vi.fn();+ await expect(+ preflightPdfOperation(+ files,+ "/api/v1/security/auto-redact",+ false,+ requestOwner,+ ),+ ).rejects.toThrow("cannot yet preserve");+ await expect(+ preflightPdfOperation(+ files,+ "/api/v1/general/merge-pdfs",+ true,+ requestOwner,+ ),+ ).rejects.toThrow("Process them individually");+ expect(requestOwner).not.toHaveBeenCalled();+ expect(post).not.toHaveBeenCalled();+ });++ it("changes permissions in place using the verified owner rather than requiring a new owner password", async () => {+ const file = new File(["encrypted"], "restricted.pdf");+ rememberPdfAccess(file, { ...access, ownerAuthenticated: true });+ post.mockResolvedValue({ data: new Blob(["protected result"]) });+ 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(form.get("sourcePassword")).toBe(access.password);+ expect(form.has("ownerPassword")).toBe(false);+ });++ it("reuses verified owner access for opening-password removal", async () => {+ const file = new File(["encrypted"], "restricted.pdf");+ rememberPdfAccess(file, { ...access, ownerAuthenticated: true });+ post.mockResolvedValue({ data: new Blob(["result"]) });+ const form = new FormData();+ 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");+ });it("authenticates without rewriting bytes or retaining credentials before adoption", async () => {const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));const { password, ...info } = access;@@ -96,6 +319,8 @@ describe("session PDF access", () => {{ 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 } });@@ -109,7 +334,10 @@ describe("session PDF access", () => {const output = new File(["export"], "edited.pdf");post.mockResolvedValueOnce({ data: access });await verifyEditedPdfProtection(output, access);- expect(getPdfAccess(output)).toEqual(access);+ expect(getPdfAccess(output)).toEqual({+ ...access,+ openingPassword: access.password,+ });await expect(verifyEditedPdfProtection(output, { ...access, signed: true }),).rejects.toThrow("digital signatures");@@ -135,7 +363,10 @@ describe("session PDF access", () => {const first = createStirlingFile(new File(["one"], "locked.pdf"));const second = createStirlingFile(new File(["two"], "locked.pdf"));rememberPdfAccess(first, access);- expect(getPdfAccess(first.fileId)).toEqual(access);+ expect(getPdfAccess(first.fileId)).toEqual({+ ...access,+ openingPassword: access.password,+ });expect(getPdfAccess(second)).toBeUndefined();expect(Object.keys(first)).not.toContain("password");forgetPdfAccess([first.fileId]);@@ -151,7 +382,10 @@ describe("session PDF access", () => {expect(working).not.toBe(original);expect(working.name).toBe(original.name);expect(getPdfAccess(working)).toBeUndefined();- expect(getPdfAccess(original.fileId)).toEqual(access);+ expect(getPdfAccess(original.fileId)).toEqual({+ ...access,+ openingPassword: access.password,+ });});it("requires a fresh unlock when different bytes replace an existing file identity", () => {@@ -167,9 +401,13 @@ describe("session PDF access", () => {});it.each([- ["/api/v1/security/auto-redact", access, "does not yet support"],+ ["/api/v1/security/auto-redact", access, "cannot yet preserve"],[rotate, { ...access, signed: true }, "digital signatures"],- [rotate, { ...access, canAssemble: false }, "restricts"],+ [+ rotate,+ { ...access, canAssemble: false, permissions: -4 & ~1024 },+ "permissions password",+ ],])("rejects unsupported or restricted processing before decrypting",async (endpoint, permission, message) => {@@ -184,7 +422,7 @@ describe("session PDF access", () => {},);- it("decrypts a mixed-password merge independently and inherits its first protected input", async () => {+ it("rejects mixed protected inputs without admitting an output", async () => {const first = createStirlingFile(new File(["a"], "first.pdf"));const second = createStirlingFile(new File(["b"], "second.pdf"));rememberPdfAccess(first, access);@@ -193,21 +431,14 @@ describe("session PDF access", () => {const merge = "/api/v1/general/merge-pdfs";await prepareUnlockedFile(first, merge);await prepareUnlockedFile(second, merge);- const [result] = await protectUnlockedResults(- [new File(["merged"], "merged.pdf")],- [first, second],- merge,- );- expect((post.mock.calls[0][1] as FormData).get("password")).toBe(- access.password,- );- expect((post.mock.calls[1][1] as FormData).get("password")).toBe(- "second-password",- );- const restore = post.mock.calls[2][1] as FormData;- expect(restore.get("sourceFile")).toBe(first);- expect(restore.get("password")).toBe(access.password);- expect(getPdfAccess(result)).toEqual(access);+ await expect(+ protectUnlockedResults(+ [new File(["merged"], "merged.pdf")],+ [first, second],+ merge,+ ),+ ).rejects.toThrow("output protection policy");+ expect(post).toHaveBeenCalledTimes(2);});it("returns no partial output if protection restoration fails", async () => {diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.ts b/frontend/editor/src/core/services/pdfSessionUnlock.tsindex 3bb66920d0..5af138193f 100644--- a/frontend/editor/src/core/services/pdfSessionUnlock.ts+++ b/frontend/editor/src/core/services/pdfSessionUnlock.ts@@ -1,5 +1,5 @@import apiClient from "@app/services/apiClient";-import axios from "axios";+import axios, { type CancelToken } from "axios";import i18n from "i18next";import {getPdfAccess,@@ -7,9 +7,53 @@ import {type PdfAccess,} from "@app/services/pdfPasswordStore";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)!;+}+const SUPPORTED_ENDPOINTS = new Set([+ "/api/v1/security/add-password",+ "/api/v1/security/remove-password","/api/v1/general/rotate-pdf","/api/v1/general/remove-pages","/api/v1/general/rearrange-pages",@@ -27,16 +71,21 @@ async function requestWorkingPdf(endpoint: string,form: FormData,message: string,+ cancelToken?: CancelToken,): Promise<Blob> {try {const response = await apiClient.post<Blob>(endpoint, form, {responseType: "blob",suppressErrorToast: true,+ cancelToken,});return response.data;- } catch {+ } catch (error) {// Axios errors carry the password-bearing request form into tool logs and failure history.- throw new Error(message);+ const sanitized = axios.isCancel(error)+ ? new axios.CanceledError("Operation cancelled")+ : new Error(message);+ throw sanitized;}}@@ -45,10 +94,65 @@ export function supportsSessionUnlock(endpoint: string | undefined): boolean {return endpoint !== undefined && SUPPORTED_ENDPOINTS.has(endpoint);}+/** Checks the whole selection before processing or prompting for credentials. */+export async function preflightPdfOperation(+ files: readonly StirlingFile[],+ endpoint: string | undefined,+ combinesFiles: boolean,+ requestOwner: (file: StirlingFile) => Promise<boolean>,+): Promise<boolean> {+ const protectedFiles: StirlingFile[] = [];+ for (const file of files) {+ if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)) continue;+ const access = await ensurePdfAccess(file);+ if (!access.encrypted) continue;+ if (!supportsSessionUnlock(endpoint))+ throw new Error(+ i18n.t(+ "encryptedPdfUnlock.unsupportedTool",+ "This tool cannot yet preserve this PDF's protection.",+ ),+ );+ if (access.signed)+ throw new Error(+ i18n.t(+ "encryptedPdfUnlock.signedReadOnly",+ "This signed PDF can be viewed, but cannot be edited here.",+ ),+ );+ protectedFiles.push(file);+ }+ if (combinesFiles && protectedFiles.length > 1)+ throw new Error(+ i18n.t(+ "encryptedPdfUnlock.mixedProtection",+ "These PDFs have separate protection settings. Process them individually.",+ ),+ );+ for (const file of protectedFiles) {+ if (endpoint === "/api/v1/security/remove-password") continue;+ const access = getPdfAccess(file)!;+ const needsOwner = endpoint?.includes("password")+ ? !hasPdfPermissionOverride(access)+ : !pdfAllows(access, operationPermission(endpoint));+ if (needsOwner && !(await requestOwner(file))) return false;+ }+ return true;+}++function operationPermission(endpoint: string | undefined): PdfPermissionFlag {+ return endpoint === "/api/v1/misc/compress-pdf"+ ? PdfPermissionFlag.ModifyContents+ : endpoint?.includes("split")+ ? PdfPermissionFlag.CopyContents+ : 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);@@ -57,10 +161,22 @@ export async function unlockPdfForSession(const response = await apiClient.post<Omit<PdfAccess, "password">>("/api/v1/security/inspect-pdf-security",form,- { suppressErrorToast: true },+ {+ 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.",);@@ -79,7 +195,9 @@ export async function unlockPdfForSession(/** Signed protected PDFs remain view-only until their edits can preserve signatures. */export function assertPdfSessionEditable(- access: Pick<PdfAccess, "encrypted" | "signed"> | undefined,+ access:+ | (Pick<PdfAccess, "encrypted" | "signed"> & Partial<PdfAccess>)+ | undefined,): void {if (access?.encrypted && access.signed)throw new Error(@@ -88,6 +206,17 @@ 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+ )+ throw new Error(+ i18n.t(+ "encryptedPdfUnlock.restrictedOperation",+ "This action requires the permissions password.",+ ),+ );}/** Native exports must retain source protection before storage or download can receive them. */@@ -105,7 +234,9 @@ export async function verifyEditedPdfProtection(sourceAccess.encryptionKeyLength === undefined ||access.encryptionKeyLength !== sourceAccess.encryptionKeyLength ||sourceAccess.encryptionRevision === undefined ||- access.encryptionRevision !== sourceAccess.encryptionRevision+ access.encryptionRevision !== sourceAccess.encryptionRevision ||+ !sourceAccess.credentialFingerprint ||+ access.credentialFingerprint !== sourceAccess.credentialFingerprint)throw new Error(i18n.t(@@ -113,7 +244,10 @@ export async function verifyEditedPdfProtection("Unable to preserve PDF protection. No unprotected result was saved.",),);- rememberPdfAccess(output, access);+ rememberPdfAccess(output, {+ ...access,+ openingPassword: sourceAccess.openingPassword,+ });}/** Decrypted bytes belong only to this operation. They must never enter FileContext or persistence. */@@ -121,14 +255,20 @@ export async function prepareUnlockedFile(file: StirlingFile,endpoint: string | undefined,): Promise<File> {- const access = getPdfAccess(file);- if (!access?.encrypted || endpoint === "/api/v1/security/remove-password")+ if (+ endpoint === "/api/v1/security/remove-password" ||+ endpoint === "/api/v1/security/add-password"+ )+ return file;+ if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name))return file;+ const access = await ensurePdfAccess(file);+ if (!access.encrypted) return file;if (!supportsSessionUnlock(endpoint))throw new Error(i18n.t("encryptedPdfUnlock.unsupportedTool",- "This tool does not yet support session-unlocked PDFs. Use Remove Password explicitly to create an unprotected copy.",+ "This tool cannot yet preserve this document's protection.",),);if (access.signed)@@ -138,22 +278,20 @@ export async function prepareUnlockedFile("This PDF has digital signatures. Session unlocking supports viewing it, but processing signed PDFs is not supported yet.",),);- const permitted =- endpoint === "/api/v1/misc/compress-pdf"- ? access.canModify- : access.canAssemble;- if (!access.ownerAuthenticated && !permitted)+ const permission = operationPermission(endpoint);+ if (!pdfAllows(access, permission))throw new Error(i18n.t("encryptedPdfUnlock.restrictedOperation",- "This PDF restricts this operation. Reopen it with the owner password to continue.",+ "This action requires the permissions password.",),);const form = new FormData();form.append("fileInput", file);form.append("password", access.password);+ form.append("endpoint", endpoint!);const bytes = await requestWorkingPdf(- "/api/v1/security/remove-password",+ "/api/v1/security/prepare-pdf-session",form,i18n.t("encryptedPdfUnlock.prepareFailed",@@ -196,13 +334,24 @@ async function protectPdfOutput(return file;}-/** Restore protection before results reach downloads or storage, including every PDF in a ZIP. Merges inherit the first protected input. */+/** Restore protection before results reach downloads or storage, including every PDF in a ZIP; mixed protected inputs are unsupported. */export async function protectUnlockedResults(outputs: File[],inputs: readonly File[],endpoint: string | undefined,): Promise<File[]> {- if (endpoint === "/api/v1/security/remove-password") return outputs;+ if (+ endpoint === "/api/v1/security/remove-password" ||+ endpoint === "/api/v1/security/add-password"+ )+ return outputs;+ if (inputs.filter((file) => getPdfAccess(file)?.encrypted).length > 1)+ throw new Error(+ i18n.t(+ "encryptedPdfUnlock.mixedProtection",+ "Combining multiple protected documents requires choosing an output protection policy. Process them separately for now.",+ ),+ );const source = inputs.find((file) => getPdfAccess(file)?.encrypted);if (!source) return outputs;const access = getPdfAccess(source)!;@@ -232,3 +381,60 @@ export async function protectUnlockedResults(}return protectedFiles;}++/** Interactive security changes use stricter contracts than the legacy public API. */+export async function changePdfSecurity(+ file: File,+ form: FormData,+ endpoint: string,+ cancelToken?: CancelToken,+): Promise<Blob> {+ const settingProtection = endpoint === "/api/v1/security/add-password";+ if (settingProtection) {+ const access = await ensurePdfAccess(file);+ 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);+ if (!form.has("keyLength")) {+ form.delete("password");+ 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.openingPassword === undefined+ ) {+ throw new Error(+ i18n.t(+ "removePassword.openWithReaderFirst",+ "Reopen this PDF using its opening password before removing only the permissions password.",+ ),+ );+ }+ form.set("sourcePassword", access.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",+ form,+ i18n.t(+ "encryptedPdfUnlock.securityChangeFailed",+ "Unable to change protection. Check the permissions password and the new security settings.",+ ),+ cancelToken,+ );+}diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsxindex 4f529800d5..d5039ecfdf 100644--- a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx@@ -35,6 +35,7 @@ import { defaultParameters as compressParameters } from "@app/hooks/tools/compreimport {rememberPdfAccess,clearPdfAccess,+ forgetPdfAccess,} from "@app/services/pdfPasswordStore";const workspace = {@@ -205,6 +206,7 @@ beforeEach(() => {describe("tool file selection", () => {test("explains why an unlocked protected PDF is excluded", async () => {workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };+ act(() => forgetPdfAccess([workspace.files[0].fileId]));rememberPdfAccess(workspace.files[0], {password: "secret",encrypted: true,@@ -241,7 +243,7 @@ describe("tool file selection", () => {});act(() => removePassword.focus());const help = await screen.findByText(- "Open Remove Password to create an unprotected copy.",+ "Open Remove Password to choose which passwords to remove.",);await waitFor(() => expect(help).toBeVisible());await userEvent.click(removePassword);@@ -349,11 +351,14 @@ describe("tool file selection", () => {screen.queryByRole("button", { name: "Sort" }),).not.toBeInTheDocument();- const secondPdf = createTestStirlingFile(- "second.pdf",- "pdf",- "application/pdf",- );+ let secondPdf!: StirlingFile;+ act(() => {+ secondPdf = createTestStirlingFile(+ "second.pdf",+ "pdf",+ "application/pdf",+ );+ });const secondStub = createNewStirlingFileStub(secondPdf, secondPdf.fileId);workspace.files.push(secondPdf);workspace.fileStubs.push(secondStub);@@ -365,6 +370,7 @@ describe("tool file selection", () => {expect(screen.getByRole("button", { name: "Sort" })).toBeEnabled();secondStub.processedFile = { pages: [], isEncrypted: true };+ act(() => forgetPdfAccess([secondPdf.fileId]));view.rerender(renderMerge());expect(screen.getByRole("button", { name: /Merge PDFs/ })).toBeDisabled();expect(@@ -426,6 +432,7 @@ describe("tool file selection", () => {expect(onFileClick).toHaveBeenCalledWith(workspace.files[1].fileId);workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };+ act(() => forgetPdfAccess([workspace.files[0].fileId]));view.rerender(renderTool(<Compress />));expect(pdf).toHaveAttribute("data-tool-skipped", "true");workspace.fileStubs[0].processedFile.isEncrypted = false;@@ -478,6 +485,7 @@ describe("tool file selection", () => {expect(screen.getByRole("button", { name: "Compress" })).toBeEnabled();workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };+ act(() => forgetPdfAccess([workspace.files[0].fileId]));view.rerender(<MantineProvider><Compress />diff --git a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsxindex 2991312aa6..35e5b392d9 100644--- a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx+++ b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx@@ -49,19 +49,6 @@ import {} from "@app/types/fileContext";import { MantineProvider } from "@mantine/core";-// Mock axios (for static methods like CancelToken, isCancel)-vi.mock("axios", () => ({- default: {- CancelToken: {- source: vi.fn(() => ({- token: "mock-cancel-token",- cancel: vi.fn(),- })),- },- isCancel: vi.fn(() => false),- },-}));-// Mock our apiClient servicevi.mock("../../services/apiClient", () => ({default: {@@ -232,6 +219,17 @@ describe("Convert Tool Integration Tests", () => {});test("filters mixed inputs using current params and protection without consuming skipped files", async () => {+ const thumbnail = {+ thumbnail: "data:image/png;base64,fake-thumbnail",+ pageCount: 1,+ };+ vi.spyOn(+ thumbnailUtils,+ "generateThumbnailPairWithMetadata",+ ).mockResolvedValue({ unrotated: thumbnail, rotated: thumbnail });+ vi.spyOn(thumbnailUtils, "generateThumbnailForFile").mockResolvedValue(+ thumbnail.thumbnail,+ );mockedApiClient.post.mockResolvedValue({data: new Blob(["output"]),headers: {},@@ -334,19 +332,35 @@ describe("Convert Tool Integration Tests", () => {expect(fileStorage.persistVersionedOutputs).toHaveBeenCalledTimes(2);expect(result.current.convert.errorMessage).toBe("noValidFiles");+ 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,+ },+ });await act(async () => {await result.current.unlock.executeOperation({ password: "secret" }, [image,locked,]);});- expect(mockedApiClient.post).toHaveBeenCalledTimes(3);+ expect(mockedApiClient.post).toHaveBeenCalledTimes(4);expect(mockedApiClient.post.mock.calls[2][0]).toBe(- "/api/v1/security/remove-password",+ "/api/v1/security/remove-pdf-passwords",);expect((mockedApiClient.post.mock.calls[2][1] as FormData).get("password"),).toBe("secret");+ expect(+ (mockedApiClient.post.mock.calls[2][1] as FormData).get("sourcePassword"),+ ).toBe("test");expect((mockedApiClient.post.mock.calls[2][1] as FormData).getAll("fileInput"),).toEqual([locked]);diff --git a/frontend/editor/src/core/tests/helpers/api-stubs.ts b/frontend/editor/src/core/tests/helpers/api-stubs.tsindex 150bbbc99b..fcf95f9626 100644--- a/frontend/editor/src/core/tests/helpers/api-stubs.ts+++ b/frontend/editor/src/core/tests/helpers/api-stubs.ts@@ -169,6 +169,19 @@ 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/live-api.ts b/frontend/editor/src/core/tests/helpers/live-api.tsnew file mode 100644index 0000000000..a4dd3a06e4--- /dev/null+++ b/frontend/editor/src/core/tests/helpers/live-api.ts@@ -0,0 +1,31 @@+import { expect, type Page } from "@playwright/test";+import { login, skipOnboarding } from "@app/tests/helpers/login";+import type { AppConfig } from "@app/types/appConfig";++/** Playwright's request client does not inherit the app's localStorage bearer token. */+export async function liveApiHeaders(+ page: Page,+): Promise<Record<string, string>> {+ if (page.url() === "about:blank") return {};+ const token = await page.evaluate(() => localStorage.getItem("stirling_jwt"));+ return token ? { Authorization: `Bearer ${token}` } : {};+}++/** Authenticate when required, while supporting local servers with login disabled. */+export async function loadLiveAppConfig(page: Page): Promise<AppConfig> {+ await skipOnboarding(page);+ let response = await page.request.get("/api/v1/config/app-config");+ if (+ response.status() === 401 ||+ (response.ok() && (await response.json()).enableLogin)+ ) {+ await login(page);+ response = await page.request.get("/api/v1/config/app-config", {+ headers: await liveApiHeaders(page),+ });+ }+ expect(response.ok(), `App config returned HTTP ${response.status()}`).toBe(+ true,+ );+ return response.json();+}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.tsnew file mode 100644index 0000000000..d632dc71f5--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-owner-policy.spec.ts@@ -0,0 +1,319 @@+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/promises";++const fixtures = path.join(import.meta.dirname, "../test-fixtures");+const owner = "policy-original-owner";+const replacement = "policy-replacement-owner";+const opening = "policy-opening-password";++test.beforeEach(async ({ page }) => {+ const config = await loadLiveAppConfig(page);+ test.skip(+ config.honorOwnerPasswords !== false,+ "Run against a server with SECURITY_HONOROWNERPASSWORDS=false",+ );+});++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,+ },+ },+ );+ 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({+ name: "restricted.pdf",+ mimeType: "application/pdf",+ buffer,+ });+}++test("ignored restrictions allow actual printing and copying without claiming owner verification", async ({+ page,+}) => {+ const original = await protect(page);+ expect(await inspect(page, original)).toMatchObject({+ honorOwnerPasswords: false,+ ownerAuthenticated: false,+ canPrint: false,+ canModify: false,+ canExtract: false,+ });+ await upload(page, original);+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(+ page.getByRole("button", {+ name: "Verify permissions for this session",+ exact: true,+ }),+ ).toHaveCount(0);+ await page+ .getByRole("button", { name: "Printing restriction ignored", exact: true })+ .hover();+ await expect(page.getByRole("tooltip")).toHaveText(+ "Permissions are ignored by this server's settings. The PDF's protection is unchanged.",+ );+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Close", exact: true })+ .click();+ await page.getByRole("button", { name: "Print PDF", exact: true }).click();+ const printFrame = page.locator('iframe[title="Print Document"]');+ await expect(printFrame).toHaveAttribute("src", /^blob:/);+ const printUrl = await printFrame.getAttribute("src");+ const printBytes = await page.evaluate(+ async (url) =>+ Array.from(new Uint8Array(await (await fetch(url!)).arrayBuffer())),+ printUrl,+ );+ expect(await inspect(page, Buffer.from(printBytes))).toMatchObject({+ encrypted: false,+ pageCount: 1,+ });+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+ await page.evaluate(() =>+ navigator.clipboard.writeText("policy-test-marker"),+ );+ const pdfPage = page.locator('[data-page-index="0"]').first();+ const copy = page.getByRole("button", { name: "Copy", exact: true });+ await expect(async () => {+ const bounds = await pdfPage.boundingBox();+ expect(bounds).not.toBeNull();+ await pdfPage.click({+ button: "right",+ position: { x: bounds!.width * 0.21, y: bounds!.height * 0.105 },+ });+ await expect(copy).toBeVisible({ timeout: 1000 });+ }).toPass();+ await expect(copy).toBeEnabled();+ await copy.click();+ await expect+ .poll(() => page.evaluate(() => navigator.clipboard.readText()))+ .not.toBe("policy-test-marker");+ expect(+ (await page.evaluate(() => navigator.clipboard.readText())).trim(),+ ).not.toBe("");+});++test("unprotected copy needs no owner password when enforcement is disabled", async ({+ page,+}) => {+ await upload(page, await protect(page));+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ const response = page.waitForResponse(+ "**/api/v1/security/remove-pdf-protection",+ );+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ const result = await response;+ expect(result.ok()).toBe(true);+ expect(await inspect(page, await result.body())).toMatchObject({+ encrypted: false,+ });+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled();+});++test("restricted rotation preserves the original protection without owner authentication", async ({+ page,+}) => {+ const original = await protect(page);+ const originalAccess = await inspect(page, original);+ await upload(page, original, "/rotate");+ const response = page.waitForResponse(+ "**/api/v1/security/restore-pdf-protection",+ );+ await page+ .getByRole("button", { name: /^Apply Rotation(?: \(this file\))?$/ })+ .click();+ const result = await response;+ expect(result.ok()).toBe(true);+ const saved = await result.body();+ expect(await inspect(page, saved)).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ permissions: originalAccess.permissions,+ credentialFingerprint: originalAccess.credentialFingerprint,+ });+ expect(await inspect(page, saved, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protection retained", { exact: true }),+ ).toBeVisible();+});++test("changing restrictions preserves the unknown owner password unless replacement is selected", async ({+ page,+}) => {+ await upload(page, await protect(page), "/change-permissions");+ await page+ .getByRole("checkbox", { name: "Change permissions password", exact: true })+ .check();+ await page+ .getByRole("textbox", { name: "New permissions password", exact: true })+ .fill(replacement);+ await page+ .getByRole("checkbox", { name: "Prevent printing", exact: true })+ .uncheck();+ const response = page.waitForResponse(+ "**/api/v1/security/change-pdf-permissions",+ );+ await page+ .getByRole("button", { name: /^Change Permissions(?: \(this file\))?$/ })+ .click();+ const result = await response;+ expect(result.ok()).toBe(true);+ const saved = await result.body();+ expect(await inspect(page, saved)).toMatchObject({+ canPrint: true,+ ownerAuthenticated: false,+ });+ expect(await inspect(page, saved, replacement)).toMatchObject({+ ownerAuthenticated: true,+ });+});++test("removing an opening password retains the blank owner field even when enforcement is off", async ({+ page,+}) => {+ const original = await protect(page, opening);+ await upload(page, original, "/remove-password");+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });+ await expect(dialog).toBeVisible();+ await dialog.getByLabel("Password to open", { exact: true }).fill("wrong");+ await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();+ await expect(+ dialog.getByText("Incorrect password", { exact: true }),+ ).toBeVisible();+ await dialog.getByLabel("Password to open", { exact: true }).fill(opening);+ 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",+ );+ 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(owner);+ await verification+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ const result = await response;+ expect(result.ok()).toBe(true);+ const saved = await result.body();+ expect(await inspect(page, saved)).toMatchObject({+ encrypted: true,+ requiresOpeningPassword: false,+ canPrint: false,+ ownerAuthenticated: false,+ });+ expect(await inspect(page, saved, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+});++test("text editing bypass retains encryption and the original credentials in the saved PDF", async ({+ page,+}) => {+ const original = await fs.readFile(+ path.join(fixtures, "owner-only-restricted.pdf"),+ );+ const originalAccess = await inspect(page, original);+ await page.goto("/pdf-text-editor");+ await page.getByTestId("pdf-editor-file-input").setInputFiles({+ name: "restricted.pdf",+ mimeType: "application/pdf",+ buffer: original,+ });+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();+ await page+ .locator('[data-testid^="pdf-editor-run-"][contenteditable="true"]')+ .first()+ .fill("Editing with owner restrictions ignored");+ await page.getByTestId("pdf-editor-download").click();+ const downloadPromise = page.waitForEvent("download");+ await page.getByTestId("pdf-editor-save-risk-confirm").click();+ const download = await downloadPromise;+ const savedPath = test.info().outputPath("edited.pdf");+ await download.saveAs(savedPath);+ const saved = await fs.readFile(savedPath);+ expect(await inspect(page, saved)).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ canModify: false,+ permissions: originalAccess.permissions,+ credentialFingerprint: originalAccess.credentialFingerprint,+ });+ 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.tsnew file mode 100644index 0000000000..1d9fb728eb--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-password-removal.spec.ts@@ -0,0 +1,490 @@+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";++const reader = "removal-reader";+const owner = "removal-owner";+const fixture = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");++test.beforeEach(async ({ page }) => {+ await loadLiveAppConfig(page);+});++async function protectedPdf(+ page: Page,+ 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", {+ headers: await liveApiHeaders(page),+ multipart: {+ fileInput: { name: "result.pdf", mimeType: "application/pdf", buffer },+ password,+ },+ });+}++async function upload(page: Page, buffer: Buffer, opening = true) {+ await page.goto("/remove-password");+ await page.getByTestId("file-input").setInputFiles({+ name: "removal-test.pdf",+ mimeType: "application/pdf",+ buffer,+ });+ if (opening) {+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });+ await dialog.getByLabel("Password to open", { exact: true }).fill(reader);+ await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();+ await expect(dialog).toBeHidden();+ }+ await expect(+ page.getByText("Leave a field blank to keep that password."),+ ).toBeVisible();+}++for (const permissions of [false, true]) {+ test(`load-time removal keeps separate owner protection: ${permissions}`, async ({+ page,+ }) => {+ const original = await protectedPdf(page, true, permissions);+ await page.goto("/editor");+ await page.getByTestId("file-input").setInputFiles({+ name: "load-time.pdf",+ mimeType: "application/pdf",+ buffer: original,+ });+ const dialog = page.getByRole("dialog");+ const remove = dialog.getByRole("button", {+ name: "Remove Password",+ exact: true,+ });+ const open = dialog.getByRole("button", { name: "Open PDF", exact: true });+ await expect(remove).toBeDisabled();+ await expect(+ dialog.getByRole("button", { name: "Cancel", exact: true }),+ ).toHaveCount(0);+ await expect(+ dialog.getByRole("button", { name: "Close", exact: true }),+ ).toBeVisible();+ await expect+ .poll(async () => {+ const [removeBounds, openBounds] = await Promise.all([+ remove.boundingBox(),+ open.boundingBox(),+ ]);+ return Math.abs(removeBounds!.y - openBounds!.y);+ })+ .toBeLessThan(1);+ await dialog+ .getByLabel("Password to open", { exact: true })+ .fill("wrong-password");+ await remove.click();+ 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",+ );+ await remove.click();+ if (permissions) {+ await expect(+ dialog.getByRole("heading", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toBeVisible();+ await expect(dialog.getByText(/This will not remove it/)).toBeVisible();+ await expect(+ dialog.getByLabel("Permissions password", { exact: true }),+ ).toHaveValue("");+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(reader);+ await dialog+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ await expect(dialog.getByRole("alert")).toContainText(+ "Enter the permissions password",+ );+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ await dialog+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ }+ const response = await removalResponse;+ expect(response.ok()).toBe(true);+ const saved = await response.body();+ await expect(dialog).toBeHidden();+ await expect(+ 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({+ encrypted: permissions,+ requiresOpeningPassword: false,+ hasOwnerPassword: permissions,+ canPrint: !permissions,+ });+ if (permissions) {+ expect(+ (await (await inspect(page, saved, owner)).json()).ownerAuthenticated,+ ).toBe(true);+ }+ expect(+ (await (await inspect(page, original, reader)).json())+ .requiresOpeningPassword,+ ).toBe(true);+ });+}++test("closing load-time owner verification leaves the protected source unchanged", async ({+ page,+}) => {+ const original = await protectedPdf(page, true, true);+ let removals = 0;+ page.on("request", (request) => {+ if (request.url().endsWith("/remove-pdf-passwords")) removals++;+ });+ await page.goto("/editor");+ await page.getByTestId("file-input").setInputFiles({+ name: "cancel-removal.pdf",+ mimeType: "application/pdf",+ buffer: original,+ });+ const dialog = page.getByRole("dialog");+ await dialog.getByLabel("Password to open", { exact: true }).fill(reader);+ await dialog+ .getByRole("button", { name: "Remove Password", exact: true })+ .click();+ await expect(+ dialog.getByLabel("Permissions password", { exact: true }),+ ).toBeVisible();+ await dialog.getByRole("button", { name: "Close", exact: true }).click();+ 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);+});++for (const remove of ["opening", "owner", "both"] as const) {+ test(`removing ${remove} keeps every blank password and refreshes print access`, async ({+ page,+ }) => {+ const original = await protectedPdf(page, true, true);+ const honor =+ (await (await inspect(page, original, reader)).json())+ .honorOwnerPasswords !== false;+ await upload(page, original);+ const submit = page.getByRole("button", {+ name: /^Remove Password(?: \(this file\))?$/,+ });+ await expect(submit).toBeDisabled();+ await expect(+ page.getByLabel("Password to open", { exact: true }),+ ).toHaveValue("");+ await expect(+ page.getByLabel("Permissions password", { exact: true }),+ ).toHaveValue("");+ if (remove !== "owner")+ await page.getByLabel("Password to open", { exact: true }).fill(reader);+ if (remove !== "opening")+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ const responsePromise = page.waitForResponse(+ "**/api/v1/security/remove-pdf-passwords",+ );+ await submit.click();+ if (remove === "opening") {+ 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(owner);+ await verification+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ }+ const response = await responsePromise;+ expect(response.ok()).toBe(true);+ 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({+ 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();+ } 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(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled({ enabled: remove !== "opening" || !honor });+ if (remove !== "opening") {+ await page+ .getByRole("button", { name: "Print PDF", exact: true })+ .click();+ await expect(+ page.locator('iframe[title="Print Document"]'),+ ).toHaveAttribute("src", /^blob:/);+ }+ expect(+ (await (await inspect(page, original, reader)).json())+ .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 ({+ page,+ }) => {+ const original = await protectedPdf(+ page,+ only === "opening",+ only === "owner",+ );+ await upload(page, original, only === "opening");+ await expect(+ page.getByLabel("Password to open", { exact: true }),+ ).toBeEnabled({ enabled: only === "opening" });+ await expect(+ page.getByLabel("Permissions password", { exact: true }),+ ).toBeEnabled({ enabled: only === "owner" });+ 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",+ );+ 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);+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled();+ });+}++test("wrong role credentials cannot remove protection and cancelled verification leaves both fields unchanged", async ({+ page,+}) => {+ await upload(page, await protectedPdf(page, true, true));+ await page.getByLabel("Password to open", { exact: true }).fill(reader);+ await page+ .getByRole("button", { name: /^Remove Password(?: \(this file\))?$/ })+ .click();+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Close", exact: true })+ .click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByLabel("Password to open", { exact: true }),+ ).toHaveValue(reader);+ await expect(+ page.getByLabel("Permissions password", { exact: true }),+ ).toHaveValue("");+ await page.getByLabel("Permissions password", { exact: true }).fill(reader);+ const responsePromise = page.waitForResponse(+ "**/api/v1/security/remove-pdf-passwords",+ );+ await page+ .getByRole("button", { name: /^Remove Password(?: \(this file\))?$/ })+ .click();+ expect((await responsePromise).ok()).toBe(false);+ await expect(page.getByText("Protected PDF", { exact: true })).toBeVisible();+});++for (const remove of ["opening", "owner", "both"] as const) {+ test(`mixed selections remove ${remove} passwords only where set`, async ({+ page,+ }) => {+ const inputs = [+ {+ name: "opening-only.pdf",+ buffer: await protectedPdf(page, true, false),+ },+ { name: "owner-only.pdf", buffer: await protectedPdf(page, false, true) },+ {+ name: "both-passwords.pdf",+ buffer: await protectedPdf(page, true, true),+ },+ { name: "plain.pdf", buffer: await fs.readFile(fixture) },+ ];+ await page.goto("/remove-password");+ await page+ .getByTestId("file-input")+ .setInputFiles(+ inputs.map((file) => ({ ...file, mimeType: "application/pdf" })),+ );+ const openingDialog = page.getByRole("dialog", { name: /^Open PDF/ });+ await openingDialog+ .getByLabel("Password to open", { exact: true })+ .fill(reader);+ await openingDialog.getByRole("button", { name: /Use for all/ }).click();+ await expect(openingDialog).toBeHidden();+ await page+ .locator("label")+ .filter({ hasText: /^Active Files$/ })+ .click();+ await expect(+ page.getByText("Set on 2 of 4 PDFs", { exact: true }),+ ).toHaveCount(2);+ const openingInput = page.getByLabel("Password to open", { exact: true });+ const ownerInput = page.getByLabel("Permissions password", { exact: true });+ await expect(openingInput).toBeEnabled();+ await expect(ownerInput).toBeEnabled();+ if (remove !== "owner") await openingInput.fill(reader);+ if (remove !== "opening") await ownerInput.fill(owner);+ const responses: Response[] = [];+ page.on("response", (response) => {+ if (response.url().endsWith("/remove-pdf-passwords"))+ responses.push(response);+ });+ await page.getByRole("button", { name: /^Remove Password/ }).click();+ if (remove === "opening") {+ const verification = page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ });+ await expect(+ verification.getByText("both-passwords.pdf", { exact: true }),+ ).toBeVisible();+ await verification+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ await verification+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ }+ await expect(+ page.getByText(+ "Entered passwords removed where set. Blank fields kept unchanged.",+ ),+ ).toBeVisible();+ expect(responses).toHaveLength(remove === "both" ? 3 : 2);+ const protection = [];+ for (const response of responses) {+ expect(response.ok()).toBe(true);+ const buffer = await response.body();+ const inspection = 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,+ hasOwnerPassword: result.hasOwnerPassword,+ canPrint: result.canPrint,+ });+ if (result.hasOwnerPassword)+ expect(+ (await (await inspect(page, buffer, owner)).json())+ .ownerAuthenticated,+ ).toBe(true);+ }+ const unprotected = {+ encrypted: false,+ requiresOpeningPassword: false,+ hasOwnerPassword: false,+ canPrint: true,+ };+ expect(protection.filter((result) => !result.encrypted)).toEqual(+ remove === "both"+ ? [unprotected, unprotected, unprotected]+ : [unprotected],+ );+ if (remove !== "both")+ expect(protection.filter((result) => result.encrypted)).toEqual([+ {+ encrypted: true,+ requiresOpeningPassword: remove === "owner",+ hasOwnerPassword: remove === "opening",+ canPrint: remove === "owner",+ },+ ]);+ await expect(+ page+ .getByTestId("file-thumbnail")+ .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();+ });+}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.tsnew file mode 100644index 0000000000..d53004eaaa--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-permissions-matrix.spec.ts@@ -0,0 +1,309 @@+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";+import type { BrowserContext, Page } from "@playwright/test";+import { PdfPermissionFlag } from "@embedpdf/models";+import path from "node:path";++const fixtures = path.join(import.meta.dirname, "../test-fixtures");+const owner = "matrix-owner-password";+const restrictions = [+ {+ label: "Prevent assembly of document",+ bit: PdfPermissionFlag.AssembleDocument,+ endpoint: "/api/v1/general/rotate-pdf",+ },+ {+ label: "Prevent content extraction",+ bit: PdfPermissionFlag.CopyContents,+ endpoint: "/api/v1/general/split-pages",+ },+ {+ label: "Prevent extraction for accessibility",+ bit: PdfPermissionFlag.ExtractForAccessibility,+ },+ { label: "Prevent filling in form", bit: PdfPermissionFlag.FillForms },+ {+ label: "Prevent modification",+ bit: PdfPermissionFlag.ModifyContents,+ endpoint: "/api/v1/misc/compress-pdf",+ },+ {+ label: "Prevent annotation modification",+ bit: PdfPermissionFlag.ModifyAnnotations,+ },+ { label: "Prevent printing", bit: PdfPermissionFlag.Print },+ {+ label: "Prevent high-quality printing",+ bit: PdfPermissionFlag.PrintHighQuality,+ },+] as const;++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,+ name: string,+ contexts: BrowserContext[],+) {+ const context = await source+ .context()+ .browser()!+ .newContext({+ baseURL: new URL(source.url()).origin,+ storageState: await source.context().storageState(),+ viewport: source.viewportSize() ?? undefined,+ });+ contexts.push(context);+ const page = await context.newPage();+ await skipOnboarding(page);+ await page.goto("/change-permissions");+ await page+ .getByTestId("file-input")+ .setInputFiles({ name, mimeType: "application/pdf", buffer });+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+ await expect(page.getByText("Protected PDF", { exact: true })).toBeVisible();+ return page;+}++async function assertPrintOutput(page: Page) {+ await page.getByRole("button", { name: "Print PDF", exact: true }).click();+ const frame = page.locator('iframe[title="Print Document"]');+ await expect(frame).toHaveAttribute("src", /^blob:/);+ const source = await frame.getAttribute("src");+ const bytes = await page.evaluate(+ async (url) =>+ Array.from(new Uint8Array(await (await fetch(url!)).arrayBuffer())),+ source,+ );+ expect(await inspect(page, Buffer.from(bytes))).toMatchObject({+ encrypted: false,+ pageCount: 1,+ });+}++async function assertCopyAccess(page: Page, allowed: boolean) {+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+ await page.evaluate(() =>+ navigator.clipboard.writeText("protection-test-marker"),+ );+ const pdfPage = page.locator('[data-page-index="0"]').first();+ const copy = page.getByRole("button", { name: "Copy", exact: true });+ await expect(async () => {+ const bounds = await pdfPage.boundingBox();+ expect(bounds).not.toBeNull();+ await pdfPage.click({+ button: "right",+ position: { x: bounds!.width * 0.21, y: bounds!.height * 0.105 },+ });+ await expect(copy).toBeVisible({ timeout: 1000 });+ }).toPass();+ if (allowed) {+ await expect(copy).toBeEnabled();+ await copy.click();+ await expect+ .poll(() => page.evaluate(() => navigator.clipboard.readText()))+ .not.toBe("protection-test-marker");+ expect(+ (await page.evaluate(() => navigator.clipboard.readText())).trim(),+ ).not.toBe("");+ } else {+ await expect(copy).toBeDisabled();+ await page.keyboard.press("Escape");+ }+}++for (const restriction of restrictions) {+ test(`${restriction.label}: setting on and off preserves protection and follows the server policy`, async ({+ page,+ }) => {+ const readerContexts: BrowserContext[] = [];+ try {+ await page.goto("/add-password");+ await page+ .getByTestId("file-input")+ .setInputFiles(path.join(fixtures, "sample.pdf"));+ await page.getByText("Restrict actions", { exact: true }).click();+ await page+ .getByRole("checkbox", { name: restriction.label, exact: true })+ .check();+ await page+ .getByRole("textbox", { name: "New permissions password", exact: true })+ .fill(owner);+ const protectedResponse = page.waitForResponse(+ "**/api/v1/security/set-pdf-protection",+ );+ await page+ .getByRole("button", { name: "Save protection", exact: true })+ .click();+ const result = await protectedResponse;+ expect(result.ok()).toBe(true);+ const protectedBytes = await result.body();+ const readerAccess = await inspect(page, protectedBytes);+ const honorOwnerPasswords = readerAccess.honorOwnerPasswords !== false;+ expect(readerAccess).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ requiresOpeningPassword: false,+ });+ for (const other of restrictions) {+ expect((readerAccess.permissions & other.bit) !== 0, other.label).toBe(+ other.bit !== restriction.bit,+ );+ }+ expect(await inspect(page, protectedBytes, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protection saved", { exact: true }),+ ).toBeVisible();++ page = await openFresh(+ page,+ protectedBytes,+ `restricted-${restriction.bit}.pdf`,+ readerContexts,+ );+ await expect(+ page.getByRole("checkbox", { name: restriction.label, exact: true }),+ ).toBeChecked();+ const printButton = page.getByRole("button", {+ name: "Print PDF",+ exact: true,+ });+ if (+ honorOwnerPasswords &&+ (restriction.bit === PdfPermissionFlag.Print ||+ restriction.bit === PdfPermissionFlag.PrintHighQuality)+ ) {+ await expect(printButton).toBeDisabled();+ await printButton.locator("..").hover();+ await expect(+ page.getByText(+ restriction.bit === PdfPermissionFlag.Print+ ? "Printing is restricted. Verify permissions in Manage protection."+ : "This PDF allows low-quality printing only, which this viewer does not support.",+ { exact: true },+ ),+ ).toBeVisible();+ } else {+ await assertPrintOutput(page);+ }+ if ("endpoint" in restriction) {+ const denied = await page.request.post(+ "/api/v1/security/prepare-pdf-session",+ {+ headers: await liveApiHeaders(page),+ multipart: {+ fileInput: {+ name: "restricted.pdf",+ mimeType: "application/pdf",+ buffer: protectedBytes,+ },+ password: "",+ endpoint: restriction.endpoint,+ },+ },+ );+ expect(denied.status()).toBe(honorOwnerPasswords ? 403 : 200);+ }+ if (restriction.bit === PdfPermissionFlag.CopyContents)+ await assertCopyAccess(page, !honorOwnerPasswords);++ await page+ .getByRole("checkbox", { name: restriction.label, exact: true })+ .uncheck();+ const savedOwner = owner;+ const changedResponse = page.waitForResponse(+ "**/api/v1/security/change-pdf-permissions",+ );+ await page+ .getByRole("button", {+ name: /^Change Permissions(?: \(this file\))?$/,+ })+ .click();+ if (honorOwnerPasswords) {+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toBeVisible();+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ await page+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ } else {+ await expect(page.getByRole("dialog")).toHaveCount(0);+ }+ const changed = await changedResponse;+ expect(changed.ok()).toBe(true);+ const allowedBytes = await changed.body();+ const allowed = await inspect(page, allowedBytes);+ expect(allowed).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ });+ for (const other of restrictions)+ expect((allowed.permissions & other.bit) !== 0, other.label).toBe(true);+ expect(await inspect(page, allowedBytes, savedOwner)).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protection saved", { exact: true }),+ ).toBeVisible();+ if ("endpoint" in restriction) {+ const permitted = await page.request.post(+ "/api/v1/security/prepare-pdf-session",+ {+ headers: await liveApiHeaders(page),+ multipart: {+ fileInput: {+ name: "allowed.pdf",+ mimeType: "application/pdf",+ buffer: allowedBytes,+ },+ password: "",+ endpoint: restriction.endpoint,+ },+ },+ );+ expect(permitted.ok()).toBe(true);+ }+ page = await openFresh(+ page,+ allowedBytes,+ `allowed-${restriction.bit}.pdf`,+ readerContexts,+ );+ await expect(+ page.getByRole("checkbox", { name: restriction.label, exact: true }),+ ).not.toBeChecked();+ await assertPrintOutput(page);+ if (restriction.bit === PdfPermissionFlag.CopyContents)+ await assertCopyAccess(page, true);+ } finally {+ for (const context of readerContexts) await context.close();+ }+ });+}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.tsnew file mode 100644index 0000000000..2e019d2744--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-protection-sessions.spec.ts@@ -0,0 +1,288 @@+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/promises";++const fixtures = path.join(import.meta.dirname, "../test-fixtures");+const reader = "session-opening-password";+const owner = "session-permissions-password";++test.beforeEach(async ({ page }) => {+ await loadLiveAppConfig(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,+ },+ },+ );+ 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);+ await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();+ await expect(dialog).toBeHidden();+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+}++test("opening passwords reject empty and wrong input, cancel safely, and are requested again after reload", async ({+ page,+}) => {+ const buffer = await protect(page);+ await page.goto("/editor");+ const upload = {+ name: "session-protected.pdf",+ mimeType: "application/pdf",+ buffer,+ };+ await page.getByTestId("file-input").setInputFiles(upload);+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });+ await expect(+ dialog.getByRole("button", { name: "Open PDF", exact: true }),+ ).toBeDisabled();+ await dialog.getByLabel("Password to open", { exact: true }).fill("wrong");+ await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();+ await expect(dialog.getByRole("alert")).toContainText("Incorrect password");+ await expect(page.locator('[data-page-index="0"]')).toHaveCount(0);+ await dialog.getByRole("button", { name: "Close", exact: true }).click();+ await expect(dialog).toBeHidden();+ await page.getByTestId("file-input").setInputFiles(upload);+ await open(page, reader);+ await page.reload();+ await expect(dialog).toBeVisible();+ await expect(page.locator('[data-page-index="0"]')).toHaveCount(0);+ await open(page, reader);+});++test("restricted processing preserves both passwords and prompts only when enforcement requires it", async ({+ page,+}) => {+ const buffer = await protect(page);+ const access = await inspect(page, buffer, reader);+ const honorOwnerPasswords = access.honorOwnerPasswords !== false;+ let preparations = 0;+ page.on("request", (request) => {+ if (request.url().endsWith("/prepare-pdf-session")) preparations++;+ });+ await page.goto("/rotate");+ await page.getByTestId("file-input").setInputFiles({+ name: "rotate-protected.pdf",+ mimeType: "application/pdf",+ buffer,+ });+ await open(page, reader);+ const apply = page.getByRole("button", {+ name: /^Apply Rotation(?: \(this file\))?$/,+ });+ if (honorOwnerPasswords) {+ await apply.click();+ const dialog = page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ });+ await expect(dialog).toBeVisible();+ expect(preparations).toBe(0);+ await dialog.getByRole("button", { name: "Close", exact: true }).click();+ await expect(apply).toBeEnabled();+ await apply.click();+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(reader);+ await dialog.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(dialog.getByRole("alert")).toBeVisible();+ expect(preparations).toBe(0);+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ }+ const response = page.waitForResponse(+ "**/api/v1/security/restore-pdf-protection",+ );+ if (honorOwnerPasswords)+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ else await apply.click();+ const result = await response;+ expect(result.ok()).toBe(true);+ const saved = await result.body();+ expect(await inspect(page, saved, reader)).toMatchObject({+ ownerAuthenticated: false,+ requiresOpeningPassword: true,+ permissions: access.permissions,+ credentialFingerprint: access.credentialFingerprint,+ });+ expect(await inspect(page, saved, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protection retained", { exact: true }),+ ).toBeVisible();+ expect(preparations).toBe(1);+ await expect(page.getByRole("dialog")).toHaveCount(0);+});++test("removing all protection can be cancelled, then opening-only protection can be reapplied", async ({+ page,+}) => {+ const buffer = await protect(page);+ const access = await inspect(page, buffer, reader);+ let removals = 0;+ page.on("request", (request) => {+ if (request.url().endsWith("/remove-pdf-protection")) removals++;+ });+ await page.goto("/editor");+ await page.getByTestId("file-input").setInputFiles({+ name: "protected.pdf",+ mimeType: "application/pdf",+ buffer,+ });+ await open(page, reader);+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Close", exact: true })+ .click();+ expect(removals).toBe(0);+ await expect(+ page.getByRole("button", { name: "Manage protection", exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ const response = page.waitForResponse(+ "**/api/v1/security/remove-pdf-protection",+ );+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ if (access.honorOwnerPasswords !== false) {+ await page.getByLabel("Permissions password", { exact: true }).fill(owner);+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ }+ const result = await response;+ expect(result.ok()).toBe(true);+ const unprotected = await result.body();+ expect(await inspect(page, unprotected, "")).toMatchObject({+ encrypted: false,+ requiresOpeningPassword: false,+ });+ await expect(+ page.getByRole("button", { name: "Manage protection", exact: true }),+ ).toHaveCount(0);+ await page.getByRole("button", { name: "Print PDF", exact: true }).click();+ await expect(page.locator('iframe[title="Print Document"]')).toHaveAttribute(+ "src",+ /^blob:/,+ );++ await page.goto("/add-password");+ await page.getByTestId("file-input").setInputFiles({+ name: "opening-only.pdf",+ mimeType: "application/pdf",+ buffer: unprotected,+ });+ await page.getByLabel("Password to open", { exact: true }).fill(reader);+ const protection = page.waitForResponse(+ "**/api/v1/security/set-pdf-protection",+ );+ await page+ .getByRole("button", { name: /^Save protection(?: \(this file\))?$/ })+ .click();+ const protectedResponse = await protection;+ expect(protectedResponse.ok()).toBe(true);+ expect(+ await inspect(page, await protectedResponse.body(), reader),+ ).toMatchObject({+ requiresOpeningPassword: true,+ permissions: -4,+ canPrint: true,+ canModify: true,+ canExtract: true,+ });+});++test("batch opening accepts a shared opening password without granting owner access", async ({+ page,+}) => {+ const buffer = await protect(page);+ const access = await inspect(page, buffer, reader);+ await page.goto("/rotate");+ await page.getByTestId("file-input").setInputFiles([+ { name: "batch-a.pdf", mimeType: "application/pdf", buffer },+ { name: "batch-b.pdf", mimeType: "application/pdf", buffer },+ ]);+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });+ await dialog.getByLabel("Password to open", { exact: true }).fill(reader);+ await dialog+ .getByRole("button", { name: "Use for all (2)", exact: true })+ .click();+ await expect(dialog).toBeHidden();+ await expect(+ page.getByRole("button", { name: "Apply Rotation (2 files)", exact: true }),+ ).toBeEnabled();+ await page.getByRole("button", { name: "Reader", exact: true }).click();+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(+ page.getByRole("button", {+ name: "Printing unlocked for this session",+ exact: true,+ }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", {+ name: "Verify permissions for this session",+ exact: true,+ }),+ ).toHaveCount(access.honorOwnerPasswords === false ? 0 : 1);+ await page+ .getByRole("button", { name: "Change Permissions", exact: true })+ .click();+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled({ enabled: access.honorOwnerPasswords === false });+});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.tsnew file mode 100644index 0000000000..8240cf3036--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-protection-workflow.spec.ts@@ -0,0 +1,507 @@+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";++const fixtures = path.join(import.meta.dirname, "../test-fixtures");+const reader = "opening-test-password";+const owner = "permissions-test-password";++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,+}) => {+ await page.goto("/add-password");+ await page+ .getByTestId("file-input")+ .setInputFiles(path.join(fixtures, "sample.pdf"));+ await page.getByLabel("Password to open", { exact: true }).fill(reader);+ await page.getByText("Restrict actions", { exact: true }).click();+ await page+ .getByRole("checkbox", { name: "Prevent printing", exact: true })+ .check();+ const ownerInput = page.getByRole("textbox", {+ name: "New permissions password",+ exact: true,+ });+ await expect(+ page.getByText("Use a different password to change restrictions."),+ ).toHaveCount(0);+ await ownerInput.fill(reader);+ await expect(+ page.getByText("The two passwords must be different."),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Save protection", exact: true }),+ ).toBeDisabled();+ await ownerInput.fill(owner);+ const protection = page.waitForResponse(+ "**/api/v1/security/set-pdf-protection",+ );+ await page+ .getByRole("button", { name: "Save protection", exact: true })+ .click();+ const protectedResponse = await protection;+ expect(protectedResponse.ok()).toBe(true);+ const protectedBytes = await protectedResponse.body();+ const readerAccess = await inspect(page, protectedBytes, reader);+ expect(readerAccess).toMatchObject({+ encrypted: true,+ requiresOpeningPassword: true,+ openingAuthenticated: true,+ hasOwnerPassword: true,+ ownerAuthenticated: false,+ canPrint: false,+ });+ const honor = readerAccess.honorOwnerPasswords !== false;+ await expect(+ page.getByText("Protection saved", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled({ enabled: !honor });+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(+ page.getByText("Permissions unlocked for this session", { exact: true }),+ ).toHaveCount(0);+ await page+ .getByRole("button", { name: "Change Permissions", exact: true })+ .click();+ await expect(+ page.getByRole("textbox", {+ name: "Password to open the updated PDF",+ exact: true,+ }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("textbox", {+ name: "New permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ await page+ .getByRole("checkbox", { name: "Prevent printing", exact: true })+ .uncheck();+ const changed = page.waitForResponse(+ "**/api/v1/security/change-pdf-permissions",+ );+ await page+ .getByRole("button", { name: "Change Permissions", exact: true })+ .click();+ if (honor) {+ const dialog = page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ });+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(reader);+ await dialog.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(dialog.getByRole("alert")).toBeVisible();+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ await dialog.getByRole("button", { name: "Continue", exact: true }).click();+ }+ const changedResponse = await changed;+ expect(changedResponse.ok()).toBe(true);+ const saved = await changedResponse.body();+ expect(await inspect(page, saved, reader)).toMatchObject({+ requiresOpeningPassword: true,+ ownerAuthenticated: false,+ canPrint: true,+ });+ expect(await inspect(page, saved, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protection saved", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled();+});+test("a protected merge is rejected before asking for passwords or processing files", async ({+ page,+}) => {+ let operations = 0;+ page.on("request", (request) => {+ if (/\/(prepare-pdf-session|merge-pdfs)$/.test(request.url())) operations++;+ });+ await page.goto("/merge");+ const buffer = fs.readFileSync(+ path.join(fixtures, "owner-only-restricted.pdf"),+ );+ await page.getByTestId("file-input").setInputFiles([+ { name: "first.pdf", mimeType: "application/pdf", buffer },+ { name: "second.pdf", mimeType: "application/pdf", buffer },+ ]);+ await page+ .getByRole("button", { name: "Merge (2 files)", exact: true })+ .click();+ await expect(+ page+ .getByText(+ "These PDFs have separate protection settings. Process them individually.",+ )+ .first(),+ ).toBeVisible();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ expect(operations).toBe(0);+});++for (const action of [+ "Change Permissions",+ "Create an unprotected copy",+] as const) {+ test(`${action} follows the owner policy in a fresh session`, async ({+ page,+ }) => {+ const buffer = fs.readFileSync(+ path.join(fixtures, "owner-only-restricted.pdf"),+ );+ const honorOwnerPasswords =+ (await inspect(page, buffer, "")).honorOwnerPasswords !== false;+ const endpoint =+ action === "Change Permissions"+ ? "change-pdf-permissions"+ : "remove-pdf-protection";+ const denied = await page.request.post(`/api/v1/security/${endpoint}`, {+ headers: await liveApiHeaders(page),+ multipart: {+ fileInput: {+ name: "restricted.pdf",+ mimeType: "application/pdf",+ buffer,+ },+ password: "",+ sourcePassword: "",+ },+ });+ expect(denied.status()).toBe(honorOwnerPasswords ? 403 : 200);+ let changes = 0;+ page.on("request", (request) => {+ if (request.url().endsWith(`/api/v1/security/${endpoint}`)) changes++;+ });+ await page.goto("/change-permissions");+ await page.getByTestId("file-input").setInputFiles({+ name: "restricted.pdf",+ mimeType: "application/pdf",+ buffer,+ });+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+ if (!honorOwnerPasswords) {+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled();+ await expect(+ page.getByText("Required to apply changes", { exact: true }),+ ).toHaveCount(0);+ if (action === "Change Permissions") {+ await expect(+ page.getByRole("button", { name: action, exact: true }),+ ).toBeEnabled();+ } else {+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page.getByRole("button", { name: action, exact: true }).click();+ }+ const response = page.waitForResponse(`**/api/v1/security/${endpoint}`);+ await page.getByRole("button", { name: action, exact: true }).click();+ const result = await response;+ expect(result.ok()).toBe(true);+ expect(changes).toBe(1);+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ const output = await result.body();+ expect(await inspect(page, output, "")).toMatchObject({+ encrypted: action === "Change Permissions",+ });+ if (action === "Change Permissions") {+ expect(+ await inspect(page, output, "owner-test-password"),+ ).toMatchObject({+ ownerAuthenticated: true,+ });+ }+ return;+ }+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeDisabled();+ await expect(+ page.getByText("Protected PDF", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByText("Required to apply changes", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("textbox", {+ name: "New permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ if (action === "Create an unprotected copy") {+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(page.getByText("Printing", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: action, exact: true }).click();+ }+ await page.getByRole("button", { name: action, exact: true }).click();+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toBeVisible();+ await page+ .getByRole("dialog", { name: "Enter permissions password", exact: true })+ .getByRole("button", { name: "Close", exact: true })+ .click();+ expect(changes).toBe(0);+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeDisabled();+ await page.getByRole("button", { name: action, exact: true }).click();+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("incorrect");+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(+ page.getByRole("alert").filter({ hasText: "Incorrect password" }),+ ).toBeVisible();+ expect(changes).toBe(0);+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("owner-test-password");+ const response = page.waitForResponse(`**/api/v1/security/${endpoint}`);+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ const result = await response;+ expect(result.ok()).toBe(true);+ expect(changes).toBe(1);+ const output = await result.body();+ if (action === "Change Permissions") {+ expect(await inspect(page, output, "")).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ canPrint: false,+ });+ expect(await inspect(page, output, "owner-test-password")).toMatchObject({+ ownerAuthenticated: true,+ });+ await expect(+ page.getByText("Protected PDF", {+ exact: true,+ }),+ ).toBeVisible();+ } else {+ expect(await inspect(page, output, "")).toMatchObject({+ encrypted: false,+ });+ }+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled({ enabled: action === "Create an unprotected copy" });+ });+}++test("a PDF with only an opening password opens and prints after removing its opening requirement", async ({+ page,+}) => {+ await page.goto("/add-password");+ await page+ .getByTestId("file-input")+ .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",+ );+ await page+ .getByRole("button", { name: "Save protection", exact: true })+ .click();+ const result = await protectedResponse;+ expect(result.ok()).toBe(true);+ expect(await inspect(page, await result.body(), reader)).toMatchObject({+ encrypted: true,+ requiresOpeningPassword: true,+ canPrint: true,+ });+ await expect(+ page.getByText("Protection saved", { exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .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();+ await page.getByLabel("Password to open", { exact: true }).fill(reader);+ await page+ .getByRole("button", { name: "Remove Password", exact: true })+ .click();+ const removed = await removedResponse;+ expect(removed.ok()).toBe(true);+ expect(await inspect(page, await removed.body(), "")).toMatchObject({+ requiresOpeningPassword: false,+ canPrint: true,+ });+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page.getByRole("button", { name: "Print PDF", exact: true }).click();+ await expect(page.locator('iframe[title="Print Document"]')).toHaveAttribute(+ "src",+ /^blob:/,+ );+});++test("replacing the permissions password follows the owner policy and invalidates the old credential", async ({+ page,+}) => {+ const honorOwnerPasswords =+ (+ await inspect(+ page,+ fs.readFileSync(path.join(fixtures, "owner-only-restricted.pdf")),+ "",+ )+ ).honorOwnerPasswords !== false;+ await page.goto("/change-permissions");+ await page+ .getByTestId("file-input")+ .setInputFiles(path.join(fixtures, "owner-only-restricted.pdf"));+ await expect(page.getByText("Protected PDF", { exact: true })).toBeVisible();+ await page+ .getByRole("checkbox", {+ name: "Change permissions password",+ exact: true,+ })+ .check();+ await page+ .getByRole("textbox", { name: "New permissions password", exact: true })+ .fill(owner);+ const changedResponse = page.waitForResponse(+ "**/api/v1/security/change-pdf-permissions",+ );+ await page+ .getByRole("button", { name: "Change Permissions", exact: true })+ .click();+ if (honorOwnerPasswords) {+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toBeVisible();+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("owner-test-password");+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ } else {+ await expect(+ page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ }+ const changed = await changedResponse;+ expect(changed.ok()).toBe(true);+ const buffer = await changed.body();+ expect(await inspect(page, buffer, owner)).toMatchObject({+ ownerAuthenticated: true,+ });+ expect(await inspect(page, buffer, "")).toMatchObject({+ 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",+ },+ },+ );+ expect(oldCredential.ok()).toBe(false);+});++for (const tool of ["annotate", "form-fill", "redact"]) {+ test(`${tool} explains that protected editing is unsupported before offering an editable output`, async ({+ page,+ }) => {+ const honorOwnerPasswords =+ (+ await inspect(+ page,+ fs.readFileSync(path.join(fixtures, "owner-only-restricted.pdf")),+ "",+ )+ ).honorOwnerPasswords !== false;+ await page.goto(`/${tool}`);+ await page+ .getByTestId("file-input")+ .setInputFiles(path.join(fixtures, "owner-only-restricted.pdf"));+ const notice = page.getByTestId("tool-file-list");+ await expect(+ notice.getByText("owner-only-restricted.pdf", { exact: true }),+ ).toBeVisible();+ await expect(notice.getByRole("status")).toHaveCount(0);+ await expect(+ page.getByText("This tool cannot yet preserve this PDF's protection.", {+ exact: true,+ }),+ ).toHaveCount(0);+ await notice.getByRole("button", { name: /Why .* is unavailable/ }).hover();+ await expect(page.getByRole("tooltip")).toHaveText(+ "This tool doesn't support encrypted PDFs. Remove the password first.",+ );+ const removePassword = notice.getByRole("button", {+ name: "Remove Password",+ });+ await removePassword.hover();+ await expect(page.getByRole("tooltip")).toHaveText(+ "Open Remove Password to choose which passwords to remove.",+ );+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Print PDF", exact: true }),+ ).toBeEnabled({ enabled: !honorOwnerPasswords });+ await removePassword.click();+ await expect(page).toHaveURL(/\/remove-password$/);+ });+}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.tsnew file mode 100644index 0000000000..db18f2139f--- /dev/null+++ b/frontend/editor/src/core/tests/live/pdf-text-editor-permissions.spec.ts@@ -0,0 +1,245 @@+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";+import type { Page } from "@playwright/test";+import path from "node:path";+import fs from "node:fs/promises";++const restricted = path.join(+ import.meta.dirname,+ "../test-fixtures/owner-only-restricted.pdf",+);+const owner = "owner-test-password";+const deniedMessage = "This action requires the permissions password.";++test.beforeEach(async ({ page }) => {+ await loadLiveAppConfig(page);+});++async function openTextEditor(page: Page) {+ await page+ .getByRole("link", { name: "PDF Text Editor", exact: true })+ .first()+ .click();+ 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,+ }) => {+ const access = await inspect(page, await fs.readFile(restricted), "");+ expect(access).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ canModify: false,+ });+ if (entry === "workbench") {+ await page.goto("/editor");+ await page.getByTestId("file-input").setInputFiles(restricted);+ await expect(+ page.getByText("Protected PDF", { exact: true }),+ ).toBeVisible();+ await openTextEditor(page);+ } else {+ await page.goto("/pdf-text-editor");+ await page.getByTestId("pdf-editor-file-input").setInputFiles(restricted);+ }+ if (access.honorOwnerPasswords !== false) {+ await expect(+ page.getByText(deniedMessage, { exact: true }),+ ).toBeVisible();+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);+ await expect(+ page.locator('[data-testid^="pdf-editor-run-"]'),+ ).toHaveCount(0);+ const verify = page.getByRole("button", {+ name: "Enter permissions password",+ exact: true,+ });+ await verify.click();+ const dialog = page.getByRole("dialog", {+ name: "Enter permissions password",+ exact: true,+ });+ await expect(+ dialog.getByLabel("Permissions password", { exact: true }),+ ).toBeVisible();+ await expect(+ dialog.getByLabel("Password to open", { exact: true }),+ ).toHaveCount(0);+ await dialog.getByRole("button", { name: "Close", exact: true }).click();+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);+ await verify.click();+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill("incorrect-password");+ await dialog+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ await expect(+ dialog.getByText("Incorrect password", { exact: true }),+ ).toBeVisible();+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);+ await dialog+ .getByLabel("Permissions password", { exact: true })+ .fill(owner);+ await dialog+ .getByRole("button", { name: "Continue", exact: true })+ .click();+ await expect(dialog).toBeHidden();+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();+ await expect(page.getByTestId("pdf-editor-error")).toHaveCount(0);+ } else {+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();+ await expect(+ page+ .locator('[data-testid^="pdf-editor-run-"][contenteditable="true"]')+ .first(),+ ).toBeVisible();+ await expect(page.getByText(deniedMessage, { exact: true })).toHaveCount(+ 0,+ );+ await expect(+ page.getByRole("button", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ }+ });+}++test("permitted text edits preserve protection and a fresh reader follows the server policy", async ({+ page,+ browser,+}) => {+ test.setTimeout(120_000);+ const source = await fs.readFile(restricted);+ const sourceAccess = await inspect(page, source, owner);+ const honorOwnerPasswords = sourceAccess.honorOwnerPasswords !== false;+ await page.goto("/editor");+ await page.getByTestId("file-input").setInputFiles(restricted);+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(+ page.getByRole("button", {+ name: "Editing unlocked for this session",+ exact: true,+ }),+ ).toHaveCount(0);+ if (honorOwnerPasswords) {+ await page+ .getByRole("button", {+ name: "Verify permissions for this session",+ exact: true,+ })+ .click();+ await page.getByLabel("Permissions password", { exact: true }).fill(owner);+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(+ page.getByText("Permissions unlocked for this session", { exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ } else {+ await expect(+ page.getByRole("button", {+ name: "Verify permissions for this session",+ exact: true,+ }),+ ).toHaveCount(0);+ }+ await page+ .getByRole("button", {+ name: honorOwnerPasswords+ ? "Editing unlocked for this session"+ : "Editing restriction ignored",+ exact: true,+ })+ .hover();+ await expect(page.getByRole("tooltip")).toHaveText(+ honorOwnerPasswords+ ? "Unlocked for this session using your permissions password."+ : "Permissions are ignored by this server's settings. The PDF's protection is unchanged.",+ );+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Close", exact: true })+ .click();+ await openTextEditor(page);+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();+ const run = page+ .locator('[data-testid^="pdf-editor-run-"][contenteditable="true"]')+ .first();+ await run.fill("Owner-authorized text edit");+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();+ await page.getByTestId("pdf-editor-download").click();+ const downloadPromise = page.waitForEvent("download");+ await page.getByTestId("pdf-editor-save-risk-confirm").click();+ const download = await downloadPromise;+ const savedPath = test.info().outputPath("restricted-edited.pdf");+ await download.saveAs(savedPath);+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden();+ const saved = await fs.readFile(savedPath);+ expect(await inspect(page, saved, "")).toMatchObject({+ encrypted: true,+ ownerAuthenticated: false,+ canModify: false,+ permissions: sourceAccess.permissions,+ encryptionKeyLength: sourceAccess.encryptionKeyLength,+ encryptionRevision: sourceAccess.encryptionRevision,+ credentialFingerprint: sourceAccess.credentialFingerprint,+ });+ expect(await inspect(page, saved, owner)).toMatchObject({+ ownerAuthenticated: true,+ });++ const readerContext = await browser.newContext({+ baseURL: new URL(page.url()).origin,+ storageState: await page.context().storageState(),+ viewport: page.viewportSize() ?? undefined,+ });+ try {+ const readerPage = await readerContext.newPage();+ await skipOnboarding(readerPage);+ await readerPage.goto("/pdf-text-editor");+ await readerPage+ .getByTestId("pdf-editor-file-input")+ .setInputFiles(savedPath);+ if (honorOwnerPasswords) {+ await expect(+ readerPage.getByText(deniedMessage, { exact: true }),+ ).toBeVisible();+ await expect(readerPage.getByTestId("pdf-editor-page-0")).toHaveCount(0);+ } else {+ await expect(readerPage.getByTestId("pdf-editor-page-0")).toBeVisible();+ await expect(+ readerPage.getByText(deniedMessage, { exact: true }),+ ).toHaveCount(0);+ }+ } finally {+ await readerContext.close();+ }+});diff --git a/frontend/editor/src/core/tests/stubbed/add-password-tool.spec.ts b/frontend/editor/src/core/tests/stubbed/add-password-tool.spec.tsindex ec1e6cd6c9..1566c4a1e3 100644--- a/frontend/editor/src/core/tests/stubbed/add-password-tool.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/add-password-tool.spec.ts@@ -8,21 +8,21 @@ test.describe("9. Add Password Tool", () => {test.describe("9.1 Add Password - Multi-Step Form", () => {test("should display all configuration steps", async ({ page }) => {- // Step 1: Verify a 3-step workflow: Files, Passwords & Encryption, Change Permissionsawait expect(page.getByText("Files").first()).toBeVisible();await expect(- page.getByText(/Passwords?\s*&?\s*Encryption/i).first(),+ page.getByText("Password to open", { exact: true }).first(),+ ).toBeVisible();+ await expect(+ page.getByText("Restrict actions", { exact: true }),).toBeVisible();- await expect(page.getByText(/Change Permissions/i).first()).toBeVisible();- // Step 2: Verify the Encrypt button is disabled- const encryptButton = page- .getByRole("button", { name: /encrypt/i })- .first();- await expect(encryptButton).toBeVisible();- await expect(encryptButton).toBeDisabled();+ const saveButton = page.getByRole("button", {+ name: "Save protection",+ exact: true,+ });+ await expect(saveButton).toBeVisible();+ await expect(saveButton).toBeDisabled();- // Step 3: Verify the file upload area is presentawait expect(page.getByText(/upload/i).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.tsindex c7a6f5bbf1..d28617901a 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@@ -57,9 +57,9 @@ async function uploadEncryptedFile(page: Page, filePath: string) {await page.locator('[data-testid="file-input"]').setInputFiles(filePath);}-const MODAL_TITLE = /^Unlock PDF/;-const PASSWORD_PLACEHOLDER = "Enter the PDF password";-const UNLOCK_BUTTON_TEXT = /^Unlock$/;+const MODAL_TITLE = /^Open PDF/;+const PASSWORD_LABEL = "Password to open";+const UNLOCK_BUTTON_TEXT = /^Open PDF$/;/*** Fill the password field and wait until the modal has registered it: the@@ -68,7 +68,7 @@ const UNLOCK_BUTTON_TEXT = /^Unlock$/;* remount mid open-transition and drop a one-shot fill, leaving it disabled.*/async function fillPassword(page: Page, password: string): Promise<void> {- const field = page.getByPlaceholder(PASSWORD_PLACEHOLDER);+ const field = page.getByLabel(PASSWORD_LABEL, { exact: true });const unlock = page.getByRole("button", { name: UNLOCK_BUTTON_TEXT });await expect(async () => {await field.fill(password);@@ -137,7 +137,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {const splitZip = await zip.generateAsync({ type: "nodebuffer" });const restoredNames: string[] = [];await mockUnlockSuccess(page, 10);- await page.route("**/api/v1/security/remove-password", (route) =>+ await page.route("**/api/v1/security/prepare-pdf-session", (route) =>route.fulfill({ contentType: "application/pdf", body: workingPdf }),);await page.route(@@ -229,62 +229,77 @@ test.describe("Encrypted PDF Unlock Modal", () => {await expect(page.getByRole("heading", { name: MODAL_TITLE })).toBeVisible({timeout: 10000,});- await expect(page.getByPlaceholder(PASSWORD_PLACEHOLDER)).toBeVisible();await expect(- page.getByRole("button", { name: "Cancel opening" }),- ).toHaveCount(0);+ page.getByLabel(PASSWORD_LABEL, { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Close", exact: true }),+ ).toBeVisible();await expect(page.getByRole("button", { name: "More options", exact: true }),).toHaveCount(0);- await expect(- page.getByRole("button", { name: "Remove Password", exact: true }),- ).toBeVisible();await expect(page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }),- ).toBeVisible();+ ).toBeDisabled();await expect(- page.getByText("Unlock for this session.", { exact: true }),+ page.getByText("Create an unprotected copy", { exact: true }),).toHaveCount(0);- const details = page.getByRole("heading").getByRole("button", {+ const details = page.getByRole("button", {name: "About session unlocking",});- await page.getByPlaceholder(PASSWORD_PLACEHOLDER).focus();- await page.keyboard.press("Shift+Tab");- await page.keyboard.press("Shift+Tab");- await expect(details).toBeFocused();- const sessionDetails = page.getByRole("tooltip").filter({- hasText: "Unlock for this session.",- });- await expect(sessionDetails).toHaveText(- "Unlock for this session. The PDF stays protected. Remove Password creates an unprotected copy.",+ await details.focus();+ await expect(page.getByRole("tooltip")).toHaveText(+ "Open for this session. The PDF stays protected.",);- await page.getByPlaceholder(PASSWORD_PLACEHOLDER).focus();- await expect(sessionDetails).toBeHidden();+ await page.getByLabel(PASSWORD_LABEL, { exact: true }).focus();+ await expect(page.getByRole("tooltip")).toBeHidden();});- test("Remove Password creates a usable copy and retains the protected source", async ({+ test("explicit removal of all protection creates a usable copy and retains the protected source", async ({page,}) => {const sample = fs.readFileSync(path.join(FIXTURES_DIR, "sample.pdf"));let removals = 0;- await page.route("**/api/v1/security/remove-password", (route) => {+ await page.route("**/api/v1/security/remove-pdf-protection", (route) => {removals++;return route.fulfill({ contentType: "application/pdf", body: sample });});- await uploadEncryptedFile(page, ENCRYPTED_PDF);- const dialog = page.getByRole("dialog");- const removePassword = dialog.getByRole("button", {- name: "Remove Password",- exact: true,+ 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 expect(removePassword).toBeDisabled();+ await uploadEncryptedFile(page, ENCRYPTED_PDF);await fillPassword(page, "testpass123");- await expect(removePassword).toBeEnabled();- await removePassword.click();- await expect(dialog).toBeHidden();+ await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();await expect(- page.getByText("Unprotected copy created", { exact: true }),+ page.getByText(+ "The copy will have no passwords or restrictions. The original stays protected.",+ ),).toBeVisible();+ expect(removals).toBe(0);+ await page+ .getByRole("button", { name: "Create an unprotected copy", exact: true })+ .click();+ await expect(page.getByRole("dialog")).toBeHidden();await expect(page.locator('[data-page-index="0"] img').first()).toBeVisible({ timeout: 30_000 },);@@ -351,7 +366,11 @@ test.describe("Encrypted PDF Unlock Modal", () => {test.setTimeout(90_000);const removalRequests: string[] = [];page.on("request", (request) => {- if (request.url().includes("/security/remove-password"))+ if (+ /\/security\/remove-(password|pdf-protection|pdf-opening-password)/.test(+ request.url(),+ )+ )removalRequests.push(request.url());});await mockUnlockSuccess(page);@@ -367,7 +386,11 @@ test.describe("Encrypted PDF Unlock Modal", () => {await expect(page.getByRole("heading", { name: MODAL_TITLE, exact: true }),).toBeHidden({ timeout: 10000 });- await expect(page.getByText("PDF unlocked", { exact: true })).toBeVisible({+ await expect(+ page+ .getByText("Permissions unlocked for this session", { exact: true })+ .first(),+ ).toBeVisible({timeout: 5000,});await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({@@ -389,12 +412,10 @@ test.describe("Encrypted PDF Unlock Modal", () => {.click();const unlockedIndicator = page.getByTestId("file-thumbnail")- .getByRole("img", { name: "PDF unlocked", exact: true });+ .getByRole("img", { name: "PDF opened", exact: true });await expect(unlockedIndicator).toBeVisible();await unlockedIndicator.hover();- await expect(page.getByRole("tooltip")).toHaveText(- "Unlocked for this session. Password protection is retained.",- );+ await expect(page.getByRole("tooltip")).toHaveText("Protection retained.");});test("incorrect password keeps the modal open with an inline error", async ({@@ -445,21 +466,21 @@ test.describe("Encrypted PDF Unlock Modal", () => {await expect(details).toBeVisible();await notice.getByText("encrypted.pdf", { exact: true }).click();await expect(details).toBeHidden();- const removePassword = notice- .getByRole("listitem")- .getByRole("button", { name: "Remove Password" });+ const removePassword = notice.getByRole("button", {+ name: "Remove Password",+ });await removePassword.hover();- await expect(- page.getByRole("tooltip").filter({- hasText: "Open Remove Password to create an unprotected copy.",- }),- ).toBeVisible();+ await expect(page.getByRole("tooltip")).toHaveText(+ "Open Remove Password to choose which passwords to remove.",+ );await removePassword.click();await expect(page).toHaveURL(/\/remove-password$/);await expect(page.getByTestId("tool-file-list")).toContainText("encrypted.pdf",);- await expect(page.getByPlaceholder("Enter current password")).toBeVisible();+ await expect(+ page.getByLabel("Password to open", { exact: true }),+ ).toBeVisible();});for (const legacy of [false, true]) {@@ -548,7 +569,7 @@ test.describe("Encrypted PDF Unlock Modal", () => {).toBeVisible({ timeout: 10000 });await fillPassword(page, "testpass123");- await page.getByPlaceholder(PASSWORD_PLACEHOLDER).press("Enter");+ await page.getByLabel(PASSWORD_LABEL, { exact: true }).press("Enter");await expect(page.getByRole("heading", { name: MODAL_TITLE, exact: true }),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.tsnew file mode 100644index 0000000000..276950560a--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/pdf-permissions-workflow.spec.ts@@ -0,0 +1,192 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";+import path from "node:path";+import fs from "node:fs";++const fixture = path.join(+ import.meta.dirname,+ "../test-fixtures/owner-only-restricted.pdf",+);+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 },+ });+ 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,+ },+ });+ });+});++for (const { name, route } of [+ { name: "Remove Password", route: "/remove-password" },+ { name: "Change Permissions", route: "/change-permissions" },+]) {+ test(`Manage protection opens ${name} from All Tools`, async ({ page }) => {+ await page.goto("/compress");+ await page.getByTestId("file-input").setInputFiles(fixture);+ await expect(+ page.getByRole("button", { name: "Manage protection", exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Back to all tools", exact: true })+ .click();+ await expect(+ page.getByRole("button", { name: "Search tools", exact: true }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("dialog")+ .getByRole("button", { name, exact: true })+ .click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(page).toHaveURL(route);+ await expect(page.getByTestId("tool-file-list")).toContainText(+ "owner-only-restricted.pdf",+ );+ await expect(+ page.getByRole("button", { name: "Back to all tools", exact: true }),+ ).toBeVisible();+ });+}++test("restricted compression prompts at execution, preserves settings on cancel, and continues after verification", async ({+ page,+}) => {+ let compressions = 0;+ await page.route("**/api/v1/security/prepare-pdf-session", (route) =>+ route.fulfill({ contentType: "application/pdf", body: sample }),+ );+ await page.route("**/api/v1/misc/compress-pdf", (route) => {+ compressions++;+ return route.fulfill({ contentType: "application/pdf", body: sample });+ });+ await page.route("**/api/v1/security/restore-pdf-protection", (route) =>+ route.fulfill({+ contentType: "application/pdf",+ body: fs.readFileSync(fixture),+ }),+ );+ await page.goto("/compress");+ await page.getByTestId("files-button").click();+ await page.getByTestId("file-input").setInputFiles(fixture);+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page.getByRole("button", { name: "Compress", exact: true }).click();+ await expect(+ page.getByText("This PDF requires permission to use Compress."),+ ).toBeVisible();+ expect(compressions).toBe(0);+ await page.getByRole("button", { name: "Close", exact: true }).click();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await page.getByRole("button", { name: "Compress", exact: true }).click();+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("incorrect");+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(+ page.getByRole("alert").filter({ hasText: "Incorrect password" }),+ ).toBeVisible();+ expect(compressions).toBe(0);+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("owner-test-password");+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(+ page.getByText("Protection retained", { exact: true }),+ ).toBeVisible();+ expect(compressions).toBe(1);+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(page.getByText("Not required", { exact: true })).toBeVisible();+ const unlockedPrinting = page.getByRole("dialog").getByRole("button", {+ name: "Printing unlocked for this session",+ exact: true,+ });+ await expect(unlockedPrinting).toBeVisible();+ await unlockedPrinting.focus();+ await expect(unlockedPrinting).toBeFocused();+ await expect(page.getByRole("tooltip")).toHaveText(+ "Unlocked for this session using your permissions password.",+ );+ await expect(+ page.getByRole("button", { name: "Remove Password", exact: true }),+ ).toBeEnabled();+});++test("unsupported tools keep the explanation in a tooltip and offer Remove Password", async ({+ page,+}) => {+ await page.goto("/redact");+ await page.getByTestId("files-button").click();+ await page.getByTestId("file-input").setInputFiles(fixture);+ const notice = page.getByTestId("tool-file-list");+ await expect(notice.getByRole("status")).toHaveCount(0);+ await notice.getByRole("button", { name: /Why .* is unavailable/ }).hover();+ await expect(page.getByRole("tooltip")).toHaveText(+ "This tool doesn't support encrypted PDFs. Remove the password first.",+ );+ await notice.getByText("owner-only-restricted.pdf", { exact: true }).click();+ await expect(page.getByRole("tooltip")).toBeHidden();+ await expect(+ notice.getByRole("button", { name: "Remove Password" }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", {+ name: "Enter permissions password",+ exact: true,+ }),+ ).toHaveCount(0);+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await page+ .getByRole("button", {+ name: "Verify permissions for this session",+ exact: true,+ })+ .click();+ await page+ .getByLabel("Permissions password", { exact: true })+ .fill("owner-test-password");+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(+ page+ .getByText("Permissions unlocked for this session", { exact: true })+ .first(),+ ).toBeVisible();+ await expect(+ notice.getByRole("button", { name: /Why .* is unavailable/ }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: "Manage protection", exact: true })+ .click();+ await expect(+ page.getByRole("button", {+ name: "Create an unprotected copy",+ exact: true,+ }),+ ).toBeVisible();+});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.tsindex 327d2bde4b..4a5845450b 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@@ -48,6 +48,7 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {permissions: -4,encryptionKeyLength: 256,encryptionRevision: 6,+ credentialFingerprint: "original-credentials",canModify: true,canAssemble: true,pageCount: 1,@@ -59,9 +60,11 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);await page- .getByPlaceholder("Enter the PDF password")+ .getByLabel("Password to open", { exact: true }).fill(ENCRYPTED_PASSWORD);- await page.getByRole("button", { name: "Unlock", exact: true }).click();+ 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 })@@ -115,6 +118,7 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {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);@@ -143,9 +147,9 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {await page.goto("/editor");await page.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);await page- .getByPlaceholder("Enter the PDF password")+ .getByLabel("Password to open", { exact: true }).fill(ENCRYPTED_PASSWORD);- await page.getByRole("button", { name: "Unlock", exact: true }).click();+ 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 })@@ -153,7 +157,7 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {.click();await expect(page.getByText(- /Session unlocking supports viewing it, but processing signed PDFs is not supported yet/,+ "This signed PDF can be viewed, but cannot be edited here.",),).toBeVisible();await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);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.tsindex d0bbea2c61..ffcfe58e3f 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@@ -9,7 +9,7 @@ const SCAN = path.join();for (const source of ["workbench", "disk"] as const) {- test(`unlocked ${source} scan explains OCR and offers Remove Password`, async ({+ test(`unlocked ${source} scan explains that OCR cannot preserve protection`, async ({page,}) => {const ocrRequests: string[] = [];@@ -36,9 +36,9 @@ for (const source of ["workbench", "disk"] as const) {await page.goto("/editor");await page.getByTestId("file-input").setInputFiles(SCAN);await page- .getByPlaceholder("Enter the PDF password")+ .getByLabel("Password to open", { exact: true }).fill("scan-password");- await page.getByRole("button", { name: "Unlock", exact: true }).click();+ 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 })@@ -60,9 +60,9 @@ for (const source of ["workbench", "disk"] as const) {await expect(ocr).toBeVisible();await expect(ocr).toBeDisabled();await expect(hint.getByRole("note")).toHaveText(- "OCR cannot keep this PDF's password protection. Use Remove Password to create an unprotected copy first.",+ "OCR cannot yet preserve this PDF's protection. The protected original remains available for viewing.",);- await expect(ocr).toHaveAccessibleDescription(/password protection/);+ await expect(ocr).toHaveAccessibleDescription(/protection/);const removePassword = hint.getByRole("button", {name: "Remove Password",exact: true,@@ -71,14 +71,9 @@ for (const source of ["workbench", "disk"] as const) {await page.getByTestId("pdf-editor-root").screenshot({path: test.info().outputPath("protected-ocr-sidebar.png"),});+ await expect(page).toHaveURL(/\/pdf-text-editor$/);+ expect(ocrRequests).toEqual([]);await removePassword.click();await expect(page).toHaveURL(/\/remove-password$/);- await expect(- page.getByRole("textbox", { name: "Current Password", exact: true }),- ).toBeVisible();- await expect(- page.getByText("✓ scanned-no-ocr-encrypted.pdf", { exact: true }),- ).toBeVisible();- expect(ocrRequests).toEqual([]);});}diff --git a/frontend/editor/src/core/tests/stubbed/settings-pdf-permissions.spec.ts b/frontend/editor/src/core/tests/stubbed/settings-pdf-permissions.spec.tsnew file mode 100644index 0000000000..10230c54be--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/settings-pdf-permissions.spec.ts@@ -0,0 +1,53 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++for (const initial of [undefined, true, false]) {+ test(`an administrator can change owner enforcement from ${initial ?? "the default"} and reload the pending value`, async ({+ page,+ }) => {+ const expectedInitial = initial ?? true;+ const target = !expectedInitial;+ let pending: boolean | undefined;+ await page.route("**/api/v1/admin/settings/section/security", (route) =>+ route.fulfill({+ json: {+ enableLogin: true,+ ...(initial === undefined ? {} : { honorOwnerPasswords: initial }),+ ...(pending === undefined+ ? {}+ : { _pending: { honorOwnerPasswords: pending } }),+ },+ }),+ );+ const saved: unknown[] = [];+ await page.route("**/api/v1/admin/settings", (route) => {+ if (route.request().method() === "PUT") {+ saved.push(route.request().postDataJSON());+ pending = target;+ }+ return route.fulfill({ json: {} });+ });+ await page.goto("/settings/adminSecurity#pdfPermissions");+ const card = page.locator(".settings-card").filter({+ has: page.getByRole("button", { name: "PDF permissions", exact: true }),+ });+ await expect(card.getByRole("switch")).toBeChecked({+ checked: expectedInitial,+ });+ await page.screenshot({+ path: test.info().outputPath("owner-policy-setting-default.png"),+ });+ await card.locator(".mantine-Switch-track").click();+ await expect(card.getByRole("switch")).toBeChecked({ checked: target });+ await page+ .getByRole("button", { name: "Save Changes", exact: true })+ .click();+ await expect+ .poll(() => saved)+ .toContainEqual({ settings: { "security.honorOwnerPasswords": target } });+ await expect(page.getByRole("dialog")).toBeVisible();+ await page.reload();+ await expect(card.getByRole("switch")).toBeChecked({ checked: target });+ });+}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.tsindex 7cbebec89f..5ffc08db56 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@@ -8,7 +8,9 @@ async function unlockFixture(page: Page, filename: string, pageCount: number) {await page.route("**/api/v1/security/inspect-pdf-security", (route) =>route.fulfill({json: {- encrypted: true,+ encrypted:+ route.request().postData()?.includes(`filename="${filename}"`) ??+ false,signed: false,ownerAuthenticated: true,permissions: -4,@@ -26,13 +28,13 @@ async function unlockFixture(page: Page, filename: string, pageCount: number) {const dialog = page.getByRole("dialog");await expect(async () => {await dialog- .getByPlaceholder("Enter the PDF password")+ .getByLabel("Password to open", { exact: true }).fill("annotation-test");await expect(- dialog.getByRole("button", { name: "Unlock", exact: true }),+ dialog.getByRole("button", { name: "Open PDF", exact: true }),).toBeEnabled({ timeout: 1000 });}).toPass();- await dialog.getByRole("button", { name: "Unlock", exact: true }).click();+ await dialog.getByRole("button", { name: "Open PDF", exact: true }).click();await expect(dialog).toBeHidden();}@@ -58,7 +60,7 @@ test("unlocked annotations render before opening comments and remain read-only",page.getByRole("button", { name: "Highlight", exact: true }),).toHaveCount(0);await expect(- page.getByRole("button", { name: "Remove Password", exact: true }),+ page.getByRole("button", { name: "Manage protection", exact: true }),).toBeVisible();await page.getByRole("button", { name: "Comments", exact: true }).click();diff --git a/frontend/editor/src/core/tests/test-fixtures/owner-only-restricted.pdf b/frontend/editor/src/core/tests/test-fixtures/owner-only-restricted.pdfnew file mode 100644index 0000000000..18cb3f4301Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/owner-only-restricted.pdf differdiff --git a/frontend/editor/src/core/tests/utils/testFileHelpers.ts b/frontend/editor/src/core/tests/utils/testFileHelpers.tsindex b726b70395..f0034a87ac 100644--- a/frontend/editor/src/core/tests/utils/testFileHelpers.ts+++ b/frontend/editor/src/core/tests/utils/testFileHelpers.ts@@ -2,6 +2,7 @@* Test utilities for creating StirlingFile objects in tests*/+import { rememberPdfAccess } from "@app/services/pdfPasswordStore";import { StirlingFile, createStirlingFile } from "@app/types/fileContext";/**@@ -13,6 +14,7 @@ export function createTestStirlingFile(type: string = "application/pdf",): StirlingFile {const file = new File([content], name, { type });+ rememberUnprotectedPdf(file);return createStirlingFile(file);}@@ -27,3 +29,18 @@ export function createTestFilesWithId(createTestStirlingFile(name, content, type),);}++/** Marks synthetic, unencrypted test bytes as already inspected at admission. */+export function rememberUnprotectedPdf(file: File): File {+ rememberPdfAccess(file, {+ password: "",+ encrypted: false,+ 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.tsxindex dcc12710da..6d958a0ddb 100644--- a/frontend/editor/src/core/tools/AddPassword.test.tsx+++ b/frontend/editor/src/core/tools/AddPassword.test.tsx@@ -1,9 +1,14 @@import { act, render, waitFor } from "@testing-library/react";-import type { ComponentProps, ReactElement } from "react";+import {+ Children,+ isValidElement,+ type ComponentProps,+ type ReactElement,+} from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import { PdfPermissionFlag } from "@embedpdf/models";-import type AddPasswordSettings from "@app/components/tools/addPassword/AddPasswordSettings";-import type ChangePermissionsSettings from "@app/components/tools/changePermissions/ChangePermissionsSettings";+import AddPasswordSettings from "@app/components/tools/addPassword/AddPasswordSettings";+import ChangePermissionsSettings from "@app/components/tools/changePermissions/ChangePermissionsSettings";import type { ToolFlowConfig } from "@app/components/tools/shared/createToolFlow";import type { AddPasswordFullParameters } from "@app/hooks/tools/addPassword/useAddPasswordParameters";import { defaultParameters } from "@app/hooks/tools/changePermissions/useChangePermissionsParameters";@@ -63,17 +68,30 @@ function currentFlow() {function passwordSettings() {return (- currentFlow().steps[0].content as ReactElement<- ComponentProps<typeof AddPasswordSettings>- >+ Children.toArray(+ (+ currentFlow().steps[0].content as ReactElement<{+ children: React.ReactNode;+ }>+ ).props.children,+ ).find(+ (child) => isValidElement(child) && child.type === AddPasswordSettings,+ ) as ReactElement<ComponentProps<typeof AddPasswordSettings>>).props;}function permissionSettings() {return (- currentFlow().steps[1].content as ReactElement<- ComponentProps<typeof ChangePermissionsSettings>- >+ Children.toArray(+ (+ currentFlow().steps[1].content as ReactElement<{+ children: React.ReactNode;+ }>+ ).props.children,+ ).find(+ (child) =>+ isValidElement(child) && child.type === ChangePermissionsSettings,+ ) as ReactElement<ComponentProps<typeof ChangePermissionsSettings>>).props;}@@ -136,7 +154,6 @@ describe("Add Password permission detection", () => {render(<AddPassword />);expect(openRawDocument).not.toHaveBeenCalled();- expect(permissionSettings().multipleFiles).toBe(true);expect(currentFlow().executeButton?.disabled).toBe(false);act(() =>@@ -164,7 +181,6 @@ describe("Add Password permission detection", () => {createStirlingFile(new File([], "second.pdf")),];rerender(<AddPassword />);- expect(permissionSettings().multipleFiles).toBe(true);expect(currentFlow().executeButton?.disabled).toBe(false);operation.isLoading = true;diff --git a/frontend/editor/src/core/tools/AddPassword.tsx b/frontend/editor/src/core/tools/AddPassword.tsxindex 21534d7887..f3599158b4 100644--- a/frontend/editor/src/core/tools/AddPassword.tsx+++ b/frontend/editor/src/core/tools/AddPassword.tsx@@ -8,16 +8,22 @@ import { createToolFlow } from "@app/components/tools/shared/createToolFlow";import AddPasswordSettings from "@app/components/tools/addPassword/AddPasswordSettings";import ChangePermissionsSettings from "@app/components/tools/changePermissions/ChangePermissionsSettings";-import { useAddPasswordParameters } from "@app/hooks/tools/addPassword/useAddPasswordParameters";+import {+ useAddPasswordParameters,+ validateAddPasswordParameters,+} from "@app/hooks/tools/addPassword/useAddPasswordParameters";import { useAddPasswordOperation } from "@app/hooks/tools/addPassword/useAddPasswordOperation";import { usePermissionExtraction } from "@app/hooks/tools/changePermissions/usePermissionExtraction";import { useAddPasswordTips } from "@app/components/tooltips/useAddPasswordTips";import { useAddPasswordPermissionsTips } from "@app/components/tooltips/useAddPasswordPermissionsTips";import { BaseToolProps, ToolComponent } from "@app/types/tool";+import { Stack, PasswordInput, Text } from "@mantine/core";+import { usePdfAccess } from "@app/hooks/usePdfAccess";const AddPassword = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {const { t } = useTranslation();const selectedFiles = useViewScopedFiles();+ const access = usePdfAccess(selectedFiles[0]);const [collapsedPermissions, setCollapsedPermissions] = useState(true);@@ -33,10 +39,19 @@ const AddPassword = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {addPasswordParams.permissions.setParameters,!addPasswordOperation.isLoading && !hasResults,);+ const hasRestrictions = Object.entries(+ addPasswordParams.permissions.parameters,+ ).some(([key, value]) => key.startsWith("prevent") && value === true);+ const outputParameters = {+ ...addPasswordParams.fullParameters,+ ownerPassword: hasRestrictions+ ? addPasswordParams.parameters.ownerPassword+ : "",+ };useEffect(() => {- if (permissions.hasError) setCollapsedPermissions(false);- }, [permissions.hasError]);+ if (permissions.hasError || hasRestrictions) setCollapsedPermissions(false);+ }, [permissions.hasError, hasRestrictions]);// Endpoint validationconst { enabled: endpointEnabled, loading: endpointLoading } =@@ -50,7 +65,7 @@ const AddPassword = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {const handleAddPassword = async () => {try {await addPasswordOperation.executeOperation(- addPasswordParams.fullParameters,+ outputParameters,selectedFiles,);if (addPasswordOperation.files && onComplete) {@@ -90,54 +105,99 @@ const AddPassword = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {files: {selectedFiles:addPasswordOperation.getEligibleFiles?.(- addPasswordParams.fullParameters,+ outputParameters,selectedFiles,) ?? selectedFiles,isCollapsed: hasResults,},steps: [{- title: t("addPassword.passwords.stepTitle", "Passwords & Encryption"),+ title: t("encryptedPdfUnlock.openingPassword", "Password to open"),isCollapsed: passwordsCollapsed,onCollapsedClick: hasResults ? handleSettingsReset : undefined,tooltip: addPasswordTips,content: (- <AddPasswordSettings- parameters={addPasswordParams.parameters}- onParameterChange={addPasswordParams.updateParameter}- disabled={endpointLoading}- />+ <Stack gap="sm">+ {access?.encrypted && (+ <Text size="xs">+ {t(+ "encryptedPdfUnlock.replaceProtection",+ "These settings replace the PDF's current protection.",+ )}+ </Text>+ )}+ <AddPasswordSettings+ parameters={addPasswordParams.parameters}+ onParameterChange={addPasswordParams.updateParameter}+ disabled={endpointLoading}+ showOwnerPassword={false}+ />+ </Stack>),},{- title: t("changePermissions.title", "Document Permissions"),+ title: t("encryptedPdfUnlock.restrictActions", "Restrict actions"),isCollapsed: permissionsCollapsed,onCollapsedClick: hasResults? handleSettingsReset: () => setCollapsedPermissions(!collapsedPermissions),content: (- <ChangePermissionsSettings- parameters={addPasswordParams.permissions.parameters}- onParameterChange={addPasswordParams.permissions.updateParameter}- disabled={endpointLoading || addPasswordOperation.isLoading}- isLoading={permissions.isLoading}- hasReadError={permissions.hasError}- multipleFiles={selectedFiles.length > 1}- />+ <Stack gap="sm">+ <ChangePermissionsSettings+ parameters={addPasswordParams.permissions.parameters}+ onParameterChange={addPasswordParams.permissions.updateParameter}+ disabled={endpointLoading || addPasswordOperation.isLoading}+ isLoading={permissions.isLoading}+ hasReadError={permissions.hasError}+ />+ {hasRestrictions && (+ <PasswordInput+ size="xs"+ label={t(+ "encryptedPdfUnlock.newOwnerPassword",+ "New permissions password",+ )}+ value={addPasswordParams.parameters.ownerPassword}+ onChange={(event) =>+ addPasswordParams.updateParameter(+ "ownerPassword",+ event.currentTarget.value,+ )+ }+ error={+ addPasswordParams.parameters.ownerPassword &&+ addPasswordParams.parameters.ownerPassword ===+ addPasswordParams.parameters.password+ ? t(+ "encryptedPdfUnlock.passwordsMustDiffer",+ "The two passwords must be different.",+ )+ : undefined+ }+ required+ autoComplete="new-password"+ disabled={addPasswordOperation.isLoading}+ />+ )}+ </Stack>),tooltip: addPasswordPermissionsTips,},],executeButton: {- text: t("addPassword.submit", "Encrypt"),+ text: t("encryptedPdfUnlock.saveProtection", "Save protection"),isVisible: !hasResults,loadingText: t("loading"),onClick: handleAddPassword,endpointEnabled: endpointEnabled,- paramsValid: addPasswordParams.validateParameters(),+ paramsValid: validateAddPasswordParameters(outputParameters),disabled: permissions.isLoading,},review: {+ protectionSummary: t(+ "encryptedPdfUnlock.protectionSaved",+ "Protection saved",+ ),isVisible: hasResults,operation: addPasswordOperation,title: t("addPassword.results.title", "Encrypted PDFs"),diff --git a/frontend/editor/src/core/tools/ChangePermissions.tsx b/frontend/editor/src/core/tools/ChangePermissions.tsxindex 3a8f6eb4f7..a398873924 100644--- a/frontend/editor/src/core/tools/ChangePermissions.tsx+++ b/frontend/editor/src/core/tools/ChangePermissions.tsx@@ -1,3 +1,5 @@+import { useState } from "react";+import { Checkbox, Group, Stack, PasswordInput, Text } from "@mantine/core";import { useTranslation } from "react-i18next";import { createToolFlow } from "@app/components/tools/shared/createToolFlow";import ChangePermissionsSettings from "@app/components/tools/changePermissions/ChangePermissionsSettings";@@ -7,9 +9,12 @@ import { usePermissionExtraction } from "@app/hooks/tools/changePermissions/usePimport { useChangePermissionsTips } from "@app/components/tooltips/useChangePermissionsTips";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";const ChangePermissions = (props: BaseToolProps) => {const { t } = useTranslation();+ const [replaceOwnerPassword, setReplaceOwnerPassword] = useState(false);const changePermissionsTips = useChangePermissionsTips();const base = useBaseTool(@@ -17,7 +22,9 @@ const ChangePermissions = (props: BaseToolProps) => {useChangePermissionsParameters,useChangePermissionsOperation,props,- { skipResetParamsOnFirstFiles: true },+ {+ skipResetParamsOnFirstFiles: true,+ },);const permissions = usePermissionExtraction(@@ -25,6 +32,25 @@ const ChangePermissions = (props: BaseToolProps) => {base.params.setParameters,!base.operation.isLoading && !base.hasResults,);+ usePdfAccess(base.selectedFiles[0]);+ const protectedInput =+ base.selectedFiles.length > 0 &&+ base.selectedFiles.every((file) => {+ const access = getPdfAccess(file);+ return access?.encrypted && access.hasOwnerPassword !== false;+ });+ const ownerVerified =+ protectedInput &&+ base.selectedFiles.every(+ (file) => getPdfAccess(file)?.ownerAuthenticated === true,+ );+ const enforcementOff = base.selectedFiles.every(+ (file) => getPdfAccess(file)?.honorOwnerPasswords === false,+ );+ const showOwnerPassword =+ !protectedInput ||+ replaceOwnerPassword ||+ !!base.params.parameters.ownerPassword;return createToolFlow({files: {@@ -40,14 +66,75 @@ const ChangePermissions = (props: BaseToolProps) => {: undefined,tooltip: changePermissionsTips,content: (- <ChangePermissionsSettings- parameters={base.params.parameters}- onParameterChange={base.params.updateParameter}- disabled={base.endpointLoading || base.operation.isLoading}- isLoading={permissions.isLoading}- hasReadError={permissions.hasError}- multipleFiles={base.selectedFiles.length > 1}- />+ <Stack>+ {protectedInput && (+ <>+ <Group justify="space-between" gap="xs">+ <Text size="sm">+ {t(+ "encryptedPdfUnlock.ownerPassword",+ "Permissions password",+ )}+ </Text>+ <Text size="xs">+ {enforcementOff+ ? t(+ "encryptedPdfUnlock.passwordRetained",+ "Kept unchanged",+ )+ : ownerVerified+ ? t(+ "encryptedPdfUnlock.verifiedForSession",+ "Verified for this session",+ )+ : t(+ "encryptedPdfUnlock.requiredToApply",+ "Required to apply changes",+ )}+ </Text>+ </Group>+ <Checkbox+ label={t(+ "encryptedPdfUnlock.changeOwnerPassword",+ "Change permissions password",+ )}+ checked={showOwnerPassword}+ onChange={(event) => {+ setReplaceOwnerPassword(event.currentTarget.checked);+ if (!event.currentTarget.checked)+ base.params.updateParameter("ownerPassword", "");+ }}+ disabled={base.operation.isLoading}+ />+ </>+ )}+ {showOwnerPassword && (+ <PasswordInput+ size="xs"+ label={t(+ "encryptedPdfUnlock.newOwnerPassword",+ "New permissions password",+ )}+ value={base.params.parameters.ownerPassword ?? ""}+ onChange={(e) =>+ base.params.updateParameter(+ "ownerPassword",+ e.currentTarget.value,+ )+ }+ disabled={base.operation.isLoading}+ required+ autoComplete="new-password"+ />+ )}+ <ChangePermissionsSettings+ parameters={base.params.parameters}+ onParameterChange={base.params.updateParameter}+ disabled={base.endpointLoading || base.operation.isLoading}+ isLoading={permissions.isLoading}+ hasReadError={permissions.hasError}+ />+ </Stack>),},],@@ -57,10 +144,16 @@ const ChangePermissions = (props: BaseToolProps) => {loadingText: t("loading"),onClick: base.handleExecute,endpointEnabled: base.endpointEnabled,- paramsValid: base.params.validateParameters(),+ paramsValid:+ base.params.validateParameters() &&+ (!showOwnerPassword || !!base.params.parameters.ownerPassword),disabled: permissions.isLoading,},review: {+ protectionSummary: t(+ "encryptedPdfUnlock.protectionSaved",+ "Protection saved",+ ),isVisible: base.hasResults,operation: base.operation,title: t("changePermissions.results.title", "Modified PDFs"),diff --git a/frontend/editor/src/core/tools/RemovePassword.tsx b/frontend/editor/src/core/tools/RemovePassword.tsxindex effe5e8557..410c5f098d 100644--- a/frontend/editor/src/core/tools/RemovePassword.tsx+++ b/frontend/editor/src/core/tools/RemovePassword.tsx@@ -1,15 +1,23 @@import { useTranslation } from "react-i18next";+import { useEffect, useState } from "react";import { createToolFlow } from "@app/components/tools/shared/createToolFlow";-import RemovePasswordSettings from "@app/components/tools/removePassword/RemovePasswordSettings";import { useRemovePasswordParameters } from "@app/hooks/tools/removePassword/useRemovePasswordParameters";import { useRemovePasswordOperation } from "@app/hooks/tools/removePassword/useRemovePasswordOperation";import { useRemovePasswordTips } from "@app/components/tooltips/useRemovePasswordTips";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 { 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",@@ -17,6 +25,123 @@ const RemovePassword = (props: BaseToolProps) => {useRemovePasswordOperation,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 access = getPdfAccess(file);+ return access?.encrypted && access.hasOwnerPassword !== false;+ }).length;+ const openingSet = protectionKnown && openingCount > 0;+ const ownerSet = protectionKnown && ownerCount > 0;+ const passwordDescription = (count: number) => {+ if (!base.hasFiles) return undefined;+ if (!protectionKnown)+ return checkingProtection+ ? t("removePassword.checkingProtection", "Checking protection…")+ : t(+ "removePassword.protectionUnavailable",+ "Unable to check protection",+ );+ if (count === 0) return t("removePassword.notSet", "Not set");+ if (count < base.selectedFiles.length)+ return t(+ "removePassword.appliesTo",+ "Set on {{count}} of {{total}} PDFs",+ {+ count,+ total: base.selectedFiles.length,+ },+ );+ return undefined;+ };+ const { password, ownerPassword } = base.params.parameters;+ const updateParameter = base.params.updateParameter;+ useEffect(() => {+ if (base.hasResults || base.operation.isLoading || !protectionKnown) return;+ if (!openingSet && password) updateParameter("password", "");+ if (!ownerSet && ownerPassword) updateParameter("ownerPassword", "");+ }, [+ openingSet,+ ownerSet,+ password,+ ownerPassword,+ updateParameter,+ base.hasResults,+ base.operation.isLoading,+ protectionKnown,+ ]);++ const handleExecute = async () => {+ if (password && !ownerPassword) {+ for (const file of base.selectedFiles) {+ const access = getPdfAccess(file);+ if (+ access?.requiresOpeningPassword &&+ access.hasOwnerPassword !== false &&+ !access.ownerAuthenticated+ ) {+ const verified = await actions.requestPdfOwnerAccess(+ file.fileId,+ t("removePassword.title", "Remove Password"),+ t(+ "encryptedPdfUnlock.retainOwnerVerification",+ "Verify the permissions password to keep it unchanged while removing the opening password. This will not remove it.",+ ),+ );+ if (!verified) return;+ }+ }+ }+ 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();+ };return createToolFlow({files: {@@ -25,18 +150,49 @@ const RemovePassword = (props: BaseToolProps) => {},steps: [{- title: t("removePassword.password.stepTitle", "Remove Password"),+ title: t("removePassword.selectPasswords", "Passwords to remove"),isCollapsed: base.settingsCollapsed,onCollapsedClick: base.hasResults? base.handleSettingsReset: undefined,tooltip: removePasswordTips,content: (- <RemovePasswordSettings- parameters={base.params.parameters}- onParameterChange={base.params.updateParameter}- disabled={base.endpointLoading}- />+ <Stack gap="sm">+ <Text size="xs" c="dimmed">+ {t(+ "removePassword.keepBlank",+ "Leave a field blank to keep that password.",+ )}+ </Text>+ <PasswordInput+ size="xs"+ label={t(+ "encryptedPdfUnlock.openingPassword",+ "Password to open",+ )}+ description={passwordDescription(openingCount)}+ value={openingSet ? password : ""}+ onChange={(event) =>+ updateParameter("password", event.currentTarget.value)+ }+ disabled={!openingSet || base.operation.isLoading}+ autoComplete="off"+ />+ <PasswordInput+ size="xs"+ label={t(+ "encryptedPdfUnlock.ownerPassword",+ "Permissions password",+ )}+ description={passwordDescription(ownerCount)}+ value={ownerSet ? (ownerPassword ?? "") : ""}+ onChange={(event) =>+ updateParameter("ownerPassword", event.currentTarget.value)+ }+ disabled={!ownerSet || base.operation.isLoading}+ autoComplete="off"+ />+ </Stack>),},],@@ -44,14 +200,15 @@ const RemovePassword = (props: BaseToolProps) => {text: t("removePassword.submit", "Remove Password"),isVisible: !base.hasResults,loadingText: t("loading"),- onClick: base.handleExecute,+ onClick: handleExecute,endpointEnabled: base.endpointEnabled,- paramsValid: base.params.validateParameters(),+ paramsValid: (openingSet && !!password) || (ownerSet && !!ownerPassword),},review: {+ protectionSummary: removalSummary,isVisible: base.hasResults,operation: base.operation,- title: t("removePassword.results.title", "Decrypted PDFs"),+ title: t("removePassword.results.title", "Updated PDFs"),onFileClick: base.handleThumbnailClick,onUndo: base.handleUndo,},diff --git a/frontend/editor/src/core/tools/formFill/FormFill.tsx b/frontend/editor/src/core/tools/formFill/FormFill.tsxindex 62bb42889b..d29897887e 100644--- a/frontend/editor/src/core/tools/formFill/FormFill.tsx+++ b/frontend/editor/src/core/tools/formFill/FormFill.tsx@@ -16,7 +16,9 @@ import {ScrollArea,Progress,Tooltip,+ Stack,} from "@mantine/core";+import { createToolSteps } from "@app/components/tools/shared/ToolStep";import { UnsavedChangesDialog } from "@app/components/shared/UnsavedChangesDialog";import { SegmentedControl } from "@app/ui/SegmentedControl";import { Button } from "@app/ui/Button";@@ -31,6 +33,7 @@ import { useNavigation } from "@app/contexts/NavigationContext";import { useFieldShortcuts } from "@app/tools/formFill/useFieldShortcuts";import { serverMessage } from "@app/tools/formFill/useFormCommit";import { useViewer } from "@app/contexts/ViewerContext";+import { usePdfAccess } from "@app/hooks/usePdfAccess";import { useAllFiles, useFileState } from "@app/contexts/FileContext";import { Skeleton } from "@mantine/core";import { isStirlingFile, getFormFillFileId } from "@app/types/fileContext";@@ -136,7 +139,7 @@ const FormFill = (_props: BaseToolProps) => {const allValues = useAllFormValues();const { validationErrors } = formState;- const { scrollActions } = useViewer();+ const { scrollActions, activeFileId } = useViewer();const [flatten, setFlatten] = useState(false);const [extracting, setExtracting] = useState(false);@@ -197,8 +200,12 @@ const FormFill = (_props: BaseToolProps) => {// changes, so the panel kept showing the pre-hydration (or pre-version) file.const { files: activeFiles } = useAllFiles();const selectedFileIds = fileState.ui.selectedFileIds;- const currentFile = useMemo(() => {+ const viewedFile = useMemo(() => {if (activeFiles.length === 0) return null;+ const viewed = activeFiles.find(+ (file) => isStirlingFile(file) && file.fileId === activeFileId,+ );+ if (viewed) return viewed;if (selectedFileIds.length > 0) {const sel = activeFiles.find((f) => isStirlingFile(f) && selectedFileIds.includes(f.fileId),@@ -206,7 +213,9 @@ const FormFill = (_props: BaseToolProps) => {if (sel) return sel;}return activeFiles[0];- }, [activeFiles, selectedFileIds]);+ }, [activeFiles, selectedFileIds, activeFileId]);+ const pdfAccess = usePdfAccess(viewedFile);+ const currentFile = pdfAccess?.encrypted === false ? viewedFile : null;const handleExtractCsv = useCallback(async () => {if (!currentFile) return;@@ -491,6 +500,22 @@ const FormFill = (_props: BaseToolProps) => {}, [requiredFields, allValues]);if (!isActive) return null;+ if (viewedFile && pdfAccess?.encrypted) {+ return (+ <Stack gap="sm" p="sm">+ {createToolSteps().createFilesStep({ selectedFiles: [] })}+ </Stack>+ );+ }+ if (viewedFile && !currentFile) {+ return (+ <div className={styles.root}>+ <Text size="sm" role="status">+ {t("loading", "Loading...")}+ </Text>+ </div>+ );+ }const changeCount =pendingFields.length +diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsxindex c80d243249..4984b0a0b6 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx@@ -42,6 +42,7 @@ import { SaveRiskModal } from "@app/tools/pdfTextEditor/components/SaveRiskModalimport { DiscardChangesModal } from "@app/tools/pdfTextEditor/components/DiscardChangesModal";import { HelpOverlay } from "@app/tools/pdfTextEditor/components/HelpOverlay";import { PasswordPromptModal } from "@app/tools/pdfTextEditor/components/PasswordPromptModal";+import { PermissionsPasswordButton } from "@app/tools/pdfTextEditor/components/PermissionsPasswordButton";import { EditorPanelActions } from "@app/tools/pdfTextEditor/components/EditorPanelActions";import { EditorSidebar } from "@app/tools/pdfTextEditor/components/EditorSidebar";import { MobileEditorSheets } from "@app/tools/pdfTextEditor/components/MobileEditorSheets";@@ -751,7 +752,19 @@ export default function PdfTextEditor(_props: BaseToolProps) {>{state.error && (<Alert color="red" m="sm" data-testid="pdf-editor-error">- {state.error}+ <Stack gap="xs">+ <Text size="sm">{state.error}</Text>+ <PermissionsPasswordButton+ file={+ pendingDiskFileRef.current ??+ (sourceFileId ? selectors.getFile(sourceFileId) : null)+ }+ onVerified={(file) => {+ if (pendingDiskFileRef.current === file) loadDiskFile(file);+ else void load(file);+ }}+ />+ </Stack></Alert>)}<EditorFileInputs onPickPdf={onPickPdf} onPickImage={handleInsertImage} />diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsxindex 2b00c8a1ca..847c994fde 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsx@@ -18,7 +18,9 @@ describe("password retry dismissal", () => {</MantineProvider>);const { rerender } = render(modal(true));- expect(screen.queryByTestId("pdf-editor-password-cancel")).toBeNull();+ expect(+ screen.queryByRole("button", { name: /^cancel$/i }),+ ).not.toBeInTheDocument();expect(document.querySelector(".mantine-Modal-close")).toBeNull();fireEvent.keyDown(document.body, { key: "Escape" });const overlay = document.querySelector(".mantine-Modal-overlay");diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsxnew file mode 100644index 0000000000..cfd58a3a15--- /dev/null+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.test.tsx@@ -0,0 +1,162 @@+import { MantineProvider } from "@mantine/core";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import apiClient from "@app/services/apiClient";+import {+ clearPdfAccess,+ getPdfAccess,+ rememberPdfAccess,+ type PdfAccess,+} from "@app/services/pdfPasswordStore";+import { PermissionsPasswordButton } from "@app/tools/pdfTextEditor/components/PermissionsPasswordButton";++vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));+const post = vi.mocked(apiClient.post);+const reader: PdfAccess = {+ encrypted: true,+ password: "reader-password",+ openingAuthenticated: true,+ ownerAuthenticated: false,+ signed: false,+ permissions: 0,+ canModify: false,+ canAssemble: false,+ pageCount: 1,+ honorOwnerPasswords: true,+};++beforeEach(() => {+ post.mockReset();+});+afterEach(() => {+ cleanup();+ clearPdfAccess();+});++function setup(access = reader) {+ const file = new File(["pdf"], "restricted.pdf", { type: "application/pdf" });+ rememberPdfAccess(file, access);+ const onVerified = vi.fn();+ render(+ <MantineProvider env="test">+ <PermissionsPasswordButton file={file} onVerified={onVerified} />+ </MantineProvider>,+ );+ return { file, onVerified };+}++describe("editor permissions verification", () => {+ it("keeps a cancelled document restricted and allows retrying", () => {+ const { file, onVerified } = setup();+ fireEvent.click(+ screen.getByRole("button", { name: "Enter permissions password" }),+ );+ expect(+ screen.getByLabelText("Permissions password", { exact: true }),+ ).toBeVisible();+ expect(+ screen.queryByLabelText("Password to open", { exact: true }),+ ).not.toBeInTheDocument();+ fireEvent.change(+ screen.getByLabelText("Permissions password", { exact: true }),+ { target: { value: "discard-this" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ expect(onVerified).not.toHaveBeenCalled();+ expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);+ fireEvent.click(+ screen.getByRole("button", { name: "Enter permissions password" }),+ );+ expect(+ screen.getByLabelText("Permissions password", { exact: true }),+ ).toHaveValue("");+ });++ it("rejects an opening credential and resumes only after owner verification", async () => {+ const { file, onVerified } = setup();+ post.mockResolvedValueOnce({ data: reader });+ fireEvent.click(+ screen.getByRole("button", { name: "Enter permissions password" }),+ );+ fireEvent.change(+ screen.getByLabelText("Permissions password", { exact: true }),+ { target: { value: "reader-password" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ expect(+ await screen.findByText(+ "Enter the permissions password to allow restricted actions.",+ ),+ ).toBeVisible();+ expect(onVerified).not.toHaveBeenCalled();+ expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);++ post.mockResolvedValueOnce({+ data: {+ ...reader,+ openingAuthenticated: false,+ ownerAuthenticated: true,+ canModify: true,+ },+ });+ fireEvent.change(+ screen.getByLabelText("Permissions password", { exact: true }),+ { target: { value: "owner-password" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ await waitFor(() => expect(onVerified).toHaveBeenCalledWith(file));+ expect(getPdfAccess(file)).toMatchObject({+ password: "owner-password",+ openingPassword: "reader-password",+ ownerAuthenticated: true,+ });+ });++ it("discards a verification response after the action unmounts", async () => {+ const { file, onVerified } = setup();+ let complete!: (response: { data: PdfAccess }) => void;+ post.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ complete = resolve;+ }),+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Enter permissions password" }),+ );+ fireEvent.change(+ screen.getByLabelText("Permissions password", { exact: true }),+ { target: { value: "owner-password" } },+ );+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ cleanup();+ await act(async () =>+ complete({ data: { ...reader, ownerAuthenticated: true } }),+ );+ expect(onVerified).not.toHaveBeenCalled();+ expect(getPdfAccess(file)?.ownerAuthenticated).toBe(false);+ });++ it.each([+ { signed: true },+ { encrypted: false },+ { canModify: true },+ { ownerAuthenticated: true },+ { honorOwnerPasswords: false },+ ])("does not request owner verification for %j", (access) => {+ setup({ ...reader, ...access });+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsxnew file mode 100644index 0000000000..43840a1897--- /dev/null+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PermissionsPasswordButton.tsx@@ -0,0 +1,113 @@+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";+import { Button } from "@app/ui/Button";+import { handlePasswordError } from "@app/utils/toolErrorHandler";++/** Verifies editing permission for the failed document before retrying its existing load flow. */+export function PermissionsPasswordButton({+ file,+ onVerified,+}: {+ file: File | null | undefined;+ onVerified: (file: File) => void;+}) {+ const { t } = useTranslation();+ const access = usePdfAccess(file);+ const [opened, setOpened] = useState(false);+ const [password, setPassword] = useState("");+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const pending = useRef<CancelTokenSource | null>(null);++ useEffect(() => {+ setOpened(false);+ setPassword("");+ setError(null);+ setBusy(false);+ return () => pending.current?.cancel();+ }, [file]);++ if (+ !file ||+ !access?.encrypted ||+ access.signed ||+ access.canModify ||+ hasPdfPermissionOverride(access)+ )+ return null;++ const verify = async () => {+ if (busy || !password) return;+ const cancellation = axios.CancelToken.source();+ pending.current = cancellation;+ setBusy(true);+ setError(null);+ try {+ const verified = await unlockPdfForSession(+ file,+ password,+ cancellation.token,+ );+ cancellation.token.throwIfRequested();+ if (!verified.ownerAuthenticated) {+ setError(+ t(+ "encryptedPdfUnlock.ownerRequired",+ "Enter the permissions password to allow restricted actions.",+ ),+ );+ return;+ }+ rememberPdfAccess(file, verified);+ setOpened(false);+ setPassword("");+ onVerified(file);+ } catch (failure) {+ if (!axios.isCancel(failure)) {+ const message = await handlePasswordError(+ failure,+ t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),+ t(+ "encryptedPdfUnlock.sessionFailed",+ "Unable to verify this password. Please try again.",+ ),+ );+ if (!cancellation.token.reason) setError(message);+ }+ } finally {+ if (!cancellation.token.reason) setBusy(false);+ }+ };++ return (+ <>+ <Button size="sm" variant="secondary" onClick={() => setOpened(true)}>+ {t("encryptedPdfUnlock.ownerTitle", "Enter permissions password")}+ </Button>+ <EncryptedPdfUnlockModal+ opened={opened}+ fileName={file.name}+ password={password}+ errorMessage={error}+ sessionUnlock+ ownerUnlock+ isProcessing={busy}+ onPasswordChange={setPassword}+ onUnlock={() => void verify()}+ onSkip={() => {+ setOpened(false);+ setPassword("");+ setError(null);+ }}+ />+ </>+ );+}diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsxindex e3c94f4f39..4aed0e5bf6 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx@@ -68,7 +68,7 @@ export function ScanHint({<Tooltipcontent={t("encryptedPdfUnlock.removePasswordHelp",- "Open Remove Password to create an unprotected copy.",+ "Open Remove Password to choose which passwords to remove.",)}position="top"maxWidth={230}diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.tsindex b1cf8e313c..bc6d63a916 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts@@ -7,8 +7,15 @@ import {} from "@app/services/pdfiumService";import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";import type { PageSnapshot } from "@app/tools/pdfTextEditor/types";-import { getPdfAccess } from "@app/services/pdfPasswordStore";-import { assertPdfSessionEditable } from "@app/services/pdfSessionUnlock";+import {+ getPdfAccess,+ rememberPdfAccess,+} from "@app/services/pdfPasswordStore";+import {+ assertPdfSessionEditable,+ ensurePdfAccess,+ unlockPdfForSession,+} from "@app/services/pdfSessionUnlock";import { detectSaveRisks } from "@app/tools/pdfTextEditor/util/documentRisks";const EAGER_PAGE_LIMIT = 5;@@ -43,11 +50,24 @@ 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;+ }+ 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.tsxindex 0d52bed693..ed1231ef83 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx@@ -146,7 +146,7 @@ describe("editor inline OCR", () => {source === "native" ? null : ("source-id" as FileId),);expect(result.current.available).toBe(true);- expect(result.current.blockedReason).toContain("password protection");+ expect(result.current.blockedReason).toContain("protection");await act(() => result.current.runOcr());expect(mocks.checkCredits).not.toHaveBeenCalled();expect(mocks.exportPdf).not.toHaveBeenCalled();@@ -169,7 +169,7 @@ describe("editor inline OCR", () => {await act(() => result.current.runOcr());expect(mocks.post).not.toHaveBeenCalled();expect(onComplete).not.toHaveBeenCalled();- expect(store.getState().error).toContain("password protection");+ expect(store.getState().error).toContain("protection");});it("rejects OCR output if source protection changes while the request is pending", async () => {@@ -189,7 +189,7 @@ describe("editor inline OCR", () => {expect(onComplete).not.toHaveBeenCalled();expect(store.getState()).toMatchObject({loading: false,- error: expect.stringContaining("password protection"),+ error: expect.stringContaining("protection"),});});@@ -197,7 +197,7 @@ describe("editor inline OCR", () => {const { result } = await setup();expect(result.current.blockedReason).toBeNull();act(protectSource);- expect(result.current.blockedReason).toContain("password protection");+ expect(result.current.blockedReason).toContain("protection");});it("posts the current editor bytes through the app client and applies the OCR PDF", async () => {diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.tsindex 5c065bcbd0..6968b277a3 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts@@ -16,7 +16,7 @@ export function getEditorOcrBlockedReason() {return t("pdfTextEditor.inspector.ocrProtected",- "OCR cannot keep this PDF's password protection. Use Remove Password to create an unprotected copy first.",+ "OCR cannot yet preserve this PDF's protection. The protected original remains available for viewing.",);}return null;diff --git a/frontend/editor/src/core/tools/stamp/createStampTool.tsx b/frontend/editor/src/core/tools/stamp/createStampTool.tsxindex 9efcf62b1a..cda85929be 100644--- a/frontend/editor/src/core/tools/stamp/createStampTool.tsx+++ b/frontend/editor/src/core/tools/stamp/createStampTool.tsx@@ -73,6 +73,7 @@ export const createStampTool = (config: StampToolConfig) => {applySignaturesRef,signatureApiRef,getImageData,+ signaturesApplied,setSignaturesApplied,placedSignatures,setApplyingSignatures,@@ -153,8 +154,11 @@ export const createStampTool = (config: StampToolConfig) => {}, [base.params.parameters, setSignatureConfig]);useEffect(() => {- if (placedSignatures.length > 0) setHasUnsavedChanges(true);- }, [placedSignatures, setHasUnsavedChanges]);+ // Permission checks can reconnect the old stamp list while the saved PDF opens.+ if (placedSignatures.length > 0 && !signaturesApplied) {+ setHasUnsavedChanges(true);+ }+ }, [placedSignatures, signaturesApplied, setHasUnsavedChanges]);const handleSaveToSystem = useCallback(async () => {if (applyInFlightRef.current) return false;diff --git a/frontend/editor/src/core/types/appConfig.ts b/frontend/editor/src/core/types/appConfig.tsindex e47b909bd4..2dec90ca65 100644--- a/frontend/editor/src/core/types/appConfig.ts+++ b/frontend/editor/src/core/types/appConfig.ts@@ -7,6 +7,7 @@ export interface AppConfig {languages?: string[];defaultLocale?: string;enableLogin?: boolean;+ honorOwnerPasswords?: boolean;showSettingsWhenNoLogin?: boolean;enableEmailInvites?: boolean;enableOAuth?: boolean;diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.tsindex 482d7c1acc..edbb94373e 100644--- a/frontend/editor/src/core/types/fileContext.ts+++ b/frontend/editor/src/core/types/fileContext.ts@@ -484,6 +484,14 @@ export interface FileContextActions {scheduleCleanup: (fileId: FileId, delay?: number) => void;cleanupFile: (fileId: FileId) => void;openEncryptedUnlockPrompt: (fileId: FileId) => void;+ /** Resolves false on cancellation or document closure; never exposes the credential. */+ requestPdfOwnerAccess: (+ fileId: FileId,+ action: string,+ preservationReason?: string,+ ) => Promise<boolean>;+ /** Creates a separate unprotected version after verifying owner access. */+ createUnprotectedCopy: (fileId: FileId) => Promise<void>;/** Authenticates preview bytes without adding a library record. Abort when the preview closes. */unlockPreviewPdf: (file: File,diff --git a/frontend/editor/src/core/utils/copyText.test.ts b/frontend/editor/src/core/utils/copyText.test.tsnew file mode 100644index 0000000000..44e3b65109--- /dev/null+++ b/frontend/editor/src/core/utils/copyText.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, test, vi } from "vitest";+import { copyText } from "@app/utils/copyText";++function setSecureContext(secure: boolean) {+ Object.defineProperty(window, "isSecureContext", {+ configurable: true,+ value: secure,+ });+}++function setClipboard(writeText?: (text: string) => Promise<void>) {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: writeText ? { writeText } : undefined,+ });+}++function stubExecCommand(result: boolean) {+ const execCommand = vi.fn(() => result);+ Object.defineProperty(document, "execCommand", {+ configurable: true,+ value: execCommand,+ });+ return execCommand;+}++describe("copyText", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ test("uses the async clipboard API in secure contexts", async () => {+ setSecureContext(true);+ const writeText = vi.fn().mockResolvedValue(undefined);+ setClipboard(writeText);+ const execCommand = stubExecCommand(true);++ await expect(copyText("hello")).resolves.toBe(true);+ expect(writeText).toHaveBeenCalledWith("hello");+ expect(execCommand).not.toHaveBeenCalled();+ });++ test("falls back to execCommand over plain HTTP", async () => {+ setSecureContext(false);+ setClipboard(undefined);+ const execCommand = stubExecCommand(true);++ await expect(copyText("hello")).resolves.toBe(true);+ expect(execCommand).toHaveBeenCalledWith("copy");+ expect(document.querySelector("textarea")).toBeNull();+ });++ test("falls back to execCommand when the async write is rejected", async () => {+ setSecureContext(true);+ setClipboard(vi.fn().mockRejectedValue(new Error("denied")));+ const execCommand = stubExecCommand(true);++ await expect(copyText("hello")).resolves.toBe(true);+ expect(execCommand).toHaveBeenCalledWith("copy");+ });++ test("reports failure when no clipboard path succeeds", async () => {+ setSecureContext(false);+ setClipboard(undefined);+ stubExecCommand(false);++ await expect(copyText("hello")).resolves.toBe(false);+ });++ test("does not copy empty text", async () => {+ setSecureContext(false);+ const execCommand = stubExecCommand(true);++ await expect(copyText("")).resolves.toBe(false);+ expect(execCommand).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/utils/copyText.ts b/frontend/editor/src/core/utils/copyText.tsnew file mode 100644index 0000000000..a323238ba3--- /dev/null+++ b/frontend/editor/src/core/utils/copyText.ts@@ -0,0 +1,40 @@+/**+ * Writes text to the clipboard and reports whether it landed.+ *+ * `navigator.clipboard` only exists in secure contexts, so self-hosted servers+ * reached over plain HTTP fall back to `execCommand("copy")`. That fallback only+ * works inside the user gesture: over HTTP it runs before any await, but after a+ * rejected async write the gesture may have expired and it can fail.+ */+export async function copyText(text: string): Promise<boolean> {+ if (!text) return false;+ if (window.isSecureContext && navigator.clipboard?.writeText) {+ try {+ await navigator.clipboard.writeText(text);+ return true;+ } catch {+ return copyWithExecCommand(text);+ }+ }+ return copyWithExecCommand(text);+}++function copyWithExecCommand(text: string): boolean {+ const previousFocus = document.activeElement as HTMLElement | null;+ const textarea = document.createElement("textarea");+ textarea.value = text;+ textarea.setAttribute("readonly", "");+ textarea.style.position = "fixed";+ textarea.style.opacity = "0";+ textarea.style.pointerEvents = "none";+ document.body.appendChild(textarea);+ textarea.select();+ try {+ return document.execCommand("copy");+ } catch {+ return false;+ } finally {+ textarea.remove();+ previousFocus?.focus?.({ preventScroll: true });+ }+}diff --git a/frontend/editor/src/desktop/services/fileImportPaths.test.ts b/frontend/editor/src/desktop/services/fileImportPaths.test.tsindex 0487a4bffc..7a9148aa2c 100644--- a/frontend/editor/src/desktop/services/fileImportPaths.test.ts+++ b/frontend/editor/src/desktop/services/fileImportPaths.test.ts@@ -29,7 +29,7 @@ vi.mock("@app/utils/thumbnailUtils", () => ({generateThumbnailPairWithMetadata: vi.fn(),}));vi.mock("@app/services/fileAnalyzer", () => ({- FileAnalyzer: { isPDFUserPasswordProtected: async () => false },+ FileAnalyzer: { isPDFEncrypted: async () => false },}));vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsxindex e1d6796495..481b77bb10 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx@@ -3,6 +3,7 @@ import { TierBadge } from "@app/components/shared/config/TierBadge";import { useLocation } from "react-router-dom";import { useTranslation } from "react-i18next";import { SettingsCard } from "@app/components/shared/config/SettingsCard";+import { SettingsToggleRow } from "@app/components/shared/config/SettingsToggleRow";import { Stack, Loader } from "@mantine/core";import { alert } from "@app/components/toast";import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";@@ -165,6 +166,30 @@ export default function AdminSecurityPage() {return (<div className="settings-section-container"><Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="pdfPermissions"+ title={t("admin.settings.security.pdfPermissions", "PDF permissions")}+ >+ <SettingsToggleRow+ label={t(+ "admin.settings.security.honorOwnerPasswords.label",+ "Honor PDF permissions",+ )}+ info={t(+ "admin.settings.security.honorOwnerPasswords.description",+ "Require the permissions password for restricted actions. Turning this off still requires passwords needed to open PDFs.",+ )}+ pending={security.isFieldPending("honorOwnerPasswords")}+ checked={security.settings?.honorOwnerPasswords ?? true}+ disabled={!loginEnabled}+ onChange={(checked) =>+ security.setSettings({+ ...security.settings,+ honorOwnerPasswords: checked,+ })+ }+ />+ </SettingsCard><SettingsCardid="securityAuthentication"title={t("admin.settings.security.authentication", "Authentication")}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.tsindex b58aadbf74..d063ae2ebb 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.test.ts@@ -4,12 +4,35 @@ import apiClient from "@app/services/apiClient";import {fetchConnectionsSettings,saveConnectionsSettings,+ fetchSecuritySettings,+ saveSecuritySettings,} from "@app/components/shared/config/configSections/security/securitySettingsTransformers";vi.mock("@app/services/apiClient", () => ({default: { get: vi.fn() },}));+describe("PDF owner-password policy", () => {+ it("keeps an explicit disabled setting through pending changes and save", async () => {+ vi.mocked(apiClient.get).mockImplementation(async (url) => ({+ data: url.endsWith("/security")+ ? {+ honorOwnerPasswords: true,+ _pending: { honorOwnerPasswords: false },+ }+ : {},+ }));+ const settings = await fetchSecuritySettings();+ expect(settings.honorOwnerPasswords).toBe(true);+ expect(settings._pending?.honorOwnerPasswords).toBe(false);+ expect(+ saveSecuritySettings({ honorOwnerPasswords: false }).deltaSettings[+ "security.honorOwnerPasswords"+ ],+ ).toBe(false);+ });+});+describe("SSO auto-login security setting", () => {beforeEach(() => vi.clearAllMocks());diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.tsindex f01bda1056..8a627de7b9 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts@@ -75,6 +75,7 @@ export function saveSecuritySettings(const deltaSettings: Record<string, unknown> = {"security.enableLogin": securitySettings.enableLogin,+ "security.honorOwnerPasswords": securitySettings.honorOwnerPasswords,"security.loginMethod": securitySettings.loginMethod,"security.loginAttemptCount": securitySettings.loginAttemptCount,"security.loginResetTimeMinutes": securitySettings.loginResetTimeMinutes,diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.tsindex cbd8087ba6..a68ed0aab4 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts@@ -3,6 +3,7 @@export interface SecuritySettingsData {enableLogin?: boolean;+ honorOwnerPasswords?: boolean;loginMethod?: string;loginAttemptCount?: number;loginResetTimeMinutes?: number;