Skip to content

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

Unlock protected PDFs for viewing and common tools without removing passwords (#8393)

ConnorYohf49885803a5d
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java
new file mode 100644
index 0000000000..9fd06587f6
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityController.java
@@ -0,0 +1,129 @@
+package stirling.software.SPDF.controller.api.security;
+
+import java.io.IOException;
+import java.nio.file.Files;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
+import org.springframework.core.io.Resource;
+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 io.swagger.v3.oas.annotations.Operation;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
+import stirling.software.common.annotations.api.SecurityApi;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.TempFile;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.WebResponseUtils;
+import stirling.software.jpdfium.doc.PdfSecurity;
+import stirling.software.jpdfium.exception.JPDFiumException;
+
+/**
+ * Stateless helpers for interactive unlocking. Neither endpoint retains credentials or documents.
+ */
+@SecurityApi
+@RequiredArgsConstructor
+public class PdfSessionSecurityController {
+ private final CustomPDFDocumentFactory pdfDocumentFactory;
+ private final TempFileManager tempFileManager;
+
+ /**
+ * Passwords are never returned; permissions describe the authenticated access to the original
+ * bytes.
+ */
+ public record SecurityInfo(
+ boolean encrypted,
+ boolean signed,
+ boolean ownerAuthenticated,
+ int permissions,
+ int encryptionKeyLength,
+ int encryptionRevision,
+ boolean canModify,
+ boolean canAssemble,
+ int pageCount) {}
+
+ /** 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 {
+ try (PDDocument document =
+ pdfDocumentFactory.load(request.getFileInput(), request.getPassword(), true)) {
+ AccessPermission permission = document.getCurrentAccessPermission();
+ return new SecurityInfo(
+ document.isEncrypted(),
+ !document.getSignatureDictionaries().isEmpty(),
+ permission.isOwnerPermission(),
+ document.isEncrypted()
+ ? document.getEncryption().getPermissions()
+ : permission.getPermissionBytes(),
+ document.isEncrypted() ? document.getEncryption().getLength() : 0,
+ document.isEncrypted() ? document.getEncryption().getRevision() : 0,
+ permission.canModify(),
+ permission.canAssembleDocument(),
+ document.getNumberOfPages());
+ }
+ }
+
+ /**
+ * Restore the source's encryption, including an unknown second password, before returning a
+ * processed PDF.
+ */
+ @Operation(hidden = true)
+ @PostMapping(value = "/restore-pdf-protection", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ public ResponseEntity<Resource> restore(
+ @RequestParam MultipartFile fileInput,
+ @RequestParam MultipartFile sourceFile,
+ @RequestParam String password)
+ throws IOException {
+ int sourcePermissions;
+ int sourceKeyLength;
+ int sourceRevision;
+ try (PDDocument source = pdfDocumentFactory.load(sourceFile, password, true)) {
+ if (!source.isEncrypted())
+ throw new IOException("The protection source is not encrypted");
+ if (!source.getSignatureDictionaries().isEmpty())
+ throw new IOException("Protection restoration does not support signed source PDFs");
+ // Effective owner access is unrestricted even when the encryption dictionary is not.
+ sourcePermissions = source.getEncryption().getPermissions();
+ sourceKeyLength = source.getEncryption().getLength();
+ sourceRevision = source.getEncryption().getRevision();
+ }
+
+ TempFile output = tempFileManager.createManagedTempFile(".pdf");
+ boolean transferred = false;
+ try (TempFile input = new TempFile(tempFileManager, ".pdf");
+ TempFile source = new TempFile(tempFileManager, ".pdf")) {
+ fileInput.transferTo(input.getFile());
+ sourceFile.transferTo(source.getFile());
+ try {
+ PdfSecurity.copyEncryption(
+ input.getPath(), output.getPath(), source.getPath(), password);
+ } catch (JPDFiumException e) {
+ throw new IOException("Unable to restore PDF protection", e);
+ }
+ try (var stream = Files.newInputStream(output.getPath());
+ PDDocument protectedDocument =
+ pdfDocumentFactory.load(stream, password, true)) {
+ if (!protectedDocument.isEncrypted()
+ || protectedDocument.getEncryption().getPermissions() != sourcePermissions
+ || protectedDocument.getEncryption().getLength() != sourceKeyLength
+ || protectedDocument.getEncryption().getRevision() != sourceRevision)
+ throw new IOException("Output protection verification failed");
+ }
+ var response =
+ WebResponseUtils.pdfFileToWebResponse(output, fileInput.getOriginalFilename());
+ transferred = true;
+ return response;
+ } finally {
+ if (!transferred) output.close();
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java
index 312cc5c040..7e702e4fb3 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
@@ -62,6 +62,10 @@ class ToolIODeclarationCoverageTest {
"/api/v1/convert/text-editor/pdf",
// Charcode lookup for the v2 editor: returns glyph mappings, not a document.
"/api/v1/general/pdf-text-editor",
+ // Interactive credential helpers, hidden from pipeline discovery; restoration
+ // requires the original protected document as well as the working result.
+ "/api/v1/security/inspect-pdf-security",
+ "/api/v1/security/restore-pdf-protection",
// 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.java
new file mode 100644
index 0000000000..121f587e01
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/PdfSessionSecurityControllerTest.java
@@ -0,0 +1,279 @@
+package stirling.software.SPDF.controller.api.security;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
+import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
+import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.web.multipart.MultipartFile;
+
+import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.TempFile;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.jpdfium.doc.PdfSecurity;
+import stirling.software.jpdfium.exception.JPDFiumException;
+
+class PdfSessionSecurityControllerTest {
+ private static final String USER = " reader password ";
+ private static final String OWNER = " owner password ";
+ @TempDir Path directory;
+ private PdfSessionSecurityController controller;
+ private CustomPDFDocumentFactory factory;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ factory = mock(CustomPDFDocumentFactory.class);
+ when(factory.load(any(MultipartFile.class), anyString(), eq(true)))
+ .thenAnswer(
+ inv ->
+ Loader.loadPDF(
+ inv.<MultipartFile>getArgument(0).getBytes(),
+ inv.getArgument(1)));
+ when(factory.load(any(InputStream.class), anyString(), eq(true)))
+ .thenAnswer(
+ inv ->
+ Loader.loadPDF(
+ inv.<InputStream>getArgument(0).readAllBytes(),
+ inv.getArgument(1)));
+ var tempFiles = mock(TempFileManager.class);
+ when(tempFiles.createTempFile(anyString()))
+ .thenAnswer(
+ inv ->
+ Files.createTempFile(directory, "unlock-", inv.getArgument(0))
+ .toFile());
+ when(tempFiles.createManagedTempFile(anyString()))
+ .thenAnswer(inv -> new TempFile(tempFiles, inv.getArgument(0)));
+ doAnswer(
+ inv -> {
+ Files.deleteIfExists(inv.<java.io.File>getArgument(0).toPath());
+ return null;
+ })
+ .when(tempFiles)
+ .deleteTempFile(any(java.io.File.class));
+ controller = new PdfSessionSecurityController(factory, tempFiles);
+ }
+
+ private byte[] pdf(boolean encrypted, int bits) throws IOException {
+ return pdf(encrypted, bits, true, USER, OWNER, 1);
+ }
+
+ private byte[] pdf(
+ boolean encrypted, int bits, boolean aes, String user, String owner, int pages)
+ throws IOException {
+ try (var document = new PDDocument();
+ var output = new ByteArrayOutputStream()) {
+ for (int page = 0; page < pages; page++) {
+ var pdfPage = new PDPage();
+ pdfPage.setRotation(90);
+ document.addPage(pdfPage);
+ }
+ if (encrypted) {
+ var permissions = new AccessPermission();
+ permissions.setCanPrint(false);
+ permissions.setCanExtractContent(false);
+ var policy = new StandardProtectionPolicy(owner, user, permissions);
+ policy.setEncryptionKeyLength(bits);
+ policy.setPreferAES(aes);
+ document.protect(policy);
+ }
+ document.save(output);
+ return output.toByteArray();
+ }
+ }
+
+ private MockMultipartFile upload(byte[] bytes) {
+ return new MockMultipartFile("fileInput", "document.pdf", "application/pdf", bytes);
+ }
+
+ @Test
+ void inspectAuthenticatesWithoutModifyingTheOriginal() throws Exception {
+ byte[] original = pdf(true, 256);
+ var request = new PDFPasswordRequest();
+ request.setFileInput(upload(original));
+ request.setPassword(USER);
+ var info = controller.inspect(request);
+ assertTrue(info.encrypted());
+ assertFalse(info.ownerAuthenticated());
+ assertFalse(info.signed());
+ assertEquals(1, info.pageCount());
+ assertEquals(0, info.permissions() & 4);
+ assertArrayEquals(original, request.getFileInput().getBytes());
+ request.setPassword(OWNER);
+ var ownerInfo = controller.inspect(request);
+ assertTrue(ownerInfo.ownerAuthenticated());
+ assertEquals(info.permissions(), ownerInfo.permissions());
+ assertEquals(256, ownerInfo.encryptionKeyLength());
+ assertEquals(6, ownerInfo.encryptionRevision());
+ request.setPassword("incorrect");
+ assertThrows(InvalidPasswordException.class, () -> controller.inspect(request));
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "40,false,false",
+ "40,false,true",
+ "128,false,false",
+ "128,false,true",
+ "128,true,false",
+ "128,true,true",
+ "256,true,false",
+ "256,true,true"
+ })
+ void restoresBothPasswordsAndRestrictionsFromEitherCredential(
+ int bits, boolean aes, boolean owner) throws Exception {
+ byte[] original = pdf(true, bits, aes, USER, OWNER, 1);
+ var sourceUpload = upload(original);
+ var response =
+ controller.restore(
+ upload(pdf(false, bits, aes, USER, OWNER, 3)),
+ sourceUpload,
+ owner ? OWNER : USER);
+ byte[] protectedBytes;
+ try (var body = response.getBody().getInputStream()) {
+ protectedBytes = body.readAllBytes();
+ }
+ assertThrows(InvalidPasswordException.class, () -> Loader.loadPDF(protectedBytes));
+ assertThrows(
+ InvalidPasswordException.class, () -> Loader.loadPDF(protectedBytes, "incorrect"));
+ try (var user = Loader.loadPDF(protectedBytes, USER);
+ var administrator = Loader.loadPDF(protectedBytes, OWNER)) {
+ assertTrue(user.isEncrypted());
+ assertFalse(user.getCurrentAccessPermission().canPrint());
+ assertFalse(user.getCurrentAccessPermission().canExtractContent());
+ assertEquals(bits, user.getEncryption().getLength());
+ assertEquals(3, user.getNumberOfPages());
+ assertEquals(90, user.getPage(0).getRotation());
+ assertTrue(administrator.getCurrentAccessPermission().isOwnerPermission());
+ }
+ assertArrayEquals(original, sourceUpload.getBytes());
+ try (var remaining = Files.list(directory)) {
+ assertEquals(0, remaining.count());
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"permissions,false", "permissions,true", "length,true", "revision,true"})
+ void rejectsChangedOutputProtection(String changed, boolean owner) throws Exception {
+ when(factory.load(any(InputStream.class), anyString(), eq(true)))
+ .thenAnswer(
+ inv -> {
+ var document =
+ Loader.loadPDF(
+ inv.<InputStream>getArgument(0).readAllBytes(),
+ inv.getArgument(1));
+ switch (changed) {
+ case "permissions" -> document.getEncryption().setPermissions(-4);
+ case "length" -> document.getEncryption().setLength(128);
+ case "revision" -> document.getEncryption().setRevision(4);
+ default -> throw new IllegalArgumentException(changed);
+ }
+ return document;
+ });
+ assertThrows(
+ IOException.class,
+ () ->
+ controller.restore(
+ upload(pdf(false, 256)),
+ upload(pdf(true, 256)),
+ owner ? OWNER : USER));
+ try (var remaining = Files.list(directory)) {
+ assertEquals(0, remaining.count());
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"128,false", "128,true", "256,false", "256,true"})
+ void preservesEscapedAndUnicodePasswords(int bits, boolean owner) throws Exception {
+ String readerPassword = bits == 256 ? " café\"読者\" " : " reader\n\"password\" ";
+ String ownerPassword = bits == 256 ? " 管理者\\\"owner\" " : " owner\\\n\"password\" ";
+ var response =
+ controller.restore(
+ upload(pdf(false, 256)),
+ upload(pdf(true, bits, true, readerPassword, ownerPassword, 1)),
+ owner ? ownerPassword : readerPassword);
+ byte[] protectedBytes;
+ try (var body = response.getBody().getInputStream()) {
+ protectedBytes = body.readAllBytes();
+ }
+ try (var reader = Loader.loadPDF(protectedBytes, readerPassword);
+ var administrator = Loader.loadPDF(protectedBytes, ownerPassword)) {
+ assertFalse(reader.getCurrentAccessPermission().canExtractContent());
+ assertTrue(administrator.getCurrentAccessPermission().isOwnerPermission());
+ }
+ }
+
+ @Test
+ void nativeFailureReturnsNoResultAndCleansTemporaryFiles() throws Exception {
+ assertThrows(
+ IOException.class,
+ () ->
+ controller.restore(
+ upload("invalid PDF".getBytes(StandardCharsets.UTF_8)),
+ upload(pdf(true, 256)),
+ USER));
+ try (var remaining = Files.list(directory)) {
+ assertEquals(0, remaining.count());
+ }
+ var validResponse =
+ controller.restore(upload(pdf(false, 256)), upload(pdf(true, 256)), USER);
+ try (var body = validResponse.getBody().getInputStream();
+ var document = Loader.loadPDF(body.readAllBytes(), USER)) {
+ assertTrue(document.isEncrypted());
+ }
+ }
+
+ @Test
+ void missingNativeSupportReturnsNoResultAndCleansTemporaryFiles() throws Exception {
+ try (var security = mockStatic(PdfSecurity.class)) {
+ security.when(() -> PdfSecurity.copyEncryption(any(), any(), any(), anyString()))
+ .thenThrow(new JPDFiumException("Native PDF protection is unavailable"));
+ assertThrows(
+ IOException.class,
+ () ->
+ controller.restore(
+ upload(pdf(false, 256)), upload(pdf(true, 256)), USER));
+ }
+ try (var remaining = Files.list(directory)) {
+ assertEquals(0, remaining.count());
+ }
+ }
+
+ @Test
+ void wrongPasswordDoesNotStartNativeProcessing() throws Exception {
+ try (var security = mockStatic(PdfSecurity.class)) {
+ assertThrows(
+ InvalidPasswordException.class,
+ () ->
+ controller.restore(
+ upload(pdf(false, 256)), upload(pdf(true, 256)), "incorrect"));
+ security.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ void refusesAnUnencryptedProtectionSource() throws Exception {
+ byte[] plaintext = pdf(false, 256);
+ assertThrows(
+ IOException.class,
+ () -> controller.restore(upload(plaintext), upload(plaintext), USER));
+ }
+}
diff --git a/build.gradle b/build.gradle
index df61c54d68..7d5874d859 100644
--- a/build.gradle
+++ b/build.gradle
@@ -43,7 +43,7 @@ ext {
bucket4jVersion = "8.19.0"
archunitVersion = "1.5.0"
batikVersion = "1.19"
- jpdfiumVersion = "1.1.5"
+ jpdfiumVersion = "1.1.6"
jwtVersion = "0.13.0"
awsSdkVersion = "2.54.13"
jschVersion = "2.28.7"
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 02b941e659..7004716ec4 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4491,22 +4491,35 @@ description = "Select the Edit Table of Contents tool to load its workspace."
title = "Open the tool to start editing"
[encryptedPdfUnlock]
-description = "This PDF is password protected. Enter the password so you can continue working with it."
-emptyResponse = "Password removal did not produce a file."
+copyCreated = "Unprotected copy created"
incorrectPassword = "Incorrect password"
missingFile = "The selected file is no longer available."
+originalProtected = "The original PDF stays protected."
+passwordHint = "Enter the PDF password to continue."
+prepareFailed = "Unable to prepare this protected PDF for processing."
+removePasswordHelp = "Open Remove Password to create an unprotected copy."
required = "Enter the password to continue."
+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."
+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"
-successBody = "Password removed successfully."
-successBodyWithName = "Password removed from {{fileName}}"
-successTitle = "Password removed"
title = "Remove password to continue"
-unlock = "Unlock & Continue"
+toolUnavailable = "This tool doesn't support encrypted PDFs. Remove the password first."
+toolUnavailableDetails = "Why {{name}} is unavailable"
+unlock = "Unlock"
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."
viewerLocked = "This PDF is password-protected"
viewerUnlock = "Unlock"
@@ -7337,6 +7350,7 @@ nothingSelectedHint = "Click any text, image or shape on the page to edit it her
ocrDocumentChanged = "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."
ocrRunning = "Recognizing text..."
ocrUnavailable = "OCR is unavailable on this server."
oneImage = "Image"
@@ -7379,13 +7393,8 @@ pageNumber = "Page {{page}}"
renderFailed = "Failed to render page"
[pdfTextEditor.password]
-cancel = "Cancel"
incorrect = "Incorrect password - try again."
label = "Password"
-open = "Open"
-protected = "This PDF is password-protected."
-protectedNamed = "\"{{fileName}}\" is password-protected."
-title = "Password required"
[pdfTextEditor.rulers]
guide = "Alignment guide at {{value}} {{unit}} - drag onto a ruler to remove"
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
index 8256f187ea..8b5101a0fb 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
@@ -156,6 +156,15 @@
padding-top: 2px;
}
+.unlockedIndicator {
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ height: var(--file-name-line-height);
+ color: var(--c-text-muted);
+ pointer-events: auto;
+}
+
.fileMeta {
font-size: 11px;
color: var(--c-text-muted);
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index 925f90a364..4f4aa2e39b 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -40,6 +40,8 @@ import ShareFileModal from "@app/components/shared/ShareFileModal";
import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryModal";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { Tooltip as StirlingTooltip } from "@app/components/shared/Tooltip";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import { truncateCenter } from "@app/utils/textUtils";
@@ -75,6 +77,7 @@ const FileEditorThumbnail = ({
policies = [],
}: FileEditorThumbnailProps) => {
const { t } = useTranslation();
+ const pdfAccess = usePdfAccess(file.id);
const eligibleFileIds = useToolEligibleFileIds();
const isToolSkipped =
eligibleFileIds !== null && !eligibleFileIds.has(file.id);
@@ -681,6 +684,30 @@ const FileEditorThumbnail = ({
<span className={styles.fileNameText}>
<PrivateContent>{truncateCenter(file.name, 40)}</PrivateContent>
</span>
+ {pdfAccess?.encrypted && (
+ <StirlingTooltip
+ content={t(
+ "encryptedPdfUnlock.sessionSuccessBody",
+ "Unlocked for this session. Password protection is retained.",
+ )}
+ position="top"
+ maxWidth={230}
+ arrow
+ >
+ <span
+ className={styles.unlockedIndicator}
+ role="img"
+ aria-label={t(
+ "encryptedPdfUnlock.sessionSuccessTitle",
+ "PDF unlocked",
+ )}
+ tabIndex={0}
+ data-no-select
+ >
+ <Icon name="lock-open" size={14} />
+ </span>
+ </StirlingTooltip>
+ )}
<PolicyBadges policies={policies} className={styles.fileNameBadges} />
</p>
<p className={styles.fileMeta}>{metaLine}</p>
diff --git a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx
index 64a0b8f84d..4a939f98e3 100644
--- a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx
@@ -18,6 +18,7 @@ import { fileStorage } from "@app/services/fileStorage";
import { readStubClassificationLabels } from "@app/services/fileClassification";
import { useLabelName } from "@app/data/labelDisplay";
import { useClassificationEnabled } from "@app/hooks/useClassificationEnabled";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
import {
VersionTimeline,
DetailField,
@@ -81,6 +82,11 @@ export function FileDetailsPanel({
const labelName = useLabelName();
const [versionChain, setVersionChain] = useState<StirlingFileStub[]>([]);
const singleFileForChain = files.length === 1 ? files[0] : null;
+ const access = usePdfAccess(singleFileForChain?.id);
+ const thumbnail =
+ singleFileForChain?.processedFile?.isEncrypted && !access
+ ? undefined
+ : singleFileForChain?.thumbnailUrl;
useEffect(() => {
if (!singleFileForChain) {
setVersionChain([]);
@@ -180,12 +186,10 @@ export function FileDetailsPanel({
{single ? (
<>
<div
- className={`files-page-details-thumb${
- compactVersions ? " is-compact" : ""
- }`}
+ className={`files-page-details-thumb${compactVersions ? " is-compact" : ""}`}
>
- {single.thumbnailUrl ? (
- <img src={single.thumbnailUrl} alt="" />
+ {thumbnail ? (
+ <img src={thumbnail} alt="" />
) : (
<Icon
name="file-pdf"
@@ -221,9 +225,7 @@ export function FileDetailsPanel({
<Icon
name="chevron-down"
size={20}
- className={`files-page-details-collapse-chevron${
- fieldsOpen ? " is-open" : ""
- }`}
+ className={`files-page-details-collapse-chevron${fieldsOpen ? " is-open" : ""}`}
/>
}
>
@@ -276,9 +278,7 @@ export function FileDetailsPanel({
<Icon
name="chevron-down"
size={20}
- className={`files-page-details-collapse-chevron${
- classificationOpen ? " is-open" : ""
- }`}
+ className={`files-page-details-collapse-chevron${classificationOpen ? " is-open" : ""}`}
/>
}
>
@@ -341,9 +341,7 @@ export function FileDetailsPanel({
<Icon
name="chevron-down"
size={20}
- className={`files-page-details-collapse-chevron${
- versionsOpen ? " is-open" : ""
- }`}
+ className={`files-page-details-collapse-chevron${versionsOpen ? " is-open" : ""}`}
/>
}
>
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
index c5409bf07b..b6a4b0bb41 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
@@ -1246,6 +1246,7 @@ const FileCard = React.memo(function FileCard({
file.id,
file.size,
file.thumbnailUrl,
+ file.processedFile?.isEncrypted,
);
const kebabRef = useRef<HTMLButtonElement>(null);
@@ -1901,6 +1902,7 @@ const FileRow = React.memo(function FileRow({
file.id,
file.size,
file.thumbnailUrl,
+ file.processedFile?.isEncrypted,
);
const compactDate = useMemo(() => formatCompactDate(date), [date]);
const longPress = useLongPress(() => {
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
index 62a4cf98e2..0e4d909853 100644
--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { FileId } from "@app/types/file";
import { StirlingFileStub } from "@app/types/fileContext";
@@ -9,14 +9,24 @@ import {
TrackWorkspace,
} from "@app/components/pageTracks/types";
import {
+ buildTrackFile,
buildSelectedPagesFiles,
policyIdsForPages,
} from "@app/components/pageTracks/buildTrackFile";
+import apiClient from "@app/services/apiClient";
+import {
+ clearPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
+import { convertImageToPdf } from "@app/utils/imageToPdfUtils";
const exportPDFMultiFile = vi.hoisted(() => vi.fn());
vi.mock("@app/services/pdfExportService", () => ({
pdfExportService: { exportPDFMultiFile },
}));
+vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+vi.mock("@app/utils/imageToPdfUtils", () => ({ convertImageToPdf: vi.fn() }));
const A = "file-a" as FileId;
const B = "file-b" as FileId;
@@ -86,6 +96,82 @@ const exportedPageIds = (call: number): string[] =>
(page) => page.id,
);
+const readText = (file: File): Promise<string> =>
+ new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(file);
+ });
+
+describe("buildTrackFile with images and protected PDFs", () => {
+ beforeEach(() => {
+ clearPdfAccess();
+ vi.clearAllMocks();
+ exportPDFMultiFile.mockResolvedValue({ blob: new Blob(["merged"]) });
+ });
+ afterEach(clearPdfAccess);
+
+ it.each([A, B])(
+ "converts image pages and restores PDF protection with %s as the anchor",
+ async (anchor) => {
+ const image = new File(["image"], "photo.png", { type: "image/png" });
+ const protectedPdf = new File(["encrypted"], "locked.pdf", {
+ type: "application/pdf",
+ });
+ const imagePdf = new File(["image PDF"], "photo.pdf", {
+ type: "application/pdf",
+ });
+ const access = {
+ password: "password",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ };
+ rememberPdfAccess(protectedPdf, access);
+ vi.mocked(convertImageToPdf).mockResolvedValue(imagePdf);
+ vi.mocked(apiClient.post)
+ .mockResolvedValueOnce({ data: new Blob(["decrypted"]) })
+ .mockResolvedValueOnce({ data: new Blob(["protected result"]) });
+ const files = new Map([
+ [A, image],
+ [B, protectedPdf],
+ ]);
+ const built = await buildTrackFile(
+ {
+ fileId: anchor,
+ name: files.get(anchor)!.name,
+ isNew: false,
+ pages: [sourcePage("image", A, 1), sourcePage("pdf", B, 1)],
+ },
+ {
+ getFile: (id) => files.get(id),
+ getStub: (id) =>
+ ({ id, name: files.get(id)!.name }) as StirlingFileStub,
+ },
+ );
+
+ const sources = exportPDFMultiFile.mock.calls[0][1] as Map<string, File>;
+ expect(sources.get(A)).toBe(imagePdf);
+ expect(await readText(sources.get(B)!)).toBe("decrypted");
+ expect(convertImageToPdf).toHaveBeenCalledExactlyOnceWith(image, {
+ pageFormat: "keep",
+ });
+ expect(apiClient.post).toHaveBeenCalledTimes(2);
+ const [endpoint, form] = vi.mocked(apiClient.post).mock.calls[1];
+ expect(endpoint).toBe("/api/v1/security/restore-pdf-protection");
+ 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);
+ },
+ );
+});
+
describe("buildSelectedPagesFiles", () => {
beforeEach(() => {
exportPDFMultiFile.mockReset();
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
index c64952c9ea..78fd3fc5a7 100644
--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
@@ -3,6 +3,11 @@ import { FileId } from "@app/types/file";
import { PDFDocument, PDFPage } from "@app/types/pageEditor";
import { pdfExportService } from "@app/services/pdfExportService";
import { policySourceIds } from "@app/services/policyFileGuard";
+import {
+ prepareUnlockedFile,
+ protectUnlockedResults,
+} from "@app/services/pdfSessionUnlock";
+import { createStirlingFile } from "@app/types/fileContext";
import {
asPdfSource,
toPdfName,
@@ -82,21 +87,38 @@ export async function buildTrackFile(
const name = toPdfName(track.isNew ? track.name : parentStub.name);
const sourceFiles = new Map<string, File>();
+ sourceFiles.set(anchorFileId, ownFile);
for (const page of sourcePages) {
if (sourceFiles.has(page.sourceFileId)) continue;
const sourceFile = lookup.getFile(page.sourceFileId);
- if (sourceFile)
- sourceFiles.set(page.sourceFileId, await asPdfSource(sourceFile));
+ if (sourceFile) sourceFiles.set(page.sourceFileId, sourceFile);
}
+ const workingSources = new Map<string, File>();
+ for (const [id, file] of sourceFiles) {
+ workingSources.set(
+ id,
+ await asPdfSource(
+ await prepareUnlockedFile(
+ createStirlingFile(file, id as FileId),
+ "/api/v1/general/rearrange-pages",
+ ),
+ ),
+ );
+ }
const { blob } = await pdfExportService.exportPDFMultiFile(
toExportDocument(name, ownFile, pages),
- sourceFiles,
+ workingSources,
[],
{ filename: name },
);
+ const [file] = await protectUnlockedResults(
+ [new File([blob], name, { type: "application/pdf" })],
+ [...sourceFiles.values()],
+ "/api/v1/general/rearrange-pages",
+ );
return {
- file: new File([blob], name, { type: "application/pdf" }),
+ file,
parentStub,
};
}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
index af465e5198..3e71cb03c4 100644
--- a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
@@ -3,6 +3,7 @@ import { useFileState } from "@app/contexts/FileContext";
import { FileId } from "@app/types/file";
import { PageSize, TrackSource } from "@app/components/pageTracks/types";
import { ProcessedFilePage } from "@app/types/fileContext";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
import { isPdfFile } from "@app/utils/fileUtils";
import { isPageImage } from "@app/components/pageTracks/trackFileKind";
import {
@@ -82,6 +83,11 @@ export function useTrackWorkspace(): TrackWorkspaceHook {
}
anyEditable = true;
+ if (stub.processedFile?.isEncrypted && !getPdfAccess(fileId)) {
+ pending.push(fileId);
+ continue;
+ }
+
const pages = stub.processedFile?.pages;
if (!pages || pages.length === 0) {
pending.push(fileId);
diff --git a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.stories.tsx b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.stories.tsx
index dd83b6eece..660a56c119 100644
--- a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.stories.tsx
+++ b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.stories.tsx
@@ -26,6 +26,7 @@ function UnlockDemo(
return (
<EncryptedPdfUnlockModal
opened
+ sessionUnlock
fileName="contract-final.pdf"
password={password}
errorMessage={null}
@@ -33,6 +34,7 @@ function UnlockDemo(
remainingCount={0}
onPasswordChange={setPassword}
onUnlock={() => {}}
+ onRemovePassword={() => {}}
onUnlockAll={() => {}}
onSkip={() => {}}
{...props}
diff --git a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
index b436790a85..a1e60528ff 100644
--- a/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
+++ b/frontend/editor/src/core/components/shared/EncryptedPdfUnlockModal.tsx
@@ -1,5 +1,8 @@
import { Modal, Stack, Text, PasswordInput, Group } from "@mantine/core";
+import { Tooltip } from "@app/components/shared/Tooltip";
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";
@@ -14,8 +17,13 @@ interface EncryptedPdfUnlockModalProps {
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;
+ 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;
@@ -29,15 +37,19 @@ const EncryptedPdfUnlockModal = ({
isProcessing,
remainingCount = 0,
confirmLabel,
+ sessionUnlock = false,
+ testIdPrefix,
onPasswordChange,
onUnlock,
+ onRemovePassword,
onUnlockAll,
onSkip,
}: EncryptedPdfUnlockModalProps) => {
const { t } = useTranslation();
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (event) => {
- if (event.key === "Enter" && !isProcessing && password.trim().length > 0) {
+ if (event.key === "Enter" && !isProcessing && password.length > 0) {
+ event.preventDefault();
onUnlock();
}
};
@@ -45,76 +57,145 @@ const EncryptedPdfUnlockModal = ({
return (
<Modal
opened={opened}
- onClose={onSkip}
- title={t("encryptedPdfUnlock.title", "Remove password to continue")}
+ onClose={() => {
+ if (!isProcessing) onSkip();
+ }}
+ title={
+ <Group component="span" gap={6} wrap="nowrap">
+ <span>
+ {sessionUnlock
+ ? t("encryptedPdfUnlock.sessionTitle", "Unlock PDF")
+ : t("encryptedPdfUnlock.title", "Remove password to continue")}
+ </span>
+ {sessionUnlock && (
+ <Tooltip
+ content={t(
+ "encryptedPdfUnlock.sessionDetails",
+ "Unlock for this session. The PDF stays protected. Remove Password creates an unprotected copy.",
+ )}
+ position="top"
+ maxWidth={280}
+ arrow
+ containerStyle={{ zIndex: Z_INDEX_OVER_FULLSCREEN_SURFACE + 1 }}
+ >
+ <ActionIcon
+ variant="quiet"
+ accent="neutral"
+ size="sm"
+ aria-label={t(
+ "encryptedPdfUnlock.sessionDetailsLabel",
+ "About session unlocking",
+ )}
+ >
+ <Icon name="info" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </Group>
+ }
centered
- size="md"
+ size="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}
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
>
<Stack gap="md">
- <Text fw={600} ta="center">
- {fileName}
- </Text>
- <Text c="dimmed" ta="center">
- {t(
- "encryptedPdfUnlock.description",
- "This PDF is password protected. Enter the password so you can continue working with it.",
- )}
- </Text>
-
- <Stack gap={4}>
- <PasswordInput
- label={t("encryptedPdfUnlock.password.label", "PDF password")}
- placeholder={t(
- "encryptedPdfUnlock.password.placeholder",
- "Enter the PDF password",
- )}
- value={password}
- onChange={(event) => onPasswordChange(event.currentTarget.value)}
- onKeyDown={handleKeyDown}
- disabled={isProcessing}
- autoFocus
+ <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 }}
/>
- {errorMessage ? (
- <Text c="var(--color-red-dark)" size="sm" role="alert">
- {errorMessage}
- </Text>
- ) : null}
- </Stack>
-
- <Group justify="space-between">
- <Button
- variant="secondary"
- accent="neutral"
- onClick={onSkip}
- disabled={isProcessing}
- >
- {t("encryptedPdfUnlock.skip", "Skip for now")}
- </Button>
- <Group gap="xs">
- {remainingCount > 0 && onUnlockAll && (
- <Button
- variant="secondary"
- onClick={onUnlockAll}
- loading={isProcessing}
- disabled={password.trim().length === 0}
- >
- {t("encryptedPdfUnlock.unlockAll", "Use for all ({{count}})", {
- count: remainingCount + 1,
- })}
- </Button>
+ <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.",
)}
+ </Text>
+ )}
+
+ <PasswordInput
+ label={t("encryptedPdfUnlock.password.label", "PDF password")}
+ placeholder={t(
+ "encryptedPdfUnlock.password.placeholder",
+ "Enter the PDF password",
+ )}
+ value={password}
+ onChange={(event) => onPasswordChange(event.currentTarget.value)}
+ onKeyDown={handleKeyDown}
+ disabled={isProcessing}
+ size="md"
+ radius="md"
+ error={errorMessage || undefined}
+ errorProps={{ role: "alert" }}
+ autoFocus
+ data-autofocus
+ data-testid={testIdPrefix ? `${testIdPrefix}-input` : undefined}
+ />
+
+ <Group justify="flex-end" gap="sm">
+ {!sessionUnlock && (
<Button
- onClick={onUnlock}
+ variant="secondary"
+ accent="neutral"
+ onClick={onSkip}
+ disabled={isProcessing}
+ data-testid={testIdPrefix ? `${testIdPrefix}-cancel` : undefined}
+ >
+ {t("encryptedPdfUnlock.skip", "Skip for now")}
+ </Button>
+ )}
+ {remainingCount > 0 && onUnlockAll && (
+ <Button
+ variant="secondary"
+ onClick={onUnlockAll}
loading={isProcessing}
- disabled={password.trim().length === 0}
+ disabled={password.length === 0}
+ >
+ {t("encryptedPdfUnlock.unlockAll", "Use for all ({{count}})", {
+ count: remainingCount + 1,
+ })}
+ </Button>
+ )}
+ {sessionUnlock && onRemovePassword && (
+ <Button
+ variant="secondary"
+ onClick={onRemovePassword}
+ disabled={isProcessing || password.length === 0}
>
- {confirmLabel ??
- t("encryptedPdfUnlock.unlock", "Unlock & Continue")}
+ {t("removePassword.submit", "Remove Password")}
</Button>
- </Group>
+ )}
+ <Button
+ variant="primary"
+ onClick={onUnlock}
+ loading={isProcessing}
+ disabled={password.length === 0}
+ data-testid={testIdPrefix ? `${testIdPrefix}-submit` : undefined}
+ >
+ {confirmLabel ?? t("encryptedPdfUnlock.unlock", "Unlock")}
+ </Button>
</Group>
</Stack>
</Modal>
diff --git a/frontend/editor/src/core/components/shared/FilePickerModal.tsx b/frontend/editor/src/core/components/shared/FilePickerModal.tsx
index 8de6c8dd7d..b41a62572d 100644
--- a/frontend/editor/src/core/components/shared/FilePickerModal.tsx
+++ b/frontend/editor/src/core/components/shared/FilePickerModal.tsx
@@ -16,6 +16,7 @@ import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbn
import { FileId } from "@app/types/file";
import type { StoredStirlingFileRecord } from "@app/services/fileStorage";
import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
type StoredFileItem = Partial<StoredStirlingFileRecord> & {
id: FileId;
@@ -90,6 +91,12 @@ interface StoredFileCardProps {
function StoredFileCard({ file, selected, onToggle }: StoredFileCardProps) {
const { t } = useTranslation();
+ const access = usePdfAccess(file.id);
+ const encrypted = file.isEncrypted ?? file.processedFile?.isEncrypted;
+ const locked = Boolean(encrypted) && !access;
+ const unverifiedPdf =
+ encrypted === undefined &&
+ (file.type === "application/pdf" || /\.pdf$/i.test(file.name ?? ""));
return (
<Box
p="sm"
@@ -128,10 +135,8 @@ function StoredFileCard({ file, selected, onToggle }: StoredFileCardProps) {
>
<DocumentThumbnail
file={file.file ?? null}
- thumbnail={
- file.processedFile?.isEncrypted ? undefined : file.thumbnail
- }
- isEncrypted={Boolean(file.processedFile?.isEncrypted)}
+ thumbnail={locked || unverifiedPdf ? undefined : file.thumbnail}
+ isEncrypted={locked}
iconSize="2rem"
/>
</Box>
diff --git a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
index 03c6ab03f4..5b338c95d0 100644
--- a/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
+++ b/frontend/editor/src/core/components/shared/FileSelectorPicker.tsx
@@ -11,9 +11,9 @@ import {
} from "@app/types/fileContext";
import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
import { useAllFiles } from "@app/contexts/FileContext";
-import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { useFileContext } from "@app/contexts/file/fileHooks";
import { useFileManager } from "@app/hooks/useFileManager";
+import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import { fileStorage } from "@app/services/fileStorage";
import apiClient from "@app/services/apiClient";
import {
@@ -131,44 +131,13 @@ export function FileSelectorPicker({
rect: DOMRect;
stub: StirlingFileStub;
} | null>(null);
- const [hoveredThumbnail, setHoveredThumbnail] = useState<string | null>(null);
- const thumbCancelRef = useRef<boolean>(false);
+ const { thumbnail: hoveredThumbnail } = useFileThumbnail(hoveredStub?.stub);
const fileInputRef = useRef<HTMLInputElement>(null);
const { fileStubs: workbenchStubs } = useAllFiles();
- const indexedDB = useIndexedDB();
const { selectors } = useFileContext();
const { loadRecentFiles } = useFileManager();
- // Load thumbnail lazily when hovering over a file row
- useEffect(() => {
- if (!hoveredStub) {
- setHoveredThumbnail(null);
- return;
- }
- if (hoveredStub.stub.thumbnailUrl) {
- setHoveredThumbnail(hoveredStub.stub.thumbnailUrl);
- return;
- }
- thumbCancelRef.current = false;
- setHoveredThumbnail(null);
- (async () => {
- try {
- const file = await indexedDB.loadFile(hoveredStub.stub.id);
- if (!file || thumbCancelRef.current) return;
- const thumbnail = await generateThumbnailForFile(file);
- if (thumbCancelRef.current || !thumbnail) return;
- setHoveredThumbnail(thumbnail);
- void indexedDB.updateThumbnail(hoveredStub.stub.id, thumbnail);
- } catch {
- // non-critical
- }
- })();
- return () => {
- thumbCancelRef.current = true;
- };
- }, [hoveredStub, indexedDB]);
-
const handleTabChange = useCallback((tab: "workbench" | "saved") => {
lsSet(LS_TAB, tab);
setActiveTab(tab);
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index d735d725e1..066fb3b84c 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -1048,11 +1048,10 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
);
const isActive = isViewedInViewer;
const isEncryptedFile = stub.processedFile?.isEncrypted === true;
- const thumbnailUrl = isEncryptedFile
- ? undefined
- : (workbenchFileId
- ? state.files.byId[workbenchFileId]?.thumbnailUrl
- : undefined) || stub.thumbnailUrl;
+ const thumbnailUrl =
+ (workbenchFileId
+ ? state.files.byId[workbenchFileId]?.thumbnailUrl
+ : undefined) || stub.thumbnailUrl;
const fileOrigin = getFileOrigin(stub);
const dataUnavailable =
stub.dataUnavailable === true || lostFileIds.has(stub.id);
@@ -1078,6 +1077,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
isActive={isActive}
isViewedInViewer={isViewedInViewer}
thumbnailUrl={thumbnailUrl}
+ isEncrypted={isEncryptedFile}
onClick={handleFileClick}
onEyeClick={handleEyeClick}
dataUnavailable={dataUnavailable}
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
index 8fd4baf8f3..95b1742c0a 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
@@ -120,6 +120,7 @@ export interface FileItemProps {
isViewedInViewer: boolean;
isToolSkipped?: boolean;
thumbnailUrl?: string;
+ isEncrypted?: boolean;
onClick: (fileId: FileId) => void;
onEyeClick: (fileId: FileId, e: React.MouseEvent) => void;
/** Policies that have run on this file — rendered as small shield badges. */
@@ -205,6 +206,7 @@ export const FileItem = React.memo(function FileItem({
isToolSkipped = false,
dataUnavailable,
thumbnailUrl,
+ isEncrypted,
onClick,
onEyeClick,
policies = [],
@@ -277,6 +279,7 @@ export const FileItem = React.memo(function FileItem({
fileId,
size ?? 0,
useRasterThumb ? thumbnailUrl : undefined,
+ isEncrypted,
isNearViewport,
);
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
index 96780cb815..9b5c1b05fa 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
@@ -234,7 +234,9 @@ export default function WorkbenchBar({
const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
if (!buffer) return;
const fileToExport =
- selectedFiles.length > 0 ? selectedFiles[0] : activeFiles[0];
+ activeFiles.find(
+ (file) => isStirlingFile(file) && file.fileId === activeFileId,
+ ) ?? activeFiles[0];
if (!fileToExport) return;
const stub = isStirlingFile(fileToExport)
? selectors.getStirlingFileStub(fileToExport.fileId)
@@ -326,6 +328,7 @@ export default function WorkbenchBar({
currentView,
selectedFiles,
activeFiles,
+ activeFileId,
viewerContext,
viewFileActions,
selectors,
diff --git a/frontend/editor/src/core/components/shared/filePreview/DocumentThumbnail.tsx b/frontend/editor/src/core/components/shared/filePreview/DocumentThumbnail.tsx
index e35b5c458c..f4e3023a1f 100644
--- a/frontend/editor/src/core/components/shared/filePreview/DocumentThumbnail.tsx
+++ b/frontend/editor/src/core/components/shared/filePreview/DocumentThumbnail.tsx
@@ -6,6 +6,7 @@ import { getFileTypeIcon } from "@app/components/shared/filePreview/getFileTypeI
import { StirlingFileStub } from "@app/types/fileContext";
import { PrivateContent } from "@app/components/shared/PrivateContent";
import { detectFileExtension } from "@app/utils/fileUtils";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
export interface DocumentThumbnailProps {
file: File | StirlingFileStub | null;
@@ -33,6 +34,13 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
children,
}) => {
const { t } = useTranslation();
+ const access = usePdfAccess(file instanceof Blob ? file : file?.id);
+ const locked =
+ !access &&
+ (isEncrypted ||
+ Boolean(
+ file && "processedFile" in file && file.processedFile?.isEncrypted,
+ ));
if (!file) return null;
const containerStyle: React.CSSProperties = {
@@ -47,7 +55,7 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
...style,
};
- if (thumbnail && !isEncrypted) {
+ if (thumbnail && !locked) {
return (
<Box style={containerStyle} onClick={onClick}>
<PrivateContent>
@@ -79,7 +87,7 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
);
}
- if (isEncrypted) {
+ if (locked) {
return (
<Box style={containerStyle} onClick={onClick}>
<div
diff --git a/frontend/editor/src/core/components/tools/shared/FileStatusIndicator.tsx b/frontend/editor/src/core/components/tools/shared/FileStatusIndicator.tsx
index cb7b8021d5..82176d9c99 100644
--- a/frontend/editor/src/core/components/tools/shared/FileStatusIndicator.tsx
+++ b/frontend/editor/src/core/components/tools/shared/FileStatusIndicator.tsx
@@ -1,29 +1,31 @@
import { useState, useEffect } from "react";
-import { Text, Anchor } from "@mantine/core";
+import { Text, Anchor, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
import { useAllFiles } from "@app/contexts/FileContext";
import { useFileManager } from "@app/hooks/useFileManager";
-import { StirlingFile } from "@app/types/fileContext";
+import { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { ProtectedPdfToolNotice } from "@app/components/tools/shared/ProtectedPdfToolNotice";
export interface FileStatusIndicatorProps {
selectedFiles?: StirlingFile[];
minFiles?: number;
+ unavailableFiles?: readonly StirlingFileStub[];
}
const FileStatusIndicator = ({
selectedFiles = [],
minFiles = 1,
+ unavailableFiles = [],
}: FileStatusIndicatorProps) => {
const { t } = useTranslation();
const { openFilesModal, onFileUpload } = useFilesModalContext();
- const { files: stirlingFileStubs } = useAllFiles();
+ const { files: workbenchFiles } = useAllFiles();
const { loadRecentFiles } = useFileManager();
const [hasRecentFiles, setHasRecentFiles] = useState<boolean | null>(null);
- // Check if there are recent files
useEffect(() => {
const checkRecentFiles = async () => {
try {
@@ -33,10 +35,9 @@ const FileStatusIndicator = ({
setHasRecentFiles(false);
}
};
- checkRecentFiles();
+ void checkRecentFiles();
}, [loadRecentFiles]);
- // Handle native file picker
const handleNativeUpload = () => {
const input = document.createElement("input");
input.type = "file";
@@ -44,103 +45,59 @@ const FileStatusIndicator = ({
input.accept = ".pdf,application/pdf";
input.onchange = (event) => {
const files = Array.from((event.target as HTMLInputElement).files || []);
- if (files.length > 0) {
- onFileUpload(files);
- }
+ if (files.length > 0) onFileUpload(files);
};
input.click();
};
- // Don't render until we know if there are recent files
- if (hasRecentFiles === null) {
- return null;
- }
-
- const getPlaceholder = () => {
- if (minFiles === undefined || minFiles === 1) {
- return t("files.selectFromWorkbench", "Add files to the workbench or ");
- } else {
- return t(
- "files.selectMultipleFromWorkbench",
- "Add at least {{count}} files to the workbench or ",
- { count: minFiles },
- );
- }
- };
+ if (hasRecentFiles === null) return null;
- // Check if there are no files in the workbench
- if (stirlingFileStubs.length === 0) {
- // If no recent files, show upload button
- if (!hasRecentFiles) {
- return (
- <Text size="sm" c="dimmed">
- <Anchor
- size="sm"
- onClick={handleNativeUpload}
- style={{
- cursor: "pointer",
- display: "inline-flex",
- alignItems: "center",
- gap: "0.25rem",
- }}
- >
- <Icon name="upload" size={"0.875rem"} />
- {t("files.upload", "Upload")}
- </Anchor>
- </Text>
- );
- } else {
- // If there are recent files, show add files button
- return (
- <Text size="sm" c="dimmed">
- <Anchor
- size="sm"
- onClick={() => openFilesModal({})}
- style={{
- cursor: "pointer",
- display: "inline-flex",
- alignItems: "center",
- gap: "0.25rem",
- }}
- >
- <Icon name="folder" size={"0.875rem"} />
- {t("files.addFiles", "Add files")}
- </Anchor>
- </Text>
- );
- }
- }
+ const needsFiles = selectedFiles.length < minFiles;
+ const showPlaceholder =
+ workbenchFiles.length > 0 && unavailableFiles.length === 0;
+ const pickerLabel = hasRecentFiles
+ ? t("files.addFiles", "Add files")
+ : workbenchFiles.length === 0
+ ? t("files.upload", "Upload")
+ : t("files.uploadFiles", "Upload Files");
- // Show selection status when there are files in workbench
- if (selectedFiles.length < minFiles) {
- // If no recent files, show upload option
- if (!hasRecentFiles) {
- return (
- <Text size="sm" c="dimmed">
- {getPlaceholder() + " "}
- <Anchor
- size="sm"
- onClick={handleNativeUpload}
- style={{
- cursor: "pointer",
- display: "inline-flex",
- alignItems: "center",
- gap: "0.25rem",
- }}
- >
- <Icon name="upload" size={"0.875rem"} />
- {t("files.uploadFiles", "Upload Files")}
- </Anchor>
+ return (
+ <Stack gap="xs" data-testid="tool-file-list">
+ {selectedFiles.length > 0 && (
+ <Text size="sm" c="dimmed" style={{ overflowWrap: "anywhere" }}>
+ ✓{" "}
+ {selectedFiles.length === 1 ? (
+ <PrivateContent>
+ {t("fileSelected", "{{filename}}", {
+ filename: selectedFiles[0]?.name,
+ })}
+ </PrivateContent>
+ ) : (
+ t("filesSelected", "{{count}} files", {
+ count: selectedFiles.length,
+ })
+ )}
</Text>
- );
- } else {
- // If there are recent files, show add files option
- return (
+ )}
+ <ProtectedPdfToolNotice files={unavailableFiles} />
+ {needsFiles && (
<Text size="sm" c="dimmed">
- {getPlaceholder() + " "}
+ {showPlaceholder &&
+ (minFiles === 1
+ ? t(
+ "files.selectFromWorkbench",
+ "Add files to the workbench or ",
+ ) + " "
+ : t(
+ "files.selectMultipleFromWorkbench",
+ "Add at least {{count}} files to the workbench or ",
+ { count: minFiles },
+ ) + " ")}
<Anchor
size="sm"
- onClick={() => openFilesModal({})}
+ onClick={
+ hasRecentFiles ? () => openFilesModal({}) : handleNativeUpload
+ }
style={{
cursor: "pointer",
display: "inline-flex",
@@ -148,31 +105,12 @@ const FileStatusIndicator = ({
gap: "0.25rem",
}}
>
- <Icon name="folder" size={"0.875rem"} />
- {t("files.addFiles", "Add files")}
+ <Icon name={hasRecentFiles ? "folder" : "upload"} size="0.875rem" />
+ {pickerLabel}
</Anchor>
</Text>
- );
- }
- }
-
- return (
- <Text
- size="sm"
- c="dimmed"
- style={{ wordBreak: "break-word", whiteSpace: "normal" }}
- >
- ✓{" "}
- {selectedFiles.length === 1 ? (
- <PrivateContent>
- {t("fileSelected", "{{filename}}", {
- filename: selectedFiles[0]?.name,
- })}
- </PrivateContent>
- ) : (
- t("filesSelected", "{{count}} files", { count: selectedFiles.length })
)}
- </Text>
+ </Stack>
);
};
diff --git a/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx b/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
index 19701c2755..36d92c38b6 100644
--- a/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
+++ b/frontend/editor/src/core/components/tools/shared/FilesToolStep.tsx
@@ -2,12 +2,40 @@ import React from "react";
import FileStatusIndicator from "@app/components/tools/shared/FileStatusIndicator";
import { StirlingFile } from "@app/types/fileContext";
import i18n from "@app/i18n";
+import { useViewScopedFileStubs } from "@app/hooks/tools/shared/useViewScopedFiles";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
export interface FilesToolStepProps {
selectedFiles: StirlingFile[];
isCollapsed?: boolean;
onCollapsedClick?: () => void;
minFiles?: number;
+ showUnavailableFiles?: boolean;
+}
+
+function FilesStepContent({
+ selectedFiles,
+ minFiles,
+ showUnavailableFiles = true,
+}: FilesToolStepProps) {
+ usePdfAccess(undefined);
+ const files = useViewScopedFileStubs();
+ const unavailableFiles = showUnavailableFiles
+ ? files.filter(
+ (file) =>
+ file.processedFile?.isEncrypted &&
+ getPdfAccess(file.id) &&
+ !selectedFiles.some((selected) => selected.fileId === file.id),
+ )
+ : [];
+ return (
+ <FileStatusIndicator
+ selectedFiles={selectedFiles}
+ minFiles={minFiles}
+ unavailableFiles={unavailableFiles}
+ />
+ );
}
interface StepBaseProps {
@@ -31,9 +59,6 @@ export function createFilesToolStep<T>(
isCollapsed: props.isCollapsed,
onCollapsedClick: props.onCollapsedClick,
},
- <FileStatusIndicator
- selectedFiles={props.selectedFiles}
- minFiles={props.minFiles}
- />,
+ <FilesStepContent {...props} />,
);
}
diff --git a/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx b/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx
new file mode 100644
index 0000000000..7b07e3d7b3
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/shared/ProtectedPdfToolNotice.tsx
@@ -0,0 +1,88 @@
+import { Group, Stack, Text } from "@mantine/core";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { useTranslation } from "react-i18next";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import { useToolWorkflowActions } from "@app/contexts/ToolWorkflowContext";
+
+function RemovePasswordAction() {
+ const { t } = useTranslation();
+ const { handleToolSelect } = useToolWorkflowActions();
+ return (
+ <Tooltip
+ content={t(
+ "encryptedPdfUnlock.removePasswordHelp",
+ "Open Remove Password to create an unprotected copy.",
+ )}
+ position="top"
+ maxWidth={230}
+ arrow
+ >
+ <ActionIcon
+ variant="tertiary"
+ accent="neutral"
+ size="sm"
+ style={{ flexShrink: 0 }}
+ aria-label={t("removePassword.submit", "Remove Password")}
+ onClick={() => handleToolSelect("removePassword")}
+ >
+ <Icon name="lock-open" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
+
+/** Protected inputs remain visible in the Files list even when this tool cannot process them. */
+export function ProtectedPdfToolNotice({
+ files,
+}: {
+ files: readonly StirlingFileStub[];
+}) {
+ const { t } = useTranslation();
+ if (!files.length) return null;
+ return (
+ <Stack gap="xs" role="list">
+ {files.map((file) => (
+ <Group key={file.id} gap={6} wrap="nowrap" role="listitem">
+ <Tooltip
+ content={t(
+ "encryptedPdfUnlock.toolUnavailable",
+ "This tool doesn't support encrypted PDFs. Remove the password first.",
+ )}
+ position="top"
+ maxWidth={260}
+ arrow
+ >
+ <ActionIcon
+ variant="quiet"
+ accent="warning"
+ size="sm"
+ aria-label={t(
+ "encryptedPdfUnlock.toolUnavailableDetails",
+ "Why {{name}} is unavailable",
+ { name: file.name },
+ )}
+ style={{ flexShrink: 0 }}
+ >
+ <Icon
+ name="triangle-alert"
+ size={16}
+ style={{ color: "var(--c-warning)" }}
+ />
+ </ActionIcon>
+ </Tooltip>
+ <Text
+ size="sm"
+ c="dimmed"
+ style={{ overflowWrap: "anywhere", minWidth: 0, flex: 1 }}
+ >
+ <PrivateContent>{file.name}</PrivateContent>
+ </Text>
+ <RemovePasswordAction />
+ </Group>
+ ))}
+ </Stack>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
index 2437673dfd..e1a763e147 100644
--- a/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
+++ b/frontend/editor/src/core/components/tools/shared/createToolFlow.tsx
@@ -124,6 +124,7 @@ export function createToolFlow<TParams = unknown>(
isCollapsed: config.files.isCollapsed,
minFiles: config.files.minFiles,
onCollapsedClick: config.files.onCollapsedClick,
+ showUnavailableFiles: !config.review.isVisible,
})}
{/* Middle Steps */}
diff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
index e42fc7e272..a612477f67 100644
--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
@@ -99,6 +99,7 @@ function formatCommentDate(obj: PdfAnnotationObject): string {
}
interface CommentsSidebarProps {
+ readOnly?: boolean;
documentId: string;
visible: boolean;
rightOffset: string;
@@ -462,6 +463,7 @@ function CommentPageGroup({
}
interface CommentCardHeaderProps {
+ readOnly: boolean;
ann: PdfAnnotationObject;
authorName: string;
typeLabel: string;
@@ -472,6 +474,7 @@ interface CommentCardHeaderProps {
}
function CommentCardHeader({
+ readOnly,
ann,
authorName,
typeLabel,
@@ -518,21 +521,23 @@ function CommentCardHeader({
<Icon name="eye" size={16} />
</ActionIcon>
</Tooltip>
- <MoreActionsMenu>
- <Menu.Item
- leftSection={<Icon name="pencil" size={18} />}
- onClick={onEdit}
- >
- {t("annotation.editText", "Edit")}
- </Menu.Item>
- <Menu.Item
- leftSection={<Icon name="trash" size={18} />}
- color="red"
- onClick={onDelete}
- >
- {t("annotation.delete", "Delete")}
- </Menu.Item>
- </MoreActionsMenu>
+ {!readOnly && (
+ <MoreActionsMenu>
+ <Menu.Item
+ leftSection={<Icon name="pencil" size={18} />}
+ onClick={onEdit}
+ >
+ {t("annotation.editText", "Edit")}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="trash" size={18} />}
+ color="red"
+ onClick={onDelete}
+ >
+ {t("annotation.delete", "Delete")}
+ </Menu.Item>
+ </MoreActionsMenu>
+ )}
</Group>
</Group>
);
@@ -622,6 +627,7 @@ function ReplyEditor({ value, onChange, onSave }: ReplyEditorProps) {
}
interface CommentReplyProps {
+ readOnly: boolean;
reply: SidebarAnnotationEntry["replies"][number];
displayName: string;
/** The text being edited, or null when the reply is not being edited. */
@@ -632,6 +638,7 @@ interface CommentReplyProps {
}
function CommentReply({
+ readOnly,
reply,
displayName,
editDraft,
@@ -643,7 +650,7 @@ function CommentReply({
const rObj = reply.object;
const author = getAuthorName(rObj, displayName);
const timestamp = formatCommentDate(rObj);
- const canEdit = isReplyAuthoredByCurrentUser(rObj, displayName);
+ const canEdit = !readOnly && isReplyAuthoredByCurrentUser(rObj, displayName);
return (
<Box
@@ -681,7 +688,7 @@ function CommentReply({
) : null}
</Group>
</Group>
- {editDraft !== null ? (
+ {!readOnly && editDraft !== null ? (
<ReplyEditor
value={editDraft}
onChange={onEditChange}
@@ -783,6 +790,7 @@ interface CommentActions {
}
interface CommentRepliesProps {
+ readOnly: boolean;
pageIndex: number;
parentId: string;
replies: SidebarAnnotationEntry["replies"];
@@ -792,6 +800,7 @@ interface CommentRepliesProps {
}
function CommentReplies({
+ readOnly,
pageIndex,
parentId,
replies,
@@ -806,6 +815,7 @@ function CommentReplies({
.filter((reply) => reply?.object?.id)
.map((reply) => (
<CommentReply
+ readOnly={readOnly}
key={reply.object.id}
reply={reply}
displayName={displayName}
@@ -833,6 +843,7 @@ function CommentReplies({
}
interface CommentThreadProps {
+ readOnly: boolean;
pageIndex: number;
entry: SidebarAnnotationEntry;
content: string;
@@ -843,6 +854,7 @@ interface CommentThreadProps {
}
function CommentThread({
+ readOnly,
pageIndex,
entry,
content,
@@ -858,6 +870,7 @@ function CommentThread({
{content}
</Text>
<CommentReplies
+ readOnly={readOnly}
pageIndex={pageIndex}
parentId={ann.id}
replies={entry.replies}
@@ -865,16 +878,21 @@ function CommentThread({
editingReply={editingReply}
actions={actions}
/>
- <ReplyComposer
- value={replyDraft}
- onChange={(value) => actions.changeReplyDraft(pageIndex, ann.id, value)}
- onSubmit={() => actions.sendReply(pageIndex, ann.id, ann.rect)}
- />
+ {!readOnly && (
+ <ReplyComposer
+ value={replyDraft}
+ onChange={(value) =>
+ actions.changeReplyDraft(pageIndex, ann.id, value)
+ }
+ onSubmit={() => actions.sendReply(pageIndex, ann.id, ann.rect)}
+ />
+ )}
</>
);
}
interface CommentCardProps {
+ readOnly: boolean;
pageIndex: number;
entry: SidebarAnnotationEntry;
selected: boolean;
@@ -889,6 +907,7 @@ interface CommentCardProps {
}
function CommentCard({
+ readOnly,
pageIndex,
entry,
selected,
@@ -920,6 +939,7 @@ function CommentCard({
}}
>
<CommentCardHeader
+ readOnly={readOnly}
ann={ann}
authorName={getAuthorName(ann, displayName)}
typeLabel={getAnnotationTypeLabel(ann, t)}
@@ -929,7 +949,7 @@ function CommentCard({
onDelete={() => actions.requestDelete(pageIndex, id, ann)}
/>
- {!hasMainContent || isEditing ? (
+ {!readOnly && (!hasMainContent || isEditing) ? (
<CommentComposer
value={text}
onChange={(value) => actions.changeDraft(pageIndex, id, value)}
@@ -937,6 +957,7 @@ function CommentCard({
/>
) : (
<CommentThread
+ readOnly={readOnly}
pageIndex={pageIndex}
entry={entry}
content={displayContent}
@@ -1035,6 +1056,7 @@ function ClearAllCommentsModal({
}
export function CommentsSidebar({
+ readOnly = false,
documentId,
visible,
rightOffset,
@@ -1494,9 +1516,9 @@ export function CommentsSidebar({
onClose={toggleCommentsSidebar}
closeLabel={t("viewer.comments.closeSidebar", "Close comments sidebar")}
headerActions={
- totalCount > 0 ? (
+ totalCount > 0 && !readOnly ? (
<CommentsHeaderActions
- readerMode={readerMode}
+ readerMode={readerMode || readOnly}
onAdd={handleAddComment}
onClearAll={() => setClearAllModalOpen(true)}
/>
@@ -1514,7 +1536,7 @@ export function CommentsSidebar({
<CommentsEmptyState>
<AddCommentButton
isPlacing={isPlacingComment}
- readerMode={readerMode}
+ readerMode={readerMode || readOnly}
onAdd={handleAddComment}
onCancel={handleCancelPlacingComment}
/>
@@ -1524,7 +1546,7 @@ export function CommentsSidebar({
<AddCommentButton
block
isPlacing={isPlacingComment}
- readerMode={readerMode}
+ readerMode={readerMode || readOnly}
onAdd={handleAddComment}
onCancel={handleCancelPlacingComment}
/>
@@ -1552,6 +1574,7 @@ export function CommentsSidebar({
const cardKey = `${pageIndex}_${id}`;
return (
<CommentCard
+ readOnly={readOnly}
key={cardKey}
pageIndex={pageIndex}
entry={entry}
@@ -1578,14 +1601,14 @@ export function CommentsSidebar({
</SidebarBase>
<DeleteLinkedCommentModal
- opened={!!deleteModal}
+ opened={!readOnly && !!deleteModal}
onClose={() => setDeleteModal(null)}
onRemoveComment={handleRemoveFromSidebar}
onDeleteAnnotation={handleDeleteAnnotation}
/>
<ClearAllCommentsModal
- opened={clearAllModalOpen}
+ opened={!readOnly && clearAllModalOpen}
onClose={() => setClearAllModalOpen(false)}
onConfirm={handleClearAllComments}
/>
diff --git a/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx
index 006e62f8cf..a425cd290b 100644
--- a/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/DocumentPermissionsAPIBridge.tsx
@@ -1,4 +1,5 @@
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 {
@@ -10,8 +11,9 @@ import {
function hasPermissionFlag(
permissions: number,
flag: PdfPermissionFlag,
+ isEncrypted: boolean,
): boolean {
- if (permissions === 0 || permissions === PdfPermissionFlag.AllowAll) {
+ if (!isEncrypted || permissions === PdfPermissionFlag.AllowAll) {
return true;
}
return (permissions & flag) !== 0;
@@ -36,31 +38,45 @@ export function DocumentPermissionsAPIBridge({
isEncrypted,
isOwnerUnlocked,
permissions,
- canPrint: hasPermissionFlag(permissions, PdfPermissionFlag.Print),
+ canPrint: canPrintPdf({
+ encrypted: isEncrypted,
+ ownerAuthenticated: isOwnerUnlocked,
+ permissions,
+ }),
canModifyContents: hasPermissionFlag(
permissions,
PdfPermissionFlag.ModifyContents,
+ isEncrypted,
),
canCopyContents: hasPermissionFlag(
permissions,
PdfPermissionFlag.CopyContents,
+ isEncrypted,
),
canModifyAnnotations: hasPermissionFlag(
permissions,
PdfPermissionFlag.ModifyAnnotations,
+ isEncrypted,
+ ),
+ canFillForms: hasPermissionFlag(
+ permissions,
+ PdfPermissionFlag.FillForms,
+ isEncrypted,
),
- canFillForms: hasPermissionFlag(permissions, PdfPermissionFlag.FillForms),
canExtractForAccessibility: hasPermissionFlag(
permissions,
PdfPermissionFlag.ExtractForAccessibility,
+ isEncrypted,
),
canAssembleDocument: hasPermissionFlag(
permissions,
PdfPermissionFlag.AssembleDocument,
+ isEncrypted,
),
canPrintHighQuality: hasPermissionFlag(
permissions,
PdfPermissionFlag.PrintHighQuality,
+ isEncrypted,
),
}),
[isEncrypted, isOwnerUnlocked, permissions],
@@ -69,15 +85,17 @@ export function DocumentPermissionsAPIBridge({
const api = useMemo<DocumentPermissionsAPIWrapper>(
() => ({
hasPermission: (flag: PdfPermissionFlag) =>
- hasPermissionFlag(permissions, flag),
+ hasPermissionFlag(permissions, flag, isEncrypted),
hasAllPermissions: (flags: PdfPermissionFlag[]) =>
- flags.every((flag) => hasPermissionFlag(permissions, flag)),
+ flags.every((flag) =>
+ hasPermissionFlag(permissions, flag, isEncrypted),
+ ),
getEffectivePermission: (flag: PdfPermissionFlag) => {
if (isOwnerUnlocked) return true;
- return hasPermissionFlag(permissions, flag);
+ return hasPermissionFlag(permissions, flag, isEncrypted);
},
}),
- [permissions, isOwnerUnlocked],
+ [permissions, isOwnerUnlocked, isEncrypted],
);
useEffect(() => {
diff --git a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
index 7344525ff3..67cb97d6be 100644
--- a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
@@ -5,6 +5,7 @@ interface PendingDocument {
buffer: ArrayBuffer;
name: string;
fileKey: string;
+ password?: string;
}
interface DocumentSwapBridgeProps {
@@ -43,6 +44,7 @@ export function DocumentSwapBridge({
.openDocumentBuffer({
buffer: pending.buffer,
name: pending.name,
+ password: pending.password,
autoActivate: false,
})
.toPromise(),
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index fcf93661b6..9663f81255 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -26,6 +26,9 @@ import type {
} from "@app/components/viewer/DocumentRestoreBridge";
import { useViewer } from "@app/contexts/ViewerContext";
import { LocalEmbedPDF } from "@app/components/viewer/LocalEmbedPDF";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { canPrintPdf } from "@app/services/pdfPermissions";
+import { PdfPreviewUnlockGate } from "@app/components/viewer/PdfPreviewUnlockGate";
import { PdfViewerToolbar } from "@app/components/viewer/PdfViewerToolbar";
import { ThumbnailSidebar } from "@app/components/viewer/ThumbnailSidebar";
import { BookmarkSidebar } from "@app/components/viewer/BookmarkSidebar";
@@ -128,7 +131,8 @@ const EmbedPdfViewerContent = ({
onSignaturePreviewsChange,
signatureOverlayApiRef,
portfolioPinned,
-}: EmbedPdfViewerProps) => {
+ onPasswordRequired,
+}: EmbedPdfViewerProps & { onPasswordRequired?: () => void }) => {
const { t } = useTranslation();
const viewerRef = React.useRef<HTMLDivElement>(null);
const pdfContainerRef = useRef<HTMLDivElement>(null);
@@ -685,11 +689,16 @@ const EmbedPdfViewerContent = ({
}, [previewFile, fileWithUrl]);
// Check if the current file is encrypted (gate the viewer to prevent PDFium crash)
- const isCurrentFileEncrypted = useFileSelector((s) =>
+ const isStoredFileEncrypted = useFileSelector((s) =>
currentFile && isStirlingFile(currentFile)
? s.files.byId[currentFile.fileId]?.processedFile?.isEncrypted === true
: false,
);
+ const pdfAccess = usePdfAccess(previewFile ?? currentFile);
+ const isCurrentFileEncrypted =
+ isStoredFileEncrypted || Boolean(pdfAccess?.encrypted);
+ const isCurrentFileLocked = isCurrentFileEncrypted && !pdfAccess;
+ const canPrint = !isCurrentFileLocked && canPrintPdf(pdfAccess);
const bookmarkCacheKey = React.useMemo(() => {
if (currentFile && isStirlingFile(currentFile)) {
@@ -769,7 +778,7 @@ const EmbedPdfViewerContent = ({
case "p":
case "P":
event.preventDefault();
- if (!policyEnforcingRef.current) {
+ if (!policyEnforcingRef.current && canPrint) {
printActions.print();
}
return;
@@ -889,6 +898,7 @@ const EmbedPdfViewerContent = ({
searchInterfaceActions,
scrollActions,
printActions,
+ canPrint,
exportActions,
rotationActions,
historyApiRef,
@@ -1836,7 +1846,7 @@ const EmbedPdfViewerContent = ({
)}
</Text>
</Center>
- ) : isCurrentFileEncrypted ? (
+ ) : isCurrentFileLocked ? (
<Center style={{ flex: 1 }}>
<Stack align="center" gap="md">
<Icon name="lock" size={48} style={{ opacity: 0.5 }} />
@@ -1880,6 +1890,7 @@ const EmbedPdfViewerContent = ({
onDocumentSwapFailed={handleDocumentSwapFailed}
onDocumentReady={documentReady}
onDocumentLoadFailed={documentFailed}
+ onPasswordRequired={onPasswordRequired}
restorePending={restorePending}
restoreRequest={restoreRequest}
onRestoreEvent={handleRestoreEvent}
@@ -1895,11 +1906,13 @@ const EmbedPdfViewerContent = ({
? effectiveFile.file.name
: undefined
}
- enableAnnotations={shouldEnableAnnotations}
+ enableAnnotations={
+ shouldEnableAnnotations && !pdfAccess?.encrypted
+ }
isSignMode={selectedTool === "sign"}
showBakedAnnotations={isAnnotationsVisible}
- enableRedaction={shouldEnableRedaction}
- enableFormFill={shouldEnableFormFill}
+ enableRedaction={shouldEnableRedaction && !pdfAccess?.encrypted}
+ enableFormFill={shouldEnableFormFill && !pdfAccess?.encrypted}
formEditingActive={isFormFillToolActive}
isManualRedactionMode={isManualRedactMode}
signatureApiRef={signatureApiRef}
@@ -2022,6 +2035,18 @@ const EmbedPdfViewerContent = ({
};
const EmbedPdfViewer = (props: EmbedPdfViewerProps) => {
+ if (props.previewFile) {
+ return (
+ <PdfPreviewUnlockGate file={props.previewFile} onClose={props.onClose}>
+ {(onPasswordRequired) => (
+ <EmbedPdfViewerContent
+ {...props}
+ onPasswordRequired={onPasswordRequired}
+ />
+ )}
+ </PdfPreviewUnlockGate>
+ );
+ }
return <EmbedPdfViewerContent {...props} />;
};
diff --git a/frontend/editor/src/core/components/viewer/ExportAPIBridge.test.tsx b/frontend/editor/src/core/components/viewer/ExportAPIBridge.test.tsx
new file mode 100644
index 0000000000..c9c1dcfaff
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/ExportAPIBridge.test.tsx
@@ -0,0 +1,82 @@
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { ExportAPIBridge } from "@app/components/viewer/ExportAPIBridge";
+import type { ExportAPIWrapper } from "@app/contexts/viewer/viewerBridges";
+
+const mock = vi.hoisted(() => ({
+ saveAsCopy: vi.fn(),
+ register: vi.fn(),
+ ready: true,
+ available: true,
+}));
+vi.mock("@embedpdf/plugin-export/react", () => ({
+ useExportCapability: () => ({
+ provides: mock.available ? { saveAsCopy: mock.saveAsCopy } : undefined,
+ }),
+}));
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => ({ registerBridge: mock.register }),
+}));
+vi.mock("@app/components/viewer/hooks/useDocumentReady", () => ({
+ useDocumentReady: () => mock.ready,
+}));
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.ready = true;
+ mock.available = true;
+});
+afterEach(cleanup);
+
+function exportApi(): ExportAPIWrapper {
+ return mock.register.mock.calls.at(-1)?.[1].api;
+}
+
+it.each([false, true])(
+ "downloads untouched protected bytes with native export available=%s",
+ async (available) => {
+ mock.available = available;
+ const source = new File(["protected"], "protected.pdf");
+ const bytes = new Uint8Array([37, 80, 68, 70, 45, 10]).buffer;
+ vi.spyOn(source, "arrayBuffer").mockResolvedValue(bytes);
+ render(<ExportAPIBridge originalFile={source} />);
+ expect(await exportApi().saveAsCopy().toPromise()).toBe(bytes);
+ expect(mock.saveAsCopy).not.toHaveBeenCalled();
+ },
+);
+
+it("continues using native export for editable unprotected documents", async () => {
+ const bytes = new ArrayBuffer(4);
+ mock.saveAsCopy.mockReturnValue({ toPromise: async () => bytes });
+ render(<ExportAPIBridge />);
+ expect(await exportApi().saveAsCopy().toPromise()).toBe(bytes);
+ expect(mock.saveAsCopy).toHaveBeenCalledOnce();
+});
+
+it("replaces the source when switching protected documents and unregisters on close", async () => {
+ const first = new File(["one"], "one.pdf");
+ const second = new File(["two"], "two.pdf");
+ const firstBytes = new ArrayBuffer(1);
+ const secondBytes = new ArrayBuffer(2);
+ vi.spyOn(first, "arrayBuffer").mockResolvedValue(firstBytes);
+ vi.spyOn(second, "arrayBuffer").mockResolvedValue(secondBytes);
+ const view = render(<ExportAPIBridge originalFile={first} />);
+ expect(await exportApi().saveAsCopy().toPromise()).toBe(firstBytes);
+ view.rerender(<ExportAPIBridge originalFile={second} />);
+ expect(await exportApi().saveAsCopy().toPromise()).toBe(secondBytes);
+ view.unmount();
+ expect(mock.register).toHaveBeenLastCalledWith("export", null);
+});
+
+it("does not expose an export before the document is ready", () => {
+ mock.ready = false;
+ render(
+ <ExportAPIBridge originalFile={new File(["protected"], "protected.pdf")} />,
+ );
+ expect(mock.register).not.toHaveBeenCalled();
+});
+
+it("never falls back to native export when a protected source is unavailable", () => {
+ render(<ExportAPIBridge disabled />);
+ expect(mock.register).not.toHaveBeenCalled();
+ expect(mock.saveAsCopy).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/core/components/viewer/ExportAPIBridge.tsx b/frontend/editor/src/core/components/viewer/ExportAPIBridge.tsx
index ec81bef5e6..703deb2fbc 100644
--- a/frontend/editor/src/core/components/viewer/ExportAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/ExportAPIBridge.tsx
@@ -1,31 +1,38 @@
-import { useEffect } from "react";
+import { useLayoutEffect } from "react";
import { useExportCapability } from "@embedpdf/plugin-export/react";
import { useViewer } from "@app/contexts/ViewerContext";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
-/**
- * Component that runs inside EmbedPDF context and provides export functionality
- */
-export function ExportAPIBridge() {
+/** Supply originalFile for protected, read-only documents: native export can remove their encryption. */
+export function ExportAPIBridge({
+ disabled = false,
+ originalFile,
+}: {
+ disabled?: boolean;
+ originalFile?: Blob;
+}) {
const { provides: exportApi } = useExportCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
- useEffect(() => {
- if (exportApi && documentReady) {
- // Register this bridge with ViewerContext
+ useLayoutEffect(() => {
+ if (documentReady && !disabled && (originalFile || exportApi)) {
registerBridge("export", {
- state: {
- canExport: true,
- },
- api: exportApi,
+ state: { canExport: true },
+ api: originalFile
+ ? {
+ saveAsCopy: () => ({
+ toPromise: () => originalFile.arrayBuffer(),
+ }),
+ }
+ : exportApi!,
});
}
return () => {
registerBridge("export", null);
};
- }, [exportApi, documentReady, registerBridge]);
+ }, [exportApi, documentReady, registerBridge, disabled, originalFile]);
return null;
}
diff --git a/frontend/editor/src/core/components/viewer/LinkLayer.tsx b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
index 0a2eba501b..7318035cdc 100644
--- a/frontend/editor/src/core/components/viewer/LinkLayer.tsx
+++ b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
@@ -75,6 +75,7 @@ function isInternalLink(annotationLink: PdfLinkAnnoObject): boolean {
// ---------------------------------------------------------------------------
interface LinkToolbarProps {
+ readOnly: boolean;
annotationLink: PdfLinkAnnoObject;
toolbarRef: React.Ref<HTMLDivElement>;
left: number;
@@ -121,6 +122,7 @@ function isRectOutsideViewport(rect: DOMRect): boolean {
const LinkToolbar: React.FC<LinkToolbarProps> = React.memo(
({
+ readOnly,
annotationLink,
toolbarRef,
left,
@@ -149,20 +151,23 @@ const LinkToolbar: React.FC<LinkToolbarProps> = React.memo(
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
- {/* Delete */}
- <ActionIcon
- variant="tertiary"
- className="pdf-link-toolbar-btn pdf-link-toolbar-btn--delete"
- onClick={(e) => {
- e.stopPropagation();
- onDelete(annotationLink);
- }}
- aria-label={t("viewer.link.delete", "Delete link")}
- title={t("viewer.link.delete", "Delete link")}
- >
- <Icon name="trash" size={13} strokeWidth={1.5} />
- </ActionIcon>
- <span className="pdf-link-toolbar-sep" />
+ {!readOnly && (
+ <>
+ <ActionIcon
+ variant="tertiary"
+ className="pdf-link-toolbar-btn pdf-link-toolbar-btn--delete"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(annotationLink);
+ }}
+ aria-label={t("viewer.link.delete", "Delete link")}
+ title={t("viewer.link.delete", "Delete link")}
+ >
+ <Icon name="trash" size={13} strokeWidth={1.5} />
+ </ActionIcon>
+ <span className="pdf-link-toolbar-sep" />
+ </>
+ )}
{/* Navigate / Open */}
<Button
@@ -198,6 +203,7 @@ LinkToolbar.displayName = "LinkToolbar";
// ---------------------------------------------------------------------------
interface LinkLayerProps {
+ readOnly?: boolean;
documentId: string;
pageIndex: number;
/** While annotation editing is active, a click selects the link's
@@ -209,6 +215,7 @@ export const LinkLayer: React.FC<LinkLayerProps> = ({
documentId,
pageIndex,
selectionActive = false,
+ readOnly = false,
}) => {
const { t } = useTranslation();
const { provides: scroll } = useScroll(documentId);
@@ -376,10 +383,10 @@ export const LinkLayer: React.FC<LinkLayerProps> = ({
(annotationLink: PdfLinkAnnoObject) => {
setHoveredLinkId(null);
setToolbarPlacement(null);
- if (!scope) return;
+ if (!scope || readOnly) return;
scope.deleteAnnotation(pageIndex, annotationLink.id);
},
- [scope, pageIndex],
+ [scope, pageIndex, readOnly],
);
useEffect(() => () => clearLeaveTimer(), [clearLeaveTimer]);
@@ -435,6 +442,7 @@ export const LinkLayer: React.FC<LinkLayerProps> = ({
typeof document !== "undefined"
? createPortal(
<LinkToolbar
+ readOnly={readOnly}
annotationLink={hoveredAnnotationLink}
toolbarRef={toolbarElementRef}
left={toolbarPlacement.left}
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 91ca801780..68384cd58b 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -51,7 +51,9 @@ import { HistoryPluginPackage } from "@embedpdf/plugin-history/react";
import {
AnnotationLayer,
AnnotationPluginPackage,
+ useAnnotationCapability,
} from "@embedpdf/plugin-annotation/react";
+import { LockModeType } from "@embedpdf/plugin-annotation";
import type { AnnotationEvent } from "@embedpdf/plugin-annotation";
import type { BoxedAnnotationRenderer } from "@embedpdf/plugin-annotation/react";
import {
@@ -101,6 +103,10 @@ import { RedactionSelectionMenu } from "@app/components/viewer/RedactionSelectio
import { AnnotationSelectionMenu } from "@app/components/viewer/AnnotationSelectionMenu";
import { AnnotationMenuEvents } from "@app/components/viewer/AnnotationMenuEvents";
import { DocumentSwapBridge } from "@app/components/viewer/DocumentSwapBridge";
+import { PdfPasswordBridge } from "@app/components/viewer/PdfPasswordBridge";
+import { isStirlingFile } from "@app/types/fileContext";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { canPrintPdf } from "@app/services/pdfPermissions";
import {
DocumentRestoreBridge,
type DocumentRestoreEvent,
@@ -184,6 +190,7 @@ interface LocalEmbedPDFProps {
onDocumentReady?: (fileKey: string) => void;
/** Includes byte-read failures, engine errors and cancelled loads. */
onDocumentLoadFailed?: (fileKey: string, error: unknown) => void;
+ onPasswordRequired?: () => void;
/** True while a view restore is in flight; gates the per-page layout hook. */
restorePending?: boolean;
restoreRequest?: DocumentRestoreRequest | null;
@@ -408,6 +415,7 @@ interface PageLayerOptions {
enableFormFill: boolean;
formEditingActive: boolean;
enableAnnotations: boolean;
+ annotationsReadOnly: boolean;
enableRedaction: boolean;
showBakedAnnotations: boolean;
onAnnotationMenuAnchor: (anchor: AnnotationMenuAnchor | null) => void;
@@ -441,7 +449,11 @@ function PageTiles({
);
}
-function PageTextSelection({ documentId, pageIndex }: PageLayerProps) {
+function PageTextSelection({
+ documentId,
+ pageIndex,
+ readOnly,
+}: PageLayerProps & { readOnly: boolean }) {
return (
<>
<div
@@ -456,7 +468,9 @@ function PageTextSelection({ documentId, pageIndex }: PageLayerProps) {
documentId={documentId}
pageIndex={pageIndex}
background="var(--pdf-selection-bg)"
- selectionMenu={(props) => <TextSelectionMenu {...props} />}
+ selectionMenu={(props) => (
+ <TextSelectionMenu {...props} readOnly={readOnly} />
+ )}
/>
</div>
<TextSelectionHandler documentId={documentId} pageIndex={pageIndex} />
@@ -595,6 +609,7 @@ function PageLayers({
enableFormFill,
formEditingActive,
enableAnnotations,
+ annotationsReadOnly,
enableRedaction,
showBakedAnnotations,
onAnnotationMenuAnchor,
@@ -610,7 +625,11 @@ function PageLayers({
renderMode={pdfRenderMode}
/>
<CustomSearchLayer documentId={documentId} pageIndex={pageIndex} />
- <PageTextSelection documentId={documentId} pageIndex={pageIndex} />
+ <PageTextSelection
+ documentId={documentId}
+ pageIndex={pageIndex}
+ readOnly={annotationsReadOnly}
+ />
<FormFillLayers
enabled={enableFormFill}
editing={formEditingActive}
@@ -643,7 +662,8 @@ function PageLayers({
<LinkLayer
documentId={documentId}
pageIndex={pageIndex}
- selectionActive={isAnnotationMode}
+ selectionActive={isAnnotationMode && !annotationsReadOnly}
+ readOnly={annotationsReadOnly}
/>
{readOnlySignaturePreviews && (
<SignaturePreviewLayer
@@ -737,6 +757,7 @@ function DocumentViewport({ documentId, pageOptions }: DocumentViewportProps) {
interface DocumentCommentsProps {
enabled: boolean;
+ readOnly: boolean;
documentId: string;
authorName: string;
visible: boolean;
@@ -745,6 +766,7 @@ interface DocumentCommentsProps {
function DocumentComments({
enabled,
+ readOnly,
documentId,
authorName,
visible,
@@ -754,6 +776,8 @@ function DocumentComments({
return (
<CommentAuthorProvider displayName={authorName}>
<CommentsSidebar
+ key={documentId}
+ readOnly={readOnly}
documentId={documentId}
visible={visible}
rightOffset={rightOffset}
@@ -762,6 +786,24 @@ function DocumentComments({
);
}
+function AnnotationInteractionLock({
+ documentId,
+ readOnly,
+}: {
+ documentId: string;
+ readOnly: boolean;
+}) {
+ const { provides } = useAnnotationCapability();
+ useLayoutEffect(() => {
+ const scope = provides?.forDocument(documentId);
+ scope?.setLocked({
+ type: readOnly ? LockModeType.All : LockModeType.None,
+ });
+ if (readOnly) scope?.setActiveTool(null);
+ }, [provides, documentId, readOnly]);
+ return null;
+}
+
type EditingBridgesProps = Pick<
LocalEmbedPDFProps,
| "historyApiRef"
@@ -852,12 +894,16 @@ export function LocalEmbedPDF({
onDocumentSwapFailed,
onDocumentReady,
onDocumentLoadFailed,
+ onPasswordRequired,
restorePending = false,
restoreRequest = null,
onRestoreEvent,
}: LocalEmbedPDFProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
+ const pdfAccess = usePdfAccess(file ?? fileId);
+ const annotationsReadOnly = Boolean(pdfAccess?.encrypted);
+ const showAnnotations = enableAnnotations || annotationsReadOnly;
const [pdfUrl, setPdfUrl] = useState<string | null>(() => url ?? null);
const [, setAnnotations] = useState<
Array<{ id: string; pageIndex: number; rect: Rect }>
@@ -992,11 +1038,13 @@ export function LocalEmbedPDF({
buffer: ArrayBuffer;
name: string;
fileKey: string;
+ password?: string;
} | null>(null);
const [pendingDocument, setPendingDocument] = useState<{
buffer: ArrayBuffer;
name: string;
fileKey: string;
+ password?: string;
} | null>(null);
const initialDocumentOpenedRef = useRef(false);
const openedContentKeyRef = useRef<string | null>(null);
@@ -1056,10 +1104,20 @@ export function LocalEmbedPDF({
openedContentKeyRef.current = contentKey;
if (!initialDocumentOpenedRef.current) {
initialDocumentOpenedRef.current = true;
- setInitialDocument({ buffer, name, fileKey: contentKey });
+ setInitialDocument({
+ buffer,
+ name,
+ fileKey: contentKey,
+ password: pdfAccess?.password,
+ });
return;
}
- setPendingDocument({ buffer, name, fileKey: contentKey });
+ setPendingDocument({
+ buffer,
+ name,
+ fileKey: contentKey,
+ password: pdfAccess?.password,
+ });
};
const fail = (source: string) => (err: unknown) => {
if (cancelled) return;
@@ -1195,7 +1253,13 @@ export function LocalEmbedPDF({
if (!initialSource) return [];
const initialDocuments: InitialDocumentOptions[] =
"buffer" in initialSource
- ? [{ buffer: initialSource.buffer, name: initialSource.name }]
+ ? [
+ {
+ buffer: initialSource.buffer,
+ name: initialSource.name,
+ password: initialSource.password,
+ },
+ ]
: [{ url: initialSource.url, name: initialSource.name }];
// Calculate 3.5rem in pixels dynamically based on root font size
@@ -1218,7 +1282,7 @@ export function LocalEmbedPDF({
createPluginRegistration(ScrollPluginPackage),
createPluginRegistration(RenderPluginPackage, {
withForms: !enableFormFill,
- withAnnotations: !enableAnnotations, // Show baked annotations only when annotation layer is OFF; live layer visibility is controlled via CSS
+ withAnnotations: !showAnnotations,
}),
// Register interaction manager (required for zoom and selection features)
@@ -1288,7 +1352,7 @@ export function LocalEmbedPDF({
createPluginRegistration(PrintPluginPackage),
];
- }, [initialDocument, urlPluginsSource, enableAnnotations]);
+ }, [initialDocument, urlPluginsSource, showAnnotations]);
const fontFallbackConfig = useFontFallbackConfig();
@@ -1411,7 +1475,7 @@ export function LocalEmbedPDF({
if (!annotationPlugin || !annotationPlugin.provides) return;
const annotationApi = annotationPlugin.provides();
- if (!annotationApi || !enableAnnotations) return;
+ if (!annotationApi) return;
registerAnnotationTools(annotationApi);
@@ -1485,7 +1549,8 @@ export function LocalEmbedPDF({
pdfRenderMode,
enableFormFill,
formEditingActive,
- enableAnnotations,
+ enableAnnotations: showAnnotations,
+ annotationsReadOnly,
enableRedaction,
showBakedAnnotations,
onAnnotationMenuAnchor: handleAnnotationMenuAnchor,
@@ -1555,7 +1620,9 @@ export function LocalEmbedPDF({
<EditingBridges
enableAnnotations={enableAnnotations}
enableRedaction={enableRedaction}
- isManualRedactionMode={isManualRedactionMode}
+ isManualRedactionMode={
+ isManualRedactionMode && !annotationsReadOnly
+ }
isSignMode={isSignMode}
historyApiRef={historyApiRef}
signatureApiRef={signatureApiRef}
@@ -1566,11 +1633,28 @@ export function LocalEmbedPDF({
deletedAnnotationMenu={deletedAnnotationMenu}
onDismissDeletedAnnotationMenu={dismissDeletedAnnotationMenu}
/>
- <ExportAPIBridge />
+ <PdfPasswordBridge
+ fileId={file && isStirlingFile(file) ? file.fileId : undefined}
+ password={pdfAccess?.password}
+ onPasswordRequired={onPasswordRequired}
+ />
+ <ExportAPIBridge
+ originalFile={pdfAccess?.encrypted ? file : undefined}
+ disabled={pdfAccess?.encrypted && !file}
+ />
<BookmarkAPIBridge />
<AttachmentAPIBridge />
- <PrintAPIBridge file={file} url={pdfUrl} fileName={fileName} />
- <DocumentPermissionsAPIBridge />
+ <PrintAPIBridge
+ file={file}
+ url={pdfUrl}
+ fileName={fileName}
+ canPrint={canPrintPdf(pdfAccess)}
+ />
+ <DocumentPermissionsAPIBridge
+ isEncrypted={pdfAccess?.encrypted}
+ isOwnerUnlocked={pdfAccess?.ownerAuthenticated}
+ permissions={pdfAccess?.permissions}
+ />
<DocumentReadyWrapper
fallback={
<Center style={{ height: "100%", width: "100%" }}>
@@ -1580,12 +1664,17 @@ export function LocalEmbedPDF({
>
{(documentId) => (
<>
+ <AnnotationInteractionLock
+ documentId={documentId}
+ readOnly={annotationsReadOnly}
+ />
<DocumentViewport
documentId={documentId}
pageOptions={pageOptions}
/>
<DocumentComments
- enabled={enableAnnotations}
+ enabled={showAnnotations}
+ readOnly={annotationsReadOnly}
documentId={documentId}
authorName={commentAuthorName}
visible={isCommentsSidebarVisible}
diff --git a/frontend/editor/src/core/components/viewer/PdfPasswordBridge.test.tsx b/frontend/editor/src/core/components/viewer/PdfPasswordBridge.test.tsx
new file mode 100644
index 0000000000..fcb7473076
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/PdfPasswordBridge.test.tsx
@@ -0,0 +1,101 @@
+import { act, render, waitFor, cleanup } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { PdfPasswordBridge } from "@app/components/viewer/PdfPasswordBridge";
+import { PdfErrorCode } from "@embedpdf/models";
+import type { FileId } from "@app/types/file";
+
+const mock = vi.hoisted(() => ({
+ retry: vi.fn(),
+ prompt: vi.fn(),
+ document: { id: "native-doc", status: "error", errorCode: 4 },
+ loaded: vi.fn(),
+}));
+vi.mock("@embedpdf/plugin-document-manager/react", () => ({
+ useActiveDocument: () => ({ activeDocument: mock.document }),
+ useDocumentManagerCapability: () => ({
+ provides: { retryDocument: mock.retry },
+ }),
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileActions: () => ({
+ actions: { openEncryptedUnlockPrompt: mock.prompt },
+ }),
+}));
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.document = { id: "native-doc", status: "error", errorCode: 4 };
+ mock.document.errorCode = PdfErrorCode.Password;
+ mock.loaded.mockResolvedValue(undefined);
+ mock.retry.mockReturnValue({
+ toPromise: async () => ({ task: { toPromise: mock.loaded } }),
+ });
+});
+afterEach(cleanup);
+
+it("prompts once for a native password failure then retries the same document with the session credential", async () => {
+ const fileId = "file" as FileId;
+ const view = render(<PdfPasswordBridge fileId={fileId} />);
+ expect(mock.prompt).toHaveBeenCalledExactlyOnceWith(fileId);
+ view.rerender(
+ <PdfPasswordBridge fileId={fileId} password=" exact password " />,
+ );
+ await waitFor(() => expect(mock.loaded).toHaveBeenCalledOnce());
+ expect(mock.retry).toHaveBeenCalledExactlyOnceWith("native-doc", {
+ password: " exact password ",
+ });
+ view.rerender(
+ <PdfPasswordBridge fileId={fileId} password=" exact password " />,
+ );
+ expect(mock.retry).toHaveBeenCalledOnce();
+});
+
+it("does not mistake a corrupt document for a password failure", () => {
+ mock.document.errorCode = 99;
+ render(<PdfPasswordBridge fileId="file" password="password" />);
+ expect(mock.retry).not.toHaveBeenCalled();
+ expect(mock.prompt).not.toHaveBeenCalled();
+});
+
+it("keeps a rejected native retry in the unlock flow", async () => {
+ mock.loaded.mockRejectedValueOnce(new Error("password rejected"));
+ render(<PdfPasswordBridge fileId="file" password="password" />);
+ await waitFor(() => expect(mock.prompt).toHaveBeenCalledWith("file"));
+});
+
+it.each(["switch", "unmount"])(
+ "ignores a retry failure after %s",
+ async (change) => {
+ let reject!: (error: Error) => void;
+ const retry = new Promise<void>((_resolve, rejectPromise) => {
+ reject = rejectPromise;
+ });
+ mock.loaded.mockReturnValueOnce(retry);
+ const view = render(
+ <PdfPasswordBridge fileId="old-file" password="password" />,
+ );
+ await waitFor(() => expect(mock.loaded).toHaveBeenCalledOnce());
+ if (change === "switch") {
+ mock.document = { id: "other-doc", status: "loaded", errorCode: 0 };
+ view.rerender(<PdfPasswordBridge fileId="other-file" />);
+ } else view.unmount();
+ await act(async () => reject(new Error("late password failure")));
+ expect(mock.prompt).not.toHaveBeenCalled();
+ },
+);
+
+it("requests the preview unlock prompt without a library file ID", () => {
+ const prompt = vi.fn();
+ const view = render(<PdfPasswordBridge onPasswordRequired={prompt} />);
+ expect(prompt).toHaveBeenCalledOnce();
+ view.rerender(<PdfPasswordBridge onPasswordRequired={prompt} />);
+ expect(prompt).toHaveBeenCalledOnce();
+ expect(mock.prompt).not.toHaveBeenCalled();
+});
+
+it("returns a rejected preview credential to the preview prompt", async () => {
+ const prompt = vi.fn();
+ mock.loaded.mockRejectedValueOnce(new Error("password rejected"));
+ render(<PdfPasswordBridge password="stale" onPasswordRequired={prompt} />);
+ await waitFor(() => expect(prompt).toHaveBeenCalledOnce());
+ expect(mock.prompt).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/core/components/viewer/PdfPasswordBridge.tsx b/frontend/editor/src/core/components/viewer/PdfPasswordBridge.tsx
new file mode 100644
index 0000000000..86af4fa342
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/PdfPasswordBridge.tsx
@@ -0,0 +1,66 @@
+import { useEffect, useRef } from "react";
+import {
+ useActiveDocument,
+ useDocumentManagerCapability,
+} from "@embedpdf/plugin-document-manager/react";
+import { PdfErrorCode } from "@embedpdf/models";
+import { useFileActions } from "@app/contexts/FileContext";
+import type { FileId } from "@app/types/file";
+
+/** Retry EmbedPDF's original encrypted document after the shared session prompt authenticates it. */
+export function PdfPasswordBridge({
+ fileId,
+ password,
+ onPasswordRequired,
+}: {
+ fileId?: string | null;
+ password?: string;
+ onPasswordRequired?: () => void;
+}) {
+ const { activeDocument } = useActiveDocument();
+ const { provides: manager } = useDocumentManagerCapability();
+ const { actions } = useFileActions();
+ const attempted = useRef<{ id: string; password: string } | null>(null);
+ const prompted = useRef<string | null>(null);
+
+ useEffect(() => {
+ attempted.current = null;
+ prompted.current = null;
+ return () => {
+ attempted.current = null;
+ };
+ }, [fileId, activeDocument?.id]);
+
+ useEffect(() => {
+ if (
+ !manager ||
+ activeDocument?.errorCode !== PdfErrorCode.Password ||
+ activeDocument.status !== "error"
+ )
+ return;
+ const id = activeDocument.id;
+ const prompt = () => {
+ if (onPasswordRequired) onPasswordRequired();
+ else if (fileId) actions.openEncryptedUnlockPrompt(fileId as FileId);
+ };
+ if (
+ password !== undefined &&
+ (attempted.current?.id !== id || attempted.current.password !== password)
+ ) {
+ const attempt = { id, password };
+ attempted.current = attempt;
+ void manager
+ .retryDocument(id, { password })
+ .toPromise()
+ .then((response) => response.task.toPromise())
+ .catch(() => {
+ if (attempted.current === attempt) prompt();
+ });
+ } else if ((fileId || onPasswordRequired) && prompted.current !== id) {
+ prompted.current = id;
+ prompt();
+ }
+ }, [manager, activeDocument, password, fileId, actions, onPasswordRequired]);
+
+ return null;
+}
diff --git a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx
new file mode 100644
index 0000000000..621e958260
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.test.tsx
@@ -0,0 +1,194 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { ComponentProps } from "react";
+import { PdfPreviewUnlockGate } from "@app/components/viewer/PdfPreviewUnlockGate";
+import type EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";
+import {
+ clearPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+} from "@app/services/pdfPasswordStore";
+
+vi.mock("react-i18next", () => {
+ const t = (key: string, fallback?: string) => fallback ?? key;
+ return { useTranslation: () => ({ t }) };
+});
+
+const mock = vi.hoisted(() => ({ probe: vi.fn(), unlock: vi.fn() }));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ looksEncryptedFromTrailer: mock.probe,
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileActions: () => ({ actions: { unlockPreviewPdf: mock.unlock } }),
+}));
+vi.mock("@app/components/tools/ToolLoadingFallback", () => ({
+ default: () => <span>Checking PDF</span>,
+}));
+vi.mock("@app/components/shared/EncryptedPdfUnlockModal", () => ({
+ default: (props: ComponentProps<typeof EncryptedPdfUnlockModal>) =>
+ props.opened ? (
+ <div role="dialog">
+ <span>{props.fileName}</span>
+ <input
+ aria-label="PDF password"
+ value={props.password}
+ onChange={(event) => props.onPasswordChange(event.target.value)}
+ />
+ {props.errorMessage && <span role="alert">{props.errorMessage}</span>}
+ <button onClick={props.onUnlock}>Submit password</button>
+ <button onClick={props.onSkip}>Dismiss</button>
+ </div>
+ ) : null,
+}));
+const access: PdfAccess = {
+ password: "secret",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ canModify: false,
+ canAssemble: false,
+ pageCount: 1,
+};
+const passwordError = {
+ isAxiosError: true,
+ response: { status: 400, data: { type: "/errors/pdf-password" } },
+};
+const file = () => new File(["protected"], "preview.pdf", { lastModified: 1 });
+function preview(pdf: File, close = vi.fn()) {
+ return (
+ <MantineProvider>
+ <PdfPreviewUnlockGate file={pdf} onClose={close}>
+ {(required) => <button onClick={required}>Rendered PDF</button>}
+ </PdfPreviewUnlockGate>
+ </MantineProvider>
+ );
+}
+beforeEach(() => {
+ vi.resetAllMocks();
+ clearPdfAccess();
+ mock.probe.mockResolvedValue(true);
+ mock.unlock.mockRejectedValue(passwordError);
+});
+afterEach(() => {
+ cleanup();
+ clearPdfAccess();
+});
+
+it("keeps an ordinary preview out of the viewer until its probe completes", async () => {
+ let finish!: (protectedPdf: boolean) => void;
+ mock.probe.mockReturnValue(
+ new Promise<boolean>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ render(preview(file()));
+ expect(screen.queryByText("Rendered PDF")).toBeNull();
+ await act(async () => finish(false));
+ expect(screen.getByText("Rendered PDF")).toBeVisible();
+ expect(mock.unlock).not.toHaveBeenCalled();
+});
+
+it("unlocks a plain File preview, keeping a wrong password in the shared prompt", async () => {
+ const pdf = file();
+ render(preview(pdf));
+ await screen.findByRole("dialog");
+ expect(screen.queryByText("Rendered PDF")).toBeNull();
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: "wrong" },
+ });
+ fireEvent.click(screen.getByText("Submit password"));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Incorrect password",
+ );
+ mock.unlock.mockImplementation(async (bytes: File, password: string) =>
+ rememberPdfAccess(bytes, { ...access, password }),
+ );
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: " secret " },
+ });
+ fireEvent.click(screen.getByText("Submit password"));
+ await screen.findByText("Rendered PDF");
+ expect(mock.unlock).toHaveBeenLastCalledWith(
+ pdf,
+ " secret ",
+ expect.any(AbortSignal),
+ );
+ expect(screen.queryByRole("dialog")).toBeNull();
+});
+
+it("inspects owner-only protection without prompting and keeps its permissions", async () => {
+ const pdf = file();
+ mock.unlock.mockImplementation(async (bytes: File, password: string) =>
+ rememberPdfAccess(bytes, { ...access, password }),
+ );
+ render(preview(pdf));
+ await screen.findByText("Rendered PDF");
+ expect(mock.unlock).toHaveBeenCalledExactlyOnceWith(
+ pdf,
+ "",
+ expect.any(AbortSignal),
+ );
+ expect(screen.queryByRole("dialog")).toBeNull();
+});
+
+it("reuses exact-byte session access without probing or prompting", () => {
+ const pdf = file();
+ rememberPdfAccess(pdf, access);
+ render(preview(pdf));
+ expect(screen.getByText("Rendered PDF")).toBeVisible();
+ expect(mock.probe).not.toHaveBeenCalled();
+ expect(mock.unlock).not.toHaveBeenCalled();
+});
+
+it("offers the unlock prompt when the native viewer detects protection missed by the probe", async () => {
+ mock.probe.mockResolvedValue(false);
+ render(preview(file()));
+ fireEvent.click(await screen.findByText("Rendered PDF"));
+ expect(screen.getByRole("dialog")).toBeVisible();
+ expect(screen.queryByText("Rendered PDF")).toBeNull();
+});
+
+it("closing the prompt closes the preview without rendering protected bytes", async () => {
+ const close = vi.fn();
+ render(preview(file(), close));
+ fireEvent.click(await screen.findByText("Dismiss"));
+ expect(close).toHaveBeenCalledOnce();
+ expect(screen.queryByText("Rendered PDF")).toBeNull();
+});
+
+it("ignores a late failure when another File has identical metadata", async () => {
+ let reject!: (error: unknown) => void;
+ mock.unlock.mockReturnValueOnce(
+ new Promise<void>((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const view = render(preview(file()));
+ await waitFor(() => expect(mock.unlock).toHaveBeenCalledOnce());
+ const oldSignal = mock.unlock.mock.calls[0][2] as AbortSignal;
+ mock.probe.mockResolvedValue(false);
+ view.rerender(preview(file()));
+ await screen.findByText("Rendered PDF");
+ expect(oldSignal.aborted).toBe(true);
+ await act(async () => reject(passwordError));
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(screen.getByText("Rendered PDF")).toBeVisible();
+});
+
+it("does not redisplay a rejected cached credential after dismissing its prompt", async () => {
+ const pdf = file();
+ rememberPdfAccess(pdf, access);
+ render(preview(pdf));
+ fireEvent.click(screen.getByText("Rendered PDF"));
+ fireEvent.click(await screen.findByText("Dismiss"));
+ expect(screen.queryByText("Rendered PDF")).toBeNull();
+});
diff --git a/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx
new file mode 100644
index 0000000000..20c8e21b3f
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/PdfPreviewUnlockGate.tsx
@@ -0,0 +1,181 @@
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { Center, Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";
+import ToolLoadingFallback from "@app/components/tools/ToolLoadingFallback";
+import { useFileActions } from "@app/contexts/FileContext";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { looksEncryptedFromTrailer } from "@app/utils/thumbnailUtils";
+import { handlePasswordError } from "@app/utils/toolErrorHandler";
+
+interface PreviewState {
+ file: File;
+ status: "checking" | "ready" | "locked" | "rejected" | "error";
+ prompt: boolean;
+ error: string | null;
+}
+
+/** Keeps preview bytes outside the library and gates rendering until session access is known. */
+export function PdfPreviewUnlockGate({
+ file,
+ onClose,
+ children,
+}: {
+ file: File;
+ onClose?: () => void;
+ children: (onPasswordRequired: () => void) => ReactNode;
+}) {
+ const { t } = useTranslation();
+ const {
+ actions: { unlockPreviewPdf },
+ } = useFileActions();
+ const access = usePdfAccess(file);
+ const [state, setState] = useState<PreviewState | null>(null);
+ const [password, setPassword] = useState("");
+ const [processing, setProcessing] = useState(false);
+ const lifetime = useRef<AbortController | null>(null);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ lifetime.current = controller;
+ setPassword("");
+ setProcessing(false);
+ setState({ file, status: "checking", prompt: false, error: null });
+ const probe = async () => {
+ if (getPdfAccess(file)) {
+ setState({ file, status: "locked", prompt: false, error: null });
+ return;
+ }
+ try {
+ const protectedFile = await looksEncryptedFromTrailer(file);
+ if (controller.signal.aborted) return;
+ if (!protectedFile) {
+ setState({ file, status: "ready", prompt: false, error: null });
+ return;
+ }
+ try {
+ // Owner-only protection opens with an empty password, but still carries print restrictions.
+ await unlockPreviewPdf(file, "", controller.signal);
+ if (!controller.signal.aborted)
+ setState({ file, status: "locked", prompt: false, error: null });
+ } catch (error) {
+ const message = await handlePasswordError(
+ error,
+ "",
+ t(
+ "encryptedPdfUnlock.sessionFailed",
+ "Unable to unlock this PDF. Please try again.",
+ ),
+ );
+ if (!controller.signal.aborted)
+ setState({
+ file,
+ status: "locked",
+ prompt: true,
+ error: message || null,
+ });
+ }
+ } catch {
+ if (!controller.signal.aborted)
+ setState({
+ file,
+ status: "error",
+ prompt: false,
+ error: t(
+ "encryptedPdfUnlock.sessionFailed",
+ "Unable to unlock this PDF. Please try again.",
+ ),
+ });
+ }
+ };
+ void probe();
+ return () => controller.abort();
+ }, [file, unlockPreviewPdf, t]);
+
+ const requirePassword = useCallback(() => {
+ setPassword("");
+ setState({ file, status: "rejected", prompt: true, error: null });
+ }, [file]);
+
+ const unlock = async () => {
+ const controller = lifetime.current;
+ if (!controller || controller.signal.aborted || processing || !password)
+ return;
+ setProcessing(true);
+ try {
+ await unlockPreviewPdf(file, password, controller.signal);
+ if (!controller.signal.aborted) {
+ setPassword("");
+ setState({ file, status: "locked", prompt: false, error: null });
+ }
+ } catch (error) {
+ const message = await handlePasswordError(
+ error,
+ t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),
+ t(
+ "encryptedPdfUnlock.sessionFailed",
+ "Unable to unlock this PDF. Please try again.",
+ ),
+ );
+ if (!controller.signal.aborted)
+ setState({ file, status: "rejected", prompt: true, error: message });
+ } finally {
+ if (!controller.signal.aborted) setProcessing(false);
+ }
+ };
+
+ const current = state?.file === file ? state : null;
+ if (
+ (access && current?.status !== "rejected" && !current?.prompt) ||
+ current?.status === "ready"
+ )
+ return children(requirePassword);
+ if (!current || current.status === "checking") return <ToolLoadingFallback />;
+ return (
+ <>
+ <Center style={{ flex: 1 }}>
+ <Stack align="center" gap="md">
+ <Text>
+ {current.status === "error"
+ ? current.error
+ : t(
+ "encryptedPdfUnlock.viewerLocked",
+ "This PDF is password-protected",
+ )}
+ </Text>
+ <Button onClick={requirePassword}>
+ {t("encryptedPdfUnlock.viewerUnlock", "Unlock")}
+ </Button>
+ {onClose && (
+ <Button variant="secondary" onClick={onClose}>
+ {t("close", "Close")}
+ </Button>
+ )}
+ </Stack>
+ </Center>
+ <EncryptedPdfUnlockModal
+ opened={current.prompt}
+ fileName={file.name}
+ password={password}
+ errorMessage={current.error}
+ isProcessing={processing}
+ sessionUnlock
+ onPasswordChange={setPassword}
+ onUnlock={() => void unlock()}
+ onSkip={() => {
+ setPassword("");
+ setState({ ...current, prompt: false });
+ onClose?.();
+ }}
+ />
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx b/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx
new file mode 100644
index 0000000000..15f2740b90
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/PrintAPIBridge.test.tsx
@@ -0,0 +1,101 @@
+import { cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { DocumentPermissionsAPIBridge } from "@app/components/viewer/DocumentPermissionsAPIBridge";
+import { PrintAPIBridge } from "@app/components/viewer/PrintAPIBridge";
+import { canPrintPdf } from "@app/services/pdfPermissions";
+import { PdfPermissionFlag } from "@app/contexts/viewer/viewerBridges";
+
+const mock = vi.hoisted(() => ({
+ print: vi.fn(),
+ register: vi.fn(),
+ ready: true,
+}));
+vi.mock("@embedpdf/plugin-print/react", () => ({
+ usePrintCapability: () => ({ provides: { print: mock.print } }),
+}));
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => ({ registerBridge: mock.register }),
+}));
+vi.mock("@app/components/viewer/hooks/useDocumentReady", () => ({
+ useDocumentReady: () => mock.ready,
+}));
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.ready = true;
+});
+afterEach(cleanup);
+
+it.each([
+ {
+ encrypted: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ allowed: true,
+ },
+ {
+ encrypted: true,
+ ownerAuthenticated: false,
+ permissions: 0,
+ allowed: false,
+ },
+ {
+ encrypted: true,
+ ownerAuthenticated: false,
+ permissions: PdfPermissionFlag.CopyContents,
+ allowed: false,
+ },
+ {
+ encrypted: true,
+ ownerAuthenticated: false,
+ permissions: PdfPermissionFlag.Print,
+ allowed: true,
+ },
+ { encrypted: true, ownerAuthenticated: true, permissions: 0, allowed: true },
+])("enforces effective print permission for %j", ({ allowed, ...access }) => {
+ render(<PrintAPIBridge canPrint={canPrintPdf(access)} />);
+ const bridge = mock.register.mock.calls.find(
+ ([kind, value]) => kind === "print" && value,
+ )?.[1];
+ expect(Boolean(bridge)).toBe(allowed);
+ bridge?.api.print();
+ expect(mock.print).toHaveBeenCalledTimes(allowed ? 1 : 0);
+});
+
+it("revokes a previously registered action when the replacement denies printing", () => {
+ const view = render(<PrintAPIBridge canPrint />);
+ const previous = mock.register.mock.calls.at(-1)?.[1];
+ previous.api.print();
+ expect(mock.print).toHaveBeenCalledOnce();
+ view.rerender(<PrintAPIBridge canPrint={false} />);
+ expect(mock.register).toHaveBeenLastCalledWith("print", null);
+ previous.api.print();
+ expect(mock.print).toHaveBeenCalledOnce();
+ view.rerender(<PrintAPIBridge canPrint />);
+ mock.register.mock.calls.at(-1)?.[1].api.print();
+ expect(mock.print).toHaveBeenCalledTimes(2);
+});
+
+it("does not expose printing before the document is ready", () => {
+ mock.ready = false;
+ render(<PrintAPIBridge canPrint />);
+ expect(mock.register).not.toHaveBeenCalled();
+});
+
+it.each([false, true])(
+ "reports effective print permission consistently for owner=%s",
+ (owner) => {
+ render(
+ <DocumentPermissionsAPIBridge
+ isEncrypted
+ isOwnerUnlocked={owner}
+ permissions={0}
+ />,
+ );
+ const bridge = mock.register.mock.calls.at(-1)?.[1];
+ expect(bridge.state.canPrint).toBe(owner);
+ expect(bridge.api.getEffectivePermission(PdfPermissionFlag.Print)).toBe(
+ owner,
+ );
+ expect(bridge.api.hasPermission(PdfPermissionFlag.Print)).toBe(false);
+ },
+);
diff --git a/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx b/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx
index fd3492a2b5..943f94b47b 100644
--- a/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/PrintAPIBridge.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useLayoutEffect, useRef } from "react";
import { usePrintCapability } from "@embedpdf/plugin-print/react";
import { useViewer } from "@app/contexts/ViewerContext";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
@@ -7,23 +7,28 @@ export interface PrintAPIBridgeProps {
file?: File | Blob;
url?: string | null;
fileName?: string;
+ canPrint?: boolean;
}
/**
* Connects the PDF print plugin to the shared ViewerContext.
*/
-export function PrintAPIBridge(_props: PrintAPIBridgeProps) {
+export function PrintAPIBridge({ canPrint = true }: PrintAPIBridgeProps) {
const { provides: print } = usePrintCapability();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
- useEffect(() => {
- if (print && documentReady) {
- // Register this bridge with ViewerContext
+ const allowed = useRef(canPrint);
+ allowed.current = canPrint;
+
+ useLayoutEffect(() => {
+ if (print && documentReady && canPrint) {
registerBridge("print", {
state: {},
api: {
- print: () => print.print(),
+ print: () => {
+ if (allowed.current) print.print();
+ },
},
});
}
@@ -31,7 +36,7 @@ export function PrintAPIBridge(_props: PrintAPIBridgeProps) {
return () => {
registerBridge("print", null);
};
- }, [print, documentReady, registerBridge]);
+ }, [print, documentReady, registerBridge, canPrint]);
return null;
}
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
index 94fe5525d4..d6f989ef2e 100644
--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
@@ -29,6 +29,7 @@ import "@app/components/viewer/TextSelectionMenu.css";
export type TextSelectionMenuProps = SelectionSelectionMenuProps & {
documentId?: string;
+ readOnly?: boolean;
};
export function TextSelectionMenu(props: TextSelectionMenuProps) {
@@ -47,6 +48,7 @@ function TextSelectionMenuInner({
menuWrapperProps,
placement,
documentId,
+ readOnly = false,
}: TextSelectionMenuProps & { documentId: string }) {
const { t } = useTranslation();
const { provides: selection } = useSelectionCapability();
@@ -144,7 +146,7 @@ function TextSelectionMenuInner({
color: string,
blendMode?: PdfBlendMode,
) => {
- if (!documentId) return;
+ if (!documentId || readOnly) return;
const selections = selection?.getFormattedSelection(documentId) ?? [];
if (!selections.length) return;
@@ -179,7 +181,14 @@ function TextSelectionMenuInner({
apply();
}
},
- [documentId, selection, annotationProvides, navActions, openAnnotateUi],
+ [
+ documentId,
+ selection,
+ annotationProvides,
+ navActions,
+ openAnnotateUi,
+ readOnly,
+ ],
);
const handleHighlight = useCallback(() => {
@@ -214,7 +223,7 @@ function TextSelectionMenuInner({
const handleAddLink = useCallback(
(url: string) => {
const uri = url.trim();
- if (!documentId || !uri) return;
+ if (!documentId || !uri || readOnly) return;
// User input is untrusted: refuse URI schemes the viewer itself would
// not open, so javascript: and friends cannot ride out in the PDF. The
// original string is persisted verbatim once it passes the allowlist.
@@ -238,11 +247,18 @@ function TextSelectionMenuInner({
navActions?.setHasUnsavedChanges(true);
openAnnotateUi();
},
- [documentId, selection, annotationProvides, navActions, openAnnotateUi],
+ [
+ documentId,
+ selection,
+ annotationProvides,
+ navActions,
+ openAnnotateUi,
+ readOnly,
+ ],
);
const handleRedact = useCallback(() => {
- if (!documentId) return;
+ if (!documentId || readOnly) return;
const selections = selection?.getFormattedSelection(documentId) ?? [];
for (const sel of selections) {
annotationProvides?.createAnnotation(sel.pageIndex, {
@@ -275,6 +291,7 @@ function TextSelectionMenuInner({
setLeftPanelView?.("toolContent");
setPendingRedactActivation(true);
}, [
+ readOnly,
documentId,
selection,
annotationProvides,
@@ -312,117 +329,121 @@ function TextSelectionMenuInner({
</button>
</Tooltip>
- <Tooltip label={t("annotation.highlight", "Highlight")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleHighlight}
- aria-label={t("annotation.highlight", "Highlight")}
- >
- <Icon name="highlighter" size={20} />
- </button>
- </Tooltip>
-
- <Tooltip label={t("annotation.strikeout", "Strikeout")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleStrikeout}
- aria-label={t("annotation.strikeout", "Strikeout")}
- >
- <Icon name="strikethrough" size={20} />
- </button>
- </Tooltip>
-
- <Tooltip label={t("annotation.underline", "Underline")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleUnderline}
- aria-label={t("annotation.underline", "Underline")}
- >
- <Icon name="underline" size={20} />
- </button>
- </Tooltip>
-
- <Tooltip label={t("annotation.squiggly", "Squiggly")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleSquiggly}
- aria-label={t("annotation.squiggly", "Squiggly")}
- >
- <Icon name="line-squiggle" size={20} />
- </button>
- </Tooltip>
-
- <Popover
- opened={linkPopoverOpen}
- onChange={setLinkPopoverOpen}
- position={showAbove ? "top" : "bottom"}
- withArrow
- shadow="md"
- transitionProps={{ duration: 0 }}
- >
- <Popover.Target>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={() => setLinkPopoverOpen((o) => !o)}
- aria-label={t("viewer.comments.addLink", "Add link")}
- >
- <Tooltip
- label={t("viewer.comments.addLink", "Add link")}
- withArrow
- disabled={linkPopoverOpen}
+ {!readOnly && (
+ <>
+ <Tooltip label={t("annotation.highlight", "Highlight")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleHighlight}
+ aria-label={t("annotation.highlight", "Highlight")}
>
- <span style={{ display: "inline-flex" }}>
- <Icon name="link" size={20} />
- </span>
- </Tooltip>
- </button>
- </Popover.Target>
- <Popover.Dropdown
- onMouseDown={(e) => e.stopPropagation()}
- style={{
- backgroundColor: "var(--mantine-color-body)",
- borderColor: "var(--mantine-color-default-border)",
- }}
- >
- <Stack gap="xs" style={{ minWidth: 220 }}>
- <TextInput
- placeholder="https://..."
- value={linkUrl}
- onChange={(e) => setLinkUrl(e.currentTarget.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && linkUrl.trim()) {
- handleAddLink(linkUrl);
- }
+ <Icon name="highlighter" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.strikeout", "Strikeout")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleStrikeout}
+ aria-label={t("annotation.strikeout", "Strikeout")}
+ >
+ <Icon name="strikethrough" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.underline", "Underline")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleUnderline}
+ aria-label={t("annotation.underline", "Underline")}
+ >
+ <Icon name="underline" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.squiggly", "Squiggly")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleSquiggly}
+ aria-label={t("annotation.squiggly", "Squiggly")}
+ >
+ <Icon name="line-squiggle" size={20} />
+ </button>
+ </Tooltip>
+
+ <Popover
+ opened={linkPopoverOpen}
+ onChange={setLinkPopoverOpen}
+ position={showAbove ? "top" : "bottom"}
+ withArrow
+ shadow="md"
+ transitionProps={{ duration: 0 }}
+ >
+ <Popover.Target>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={() => setLinkPopoverOpen((o) => !o)}
+ aria-label={t("viewer.comments.addLink", "Add link")}
+ >
+ <Tooltip
+ label={t("viewer.comments.addLink", "Add link")}
+ withArrow
+ disabled={linkPopoverOpen}
+ >
+ <span style={{ display: "inline-flex" }}>
+ <Icon name="link" size={20} />
+ </span>
+ </Tooltip>
+ </button>
+ </Popover.Target>
+ <Popover.Dropdown
+ onMouseDown={(e) => e.stopPropagation()}
+ style={{
+ backgroundColor: "var(--mantine-color-body)",
+ borderColor: "var(--mantine-color-default-border)",
}}
- size="xs"
- autoFocus
- />
- <Button
- size="sm"
- disabled={!linkUrl.trim()}
- onClick={() => handleAddLink(linkUrl)}
>
- {t("viewer.comments.addLink", "Add link")}
- </Button>
- </Stack>
- </Popover.Dropdown>
- </Popover>
-
- <Tooltip label={t("workbenchBar.redact", "Redact")} withArrow>
- <button
- type="button"
- className="embedpdf-text-selection-btn"
- onClick={handleRedact}
- aria-label={t("workbenchBar.redact", "Redact")}
- >
- <Icon name="file-x" size={20} />
- </button>
- </Tooltip>
+ <Stack gap="xs" style={{ minWidth: 220 }}>
+ <TextInput
+ placeholder="https://..."
+ value={linkUrl}
+ onChange={(e) => setLinkUrl(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && linkUrl.trim()) {
+ handleAddLink(linkUrl);
+ }
+ }}
+ size="xs"
+ autoFocus
+ />
+ <Button
+ size="sm"
+ disabled={!linkUrl.trim()}
+ onClick={() => handleAddLink(linkUrl)}
+ >
+ {t("viewer.comments.addLink", "Add link")}
+ </Button>
+ </Stack>
+ </Popover.Dropdown>
+ </Popover>
+
+ <Tooltip label={t("workbenchBar.redact", "Redact")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleRedact}
+ aria-label={t("workbenchBar.redact", "Redact")}
+ >
+ <Icon name="file-x" size={20} />
+ </button>
+ </Tooltip>
+ </>
+ )}
</div>
</div>,
document.body,
diff --git a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
index 1bfd0d152d..0082781ed9 100644
--- a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
+++ b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
@@ -46,34 +46,44 @@ describe("form save document completion", () => {
mocks.active = { status: "loading", error: null };
});
- it("waits for the saved document's loaded task and ignores unrelated document events", async () => {
- const load = deferred<void>();
- mocks.open.mockReturnValue({
- toPromise: async () => ({
- documentId: "saved",
- task: { toPromise: () => load.promise },
- }),
- });
- const { result } = renderHook(useDocumentLoadWaiter);
- const saved = result.current.waitForDocument("B-saved");
- const completed = vi.fn();
- void saved.then(completed);
- result.current.documentReady("A");
- result.current.documentFailed("A", new Error("unrelated"));
- render(
- <DocumentSwapBridge
- pending={pending("B-saved")}
- onSwapped={(_, key) => result.current.documentReady(key)}
- onFailed={result.current.documentFailed}
- />,
- );
- await act(async () => {});
- expect(completed).not.toHaveBeenCalled();
- await act(async () => load.resolve());
- await saved;
- expect(mocks.activate).toHaveBeenCalledWith("saved");
- expect(completed).toHaveBeenCalledOnce();
- });
+ it.each([undefined, "session-password"])(
+ "waits for the saved document's loaded task and ignores unrelated document events (password: %s)",
+ async (password) => {
+ const load = deferred<void>();
+ mocks.open.mockReturnValue({
+ toPromise: async () => ({
+ documentId: "saved",
+ task: { toPromise: () => load.promise },
+ }),
+ });
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B-saved");
+ const completed = vi.fn();
+ void saved.then(completed);
+ result.current.documentReady("A");
+ result.current.documentFailed("A", new Error("unrelated"));
+ const replacement = { ...pending("B-saved"), password };
+ render(
+ <DocumentSwapBridge
+ pending={replacement}
+ onSwapped={(_, key) => result.current.documentReady(key)}
+ onFailed={result.current.documentFailed}
+ />,
+ );
+ await act(async () => {});
+ expect(mocks.open).toHaveBeenCalledExactlyOnceWith({
+ buffer: replacement.buffer,
+ name: replacement.name,
+ password,
+ autoActivate: false,
+ });
+ expect(completed).not.toHaveBeenCalled();
+ await act(async () => load.resolve());
+ await saved;
+ expect(mocks.activate).toHaveBeenCalledWith("saved");
+ expect(completed).toHaveBeenCalledOnce();
+ },
+ );
it.each(["unmount", "clear"])(
"rejects a save when its swap is cancelled by %s",
diff --git a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
index b948de417d..6b72557387 100644
--- a/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.pendingUnlock.test.tsx
@@ -5,11 +5,21 @@ import {
fireEvent,
renderHook,
screen,
+ waitFor,
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { FileContextProvider, useFileActions } from "@app/contexts/FileContext";
+import {
+ FileContextProvider,
+ useFileActions,
+ useFileSelectors,
+} from "@app/contexts/FileContext";
+import apiClient from "@app/services/apiClient";
+import { getPdfAccess, bindPdfAccess } from "@app/services/pdfPasswordStore";
+import { fileStorage } from "@app/services/fileStorage";
+import { generateProcessedFileMetadata } from "@app/contexts/file/fileActions";
import {
createStirlingFile,
+ createNewStirlingFileStub,
type FileId,
type StirlingFileStub,
} from "@app/types/fileContext";
@@ -18,9 +28,15 @@ import {
setPendingUnlocks,
} from "@app/services/pendingUnlocks";
-const observed = vi.hoisted(() => ({ heldBeforeEffects: false }));
+const observed = vi.hoisted(() => ({
+ isEncrypted: true,
+ heldBeforeEffects: false,
+ afterDispatch: undefined as (() => Promise<void>) | undefined,
+}));
const id = "editor-encrypted" as FileId;
+vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => null,
}));
@@ -39,14 +55,39 @@ vi.mock("@app/components/shared/ZipWarningModal", () => ({
default: () => null,
}));
vi.mock("@app/components/shared/EncryptedPdfUnlockModal", () => ({
- default: ({ opened, onSkip }: { opened: boolean; onSkip: () => void }) =>
- opened ? <button onClick={onSkip}>Skip unlock</button> : null,
+ default: ({
+ opened,
+ onSkip,
+ onUnlock,
+ onRemovePassword,
+ onPasswordChange,
+ }: {
+ opened: boolean;
+ onSkip: () => void;
+ onUnlock: () => void;
+ onRemovePassword: () => void;
+ onPasswordChange: (password: string) => void;
+ }) =>
+ opened ? (
+ <>
+ <button onClick={onSkip}>Cancel opening</button>
+ <input
+ aria-label="PDF password"
+ onChange={(event) => onPasswordChange(event.target.value)}
+ />
+ <button onClick={onUnlock}>Unlock</button>
+ <button onClick={onRemovePassword}>Remove Password</button>
+ </>
+ ) : null,
}));
vi.mock("@app/contexts/file/fileActions", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@app/contexts/file/fileActions")>();
return {
...actual,
+ generateProcessedFileMetadata: vi
+ .fn()
+ .mockResolvedValue({ pages: [], totalPages: 1 }),
addFiles: vi.fn<typeof actual.addFiles>(
async (options, _stateRef, filesRef, dispatch) => {
const source = options.files?.[0];
@@ -61,11 +102,12 @@ vi.mock("@app/contexts/file/fileActions", async (importOriginal) => {
isLeaf: true,
originalFileId: id,
versionNumber: 1,
- processedFile: { pages: [], isEncrypted: true },
+ processedFile: { pages: [], isEncrypted: observed.isEncrypted },
};
filesRef.current.set(id, file);
dispatch({ type: "ADD_FILES", payload: { stirlingFileStubs: [stub] } });
observed.heldBeforeEffects = isAwaitingUnlock(id);
+ await observed.afterDispatch?.();
return [file];
},
),
@@ -81,58 +123,475 @@ function wrapper({ children }: { children: ReactNode }) {
}
beforeEach(() => {
+ vi.mocked(generateProcessedFileMetadata).mockResolvedValue({
+ pages: [],
+ totalPages: 1,
+ isEncrypted: false,
+ });
+ observed.isEncrypted = true;
observed.heldBeforeEffects = false;
+ observed.afterDispatch = undefined;
setPendingUnlocks([]);
});
+
+describe("protected tool replacements", () => {
+ beforeEach(() => {
+ observed.isEncrypted = false;
+ vi.spyOn(fileStorage, "persistVersionedOutputs").mockResolvedValue();
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it.each(["cancel", "unlock", "remove-password"])(
+ "retains inputs until %s settles the output",
+ async (decision) => {
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ await act(() =>
+ result.current.actions.addFiles([new File(["original"], "source.pdf")]),
+ );
+ const output = createStirlingFile(
+ new File(["encrypted"], "protected.pdf"),
+ );
+ const stub = createNewStirlingFileStub(output, output.fileId, undefined, {
+ pages: [],
+ isEncrypted: true,
+ });
+ let consuming!: ReturnType<typeof result.current.actions.consumeFiles>;
+ await act(async () => {
+ consuming = result.current.actions.consumeFiles(
+ [id],
+ [output],
+ [stub],
+ { silent: true },
+ );
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([id]);
+ expect(result.current.selectors.getFile(output.fileId)).toBeUndefined();
+ if (decision === "cancel") {
+ await act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ await consuming;
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([id]);
+ await expect(consuming).resolves.toEqual([]);
+ 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,
+ },
+ });
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: "secret" },
+ });
+ await act(async () => {
+ fireEvent.click(
+ screen.getByText(
+ decision === "unlock" ? "Unlock" : "Remove Password",
+ ),
+ );
+ await consuming;
+ });
+ const accepted = await consuming;
+ expect(accepted).toHaveLength(1);
+ expect(result.current.selectors.getAllFileIds()).toEqual(accepted);
+ expect(
+ result.current.selectors.getStirlingFileStub(accepted[0]),
+ ).toMatchObject({
+ derivedFromTool: true,
+ sourceFileIds: [id],
+ processedFile: { isEncrypted: decision === "unlock" },
+ });
+ },
+ );
+
+ it.each(["cancel", "clear"])(
+ "handles %s after part of a protected batch is admitted",
+ async (decision) => {
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ await act(() =>
+ result.current.actions.addFiles([new File(["original"], "source.pdf")]),
+ );
+ const outputs = ["first", "second"].map((name) =>
+ createStirlingFile(new File(["encrypted"], `${name}.pdf`)),
+ );
+ const stubs = outputs.map((file) =>
+ createNewStirlingFileStub(file, file.fileId, undefined, {
+ pages: [],
+ isEncrypted: true,
+ }),
+ );
+ let consuming!: ReturnType<typeof result.current.actions.consumeFiles>;
+ await act(async () => {
+ consuming = result.current.actions.consumeFiles([id], outputs, stubs);
+ });
+ vi.mocked(apiClient.post).mockResolvedValueOnce({
+ 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("Unlock"));
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([id]);
+ if (decision === "clear") {
+ await act(async () => {
+ await result.current.actions.clearAllFiles();
+ await consuming;
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ await expect(consuming).resolves.toEqual([]);
+ return;
+ }
+ await act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ await consuming;
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual(
+ expect.arrayContaining([id, outputs[0].fileId]),
+ );
+ expect(
+ result.current.selectors.getStirlingFileStub(outputs[0].fileId)
+ ?.sourceFileIds,
+ ).toEqual([id]);
+ await expect(consuming).resolves.toEqual([outputs[0].fileId]);
+ },
+ );
+});
afterEach(() => {
cleanup();
setPendingUnlocks([]);
});
describe("encrypted bytes opened by another editor", () => {
- it("holds policies before dispatch without opening a duplicate password modal", async () => {
- const { result } = renderHook(() => useFileActions(), { wrapper });
- await act(() =>
- result.current.actions.addFiles([new File(["encrypted"], "locked.pdf")], {
- selectFiles: false,
- skipAutomaticPasswordPrompt: true,
- }),
+ 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"]),
+ });
+ 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]);
+ });
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: "secret" },
+ });
+ 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" }],
+ });
+ expect(persist).toHaveBeenCalledWith(
+ [id],
+ [copy],
+ [expect.objectContaining({ parentFileId: id })],
+ );
+ expect(original.name).toBe("locked.pdf");
+ expect(original.size).toBe("encrypted original".length);
+ expect(getPdfAccess(copy)).toBeUndefined();
+ expect(getPdfAccess(original)).toBeUndefined();
+ 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 () => {
+ 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"),
+ ]);
+ });
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: "wrong" },
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Remove Password"));
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ expect(isAwaitingUnlock(id)).toBe(true);
+ expect(persist).not.toHaveBeenCalled();
+ await act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ });
+ await expect(loading).resolves.toEqual([]);
+ persist.mockRestore();
+ });
+
+ it("cancelling while persistence finishes does not return a file to the caller", async () => {
+ let finishWrite!: () => void;
+ observed.afterDispatch = () =>
+ new Promise<void>((resolve) => {
+ finishWrite = resolve;
+ });
+ 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 act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ });
+ await act(async () => {
+ finishWrite();
+ await loading;
+ });
+ await expect(loading).resolves.toEqual([]);
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ });
+ it("unlocks the original in place without adding a password-removal version", async () => {
+ vi.mocked(apiClient.post).mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ },
+ });
+ 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]);
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ expect(result.current.selectors.getFile(id)).toBeUndefined();
+ expect(result.current.selectors.getFiles([id])).toEqual([]);
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: " secret " },
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Unlock"));
+ });
+ await expect(loading).resolves.toEqual([original]);
+ expect(result.current.selectors.getFile(id)).toBe(original);
+ expect(result.current.selectors.getStirlingFileStub(id)).toMatchObject({
+ id,
+ versionNumber: 1,
+ isLeaf: true,
+ processedFile: { isEncrypted: true },
+ });
+ expect(getPdfAccess(id)?.password).toBe(" secret ");
+ expect(isAwaitingUnlock(id)).toBe(false);
+ expect(vi.mocked(apiClient.post).mock.calls.at(-1)?.[0]).toBe(
+ "/api/v1/security/inspect-pdf-security",
+ );
+ await act(() => result.current.actions.removeFiles([id]));
+ expect(getPdfAccess(original)).toBeUndefined();
+ });
+
+ it("cancel keeps protected bytes out of context and settles the loading action", async () => {
+ 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"),
+ ]);
+ });
expect(observed.heldBeforeEffects).toBe(true);
expect(isAwaitingUnlock(id)).toBe(true);
- expect(screen.queryByText("Skip unlock")).toBeNull();
+ expect(screen.getByText("Cancel opening")).toBeVisible();
+ await act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ });
+ await expect(loading).resolves.toEqual([]);
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ expect(result.current.selectors.getFile(id)).toBeUndefined();
+ expect(isAwaitingUnlock(id)).toBe(false);
+ });
- act(() => result.current.actions.openEncryptedUnlockPrompt(id));
- expect(screen.getByText("Skip unlock")).toBeVisible();
+ it("clearing the workspace cancels pending admissions", async () => {
+ const { result } = renderHook(() => useFileActions(), { wrapper });
+ let loading!: ReturnType<typeof result.current.actions.addFiles>;
+ await act(async () => {
+ loading = result.current.actions.addFiles([
+ new File(["encrypted"], "locked.pdf"),
+ ]);
+ });
expect(isAwaitingUnlock(id)).toBe(true);
- fireEvent.click(screen.getByText("Skip unlock"));
+ await act(async () => {
+ await result.current.actions.clearAllFiles();
+ });
expect(isAwaitingUnlock(id)).toBe(false);
+ await expect(loading).resolves.toEqual([]);
});
- it.each(["decrypt", "remove"])(
- "releases the hold after %s",
- async (action) => {
- const { result } = renderHook(() => useFileActions(), { wrapper });
- await act(() =>
- result.current.actions.addFiles(
- [new File(["encrypted"], "locked.pdf")],
- {
- selectFiles: false,
- skipAutomaticPasswordPrompt: true,
- },
- ),
- );
- expect(isAwaitingUnlock(id)).toBe(true);
- await act(async () => {
- if (action === "decrypt") {
- result.current.actions.updateStirlingFileStub(id, {
- processedFile: { pages: [], isEncrypted: false },
- });
- } else {
- await result.current.actions.clearAllFiles();
- }
- });
- expect(isAwaitingUnlock(id)).toBe(false);
+ it("a rejected password leaves the file pending until cancelled", async () => {
+ vi.mocked(apiClient.post).mockRejectedValueOnce(new Error("bad 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"),
+ ]);
+ });
+ fireEvent.change(screen.getByLabelText("PDF password"), {
+ target: { value: "wrong" },
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Unlock"));
+ });
+ await waitFor(() =>
+ expect(screen.getByText("Cancel opening")).toBeVisible(),
+ );
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ expect(getPdfAccess(id)).toBeUndefined();
+ await act(async () => {
+ fireEvent.click(screen.getByText("Cancel opening"));
+ });
+ await expect(loading).resolves.toEqual([]);
+ });
+});
+
+describe("preview session credentials", () => {
+ const previewSecurity = {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: 0,
+ canModify: false,
+ canAssemble: false,
+ pageCount: 1,
+ };
+ afterEach(cleanup);
+
+ it("unlocks without publishing or persisting a file, then forgets access on close", async () => {
+ vi.mocked(apiClient.post).mockResolvedValueOnce({ data: previewSecurity });
+ const { result } = renderHook(
+ () => ({ ...useFileActions(), selectors: useFileSelectors() }),
+ { wrapper },
+ );
+ const preview = new File(["protected"], "preview.pdf");
+ const lifetime = new AbortController();
+ await act(() =>
+ result.current.actions.unlockPreviewPdf(
+ preview,
+ " secret ",
+ lifetime.signal,
+ ),
+ );
+ expect(getPdfAccess(preview)).toEqual({
+ ...previewSecurity,
+ password: " secret ",
+ });
+ expect(result.current.selectors.getAllFileIds()).toEqual([]);
+ expect(result.current.selectors.getFiles()).toEqual([]);
+ act(() => lifetime.abort());
+ expect(getPdfAccess(preview)).toBeUndefined();
+ });
+
+ it("does not retain a password when authentication finishes after the preview closes", async () => {
+ let finish!: (response: { data: typeof previewSecurity }) => void;
+ vi.mocked(apiClient.post).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result } = renderHook(useFileActions, { wrapper });
+ const preview = new File(["protected"], "preview.pdf");
+ const lifetime = new AbortController();
+ const unlocking = result.current.actions.unlockPreviewPdf(
+ preview,
+ "secret",
+ lifetime.signal,
+ );
+ lifetime.abort();
+ await act(async () => {
+ finish({ data: previewSecurity });
+ await unlocking;
+ });
+ expect(getPdfAccess(preview)).toBeUndefined();
+ });
+});
+
+it("preserves a preview credential after its bytes are admitted to FileContext", async () => {
+ vi.mocked(apiClient.post).mockResolvedValueOnce({
+ data: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
},
+ });
+ const { result } = renderHook(useFileActions, { wrapper });
+ const preview = new File(["protected"], "preview.pdf");
+ const lifetime = new AbortController();
+ await act(() =>
+ result.current.actions.unlockPreviewPdf(preview, "secret", lifetime.signal),
);
+ const admitted = createStirlingFile(preview, id);
+ bindPdfAccess(admitted, id);
+ act(() => lifetime.abort());
+ expect(getPdfAccess(id)?.password).toBe("secret");
});
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index eff8600c9b..e57073bc2c 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -26,6 +26,7 @@ import {
FileContextSelectors,
FileContextActionsValue,
FileContextActions,
+ FileContextAction,
FileId,
StirlingFileStub,
StirlingFile,
@@ -65,18 +66,26 @@ 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 { buildRemovePasswordFormData } from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";
-import type { RemovePasswordParameters } from "@app/hooks/tools/removePassword/useRemovePasswordParameters";
-import { useResolutionContinuation } from "@app/hooks/tools/shared/useResolutionContinuation";
-import apiClient from "@app/services/apiClient";
+import { unlockPdfForSession } from "@app/services/pdfSessionUnlock";
+import {
+ bindPdfAccess,
+ clearPdfAccess,
+ forgetPdfAccess,
+ forgetPreviewPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
import { reportFilesRemoved } from "@app/services/failureReporting";
import {
addPendingUnlocks,
setPendingUnlocks,
} from "@app/services/pendingUnlocks";
-import { processResponse } from "@app/utils/toolResponseProcessor";
-import { ToolOperation } from "@app/types/file";
import { handlePasswordError } from "@app/utils/toolErrorHandler";
+import apiClient from "@app/services/apiClient";
+import {
+ buildRemovePasswordFormData,
+ REMOVE_PASSWORD_ENDPOINT,
+} from "@app/hooks/tools/removePassword/buildRemovePasswordFormData";
// Inner provider component that has access to IndexedDB
function FileContextInner({
@@ -118,7 +127,6 @@ function FileContextInner({
}
const lifecycleManager = lifecycleManagerRef.current;
const { t } = useTranslation();
- const continueResolutions = useResolutionContinuation();
const [encryptedQueue, setEncryptedQueue] = useState<FileId[]>([]);
const [activeEncryptedFileId, setActiveEncryptedFileId] =
@@ -126,9 +134,152 @@ function FileContextInner({
const [unlockPassword, setUnlockPassword] = useState("");
const [unlockError, setUnlockError] = useState<string | null>(null);
const [isUnlocking, setIsUnlocking] = useState(false);
- const dismissedEncryptedFilesRef = useRef<Set<FileId>>(new Set());
- const deferredEncryptedFilesRef = useRef<Set<FileId>>(new Set());
const observedFileIdsRef = useRef<Set<FileId>>(new Set());
+ const admissionResults = useRef(
+ new Map<FileId, Promise<boolean | StirlingFile>>(),
+ );
+ const pendingAdmissions = useRef(
+ new Map<
+ FileId,
+ {
+ stub: StirlingFileStub;
+ publishOnUnlock: boolean;
+ admitted: Promise<boolean | StirlingFile>;
+ resolve: (admitted: boolean | StirlingFile) => void;
+ }
+ >(),
+ );
+
+ const dispatchWithUnlock = useCallback((action: FileContextAction) => {
+ if (
+ action.type !== "ADD_FILES" &&
+ action.type !== "CONSUME_FILES" &&
+ action.type !== "UNDO_CONSUME_FILES"
+ ) {
+ dispatch(action);
+ return;
+ }
+ const ready: StirlingFileStub[] = [];
+ const locked: FileId[] = [];
+ const stubs =
+ action.type === "ADD_FILES"
+ ? action.payload.stirlingFileStubs
+ : action.type === "CONSUME_FILES"
+ ? action.payload.outputStirlingFileStubs
+ : action.payload.inputStirlingFileStubs;
+ for (const stub of stubs) {
+ if (!stub.processedFile?.isEncrypted || getPdfAccess(stub.id)) {
+ ready.push(stub);
+ continue;
+ }
+ if (pendingAdmissions.current.has(stub.id)) continue;
+ let resolve!: (admitted: boolean | StirlingFile) => void;
+ const admitted = new Promise<boolean | StirlingFile>((settle) => {
+ resolve = settle;
+ });
+ pendingAdmissions.current.set(stub.id, {
+ stub,
+ publishOnUnlock: action.type !== "CONSUME_FILES",
+ admitted,
+ resolve,
+ });
+ admissionResults.current.set(stub.id, admitted);
+ locked.push(stub.id);
+ }
+ if (locked.length) {
+ addPendingUnlocks(locked);
+ setEncryptedQueue((queue) => [...queue, ...locked]);
+ }
+ if (
+ action.type === "CONSUME_FILES" &&
+ stubs.some((stub) => pendingAdmissions.current.has(stub.id))
+ ) {
+ const sourceFileIds = Array.from(
+ new Set(
+ action.payload.inputFileIds.flatMap((id) => [
+ id,
+ ...(stateRef.current.files.byId[id]?.sourceFileIds ?? []),
+ ]),
+ ),
+ );
+ // A replacement is atomic: cancelling any output keeps the inputs available.
+ void Promise.all(
+ stubs.map(async (stub) => {
+ const pending = pendingAdmissions.current.get(stub.id);
+ const result = pending ? await pending.admitted : true;
+ const admittedStub = pending?.stub ?? stub;
+ return result !== false && filesRef.current.has(admittedStub.id)
+ ? admittedStub
+ : null;
+ }),
+ ).then((results) => {
+ const admitted = results.filter(
+ (stub): stub is StirlingFileStub =>
+ stub !== null && filesRef.current.has(stub.id),
+ );
+ if (admitted.length === results.length) {
+ dispatch({
+ ...action,
+ payload: { ...action.payload, outputStirlingFileStubs: admitted },
+ });
+ } else if (admitted.length) {
+ dispatch({
+ type: "ADD_FILES",
+ payload: {
+ stirlingFileStubs: admitted.map((stub) => ({
+ ...stub,
+ derivedFromTool: true,
+ sourceFileIds,
+ })),
+ },
+ });
+ }
+ });
+ return;
+ }
+ if (action.type === "UNDO_CONSUME_FILES") {
+ dispatch({
+ ...action,
+ payload: { ...action.payload, inputStirlingFileStubs: ready },
+ });
+ } else if (action.type === "CONSUME_FILES") {
+ dispatch({
+ ...action,
+ payload: { ...action.payload, outputStirlingFileStubs: ready },
+ });
+ } else if (ready.length)
+ dispatch({
+ ...action,
+ payload: { ...action.payload, stirlingFileStubs: ready },
+ });
+ }, []);
+
+ const awaitAdmissions = useCallback(async (files: StirlingFile[]) => {
+ const admitted = await Promise.all(
+ files.map(async (file) => {
+ const admitted = admissionResults.current.get(file.fileId);
+ const result = admitted ? await admitted : true;
+ admissionResults.current.delete(file.fileId);
+ return result === true ? file : result === false ? null : result;
+ }),
+ );
+ return admitted.filter(
+ (file): file is StirlingFile =>
+ file !== null && filesRef.current.get(file.fileId) === file,
+ );
+ }, []);
+
+ const cancelPendingAdmissions = useCallback((ids: readonly FileId[]) => {
+ for (const id of ids) {
+ const pending = pendingAdmissions.current.get(id);
+ if (!pending) continue;
+ pendingAdmissions.current.delete(id);
+ filesRef.current.delete(id);
+ pending.resolve(false);
+ }
+ setEncryptedQueue((queue) => queue.filter((id) => !ids.includes(id)));
+ setActiveEncryptedFileId((id) => (id && ids.includes(id) ? null : id));
+ }, []);
const enqueueEncryptedFiles = useCallback(
(fileIds: FileId[]) => {
@@ -137,8 +288,6 @@ function FileContextInner({
const existing = new Set(prevQueue);
const next = [...prevQueue];
for (const id of fileIds) {
- if (dismissedEncryptedFilesRef.current.has(id)) continue;
- if (deferredEncryptedFilesRef.current.has(id)) continue;
if (id === activeEncryptedFileId) continue;
if (existing.has(id)) continue;
existing.add(id);
@@ -160,7 +309,8 @@ function FileContextInner({
const stub = state.files.byId[id];
if (
(stub?.versionNumber ?? 1) <= 1 &&
- stub?.processedFile?.isEncrypted
+ stub?.processedFile?.isEncrypted &&
+ !getPdfAccess(id)
) {
newEncryptedIds.push(id);
}
@@ -184,25 +334,19 @@ function FileContextInner({
useEffect(() => {
if (
activeEncryptedFileId &&
- !state.files.ids.includes(activeEncryptedFileId)
+ !state.files.ids.includes(activeEncryptedFileId) &&
+ !pendingAdmissions.current.has(activeEncryptedFileId)
) {
setActiveEncryptedFileId(null);
}
}, [activeEncryptedFileId, state.files.ids]);
- // Published so an upload policy holds off until the user has answered the prompt: running now
- // would fail on a document they are about to decrypt, and leave a row about a version that no
- // longer exists once they have.
+ // Upload policies wait for the prompt to settle; interactive credentials are not passed to automation.
useEffect(() => {
- const deferred = deferredEncryptedFilesRef.current;
- for (const id of deferred) {
- if (!state.files.byId[id]?.processedFile?.isEncrypted)
- deferred.delete(id);
- }
setPendingUnlocks([
...(activeEncryptedFileId ? [activeEncryptedFileId] : []),
...encryptedQueue,
- ...deferred,
+ ...pendingAdmissions.current.keys(),
]);
}, [activeEncryptedFileId, encryptedQueue, state.files.byId]);
@@ -232,20 +376,40 @@ function FileContextInner({
const handleUnlockSkip = useCallback(() => {
if (activeEncryptedFileId) {
- dismissedEncryptedFilesRef.current.add(activeEncryptedFileId);
+ const pending = pendingAdmissions.current.get(activeEncryptedFileId);
+ if (pending) {
+ pendingAdmissions.current.delete(activeEncryptedFileId);
+ filesRef.current.delete(activeEncryptedFileId);
+ forgetPdfAccess([activeEncryptedFileId]);
+ pending.resolve(false);
+ } else {
+ lifecycleManager.removeFiles([activeEncryptedFileId], stateRef);
+ }
}
setActiveEncryptedFileId(null);
- }, [activeEncryptedFileId]);
+ }, [activeEncryptedFileId, lifecycleManager]);
const promptEncryptedUnlock = useCallback((fileId: FileId) => {
- const stub = stateRef.current.files.byId[fileId];
- if (!stub?.processedFile?.isEncrypted) {
- return;
+ const stub =
+ pendingAdmissions.current.get(fileId)?.stub ??
+ stateRef.current.files.byId[fileId];
+ if (!stub) return;
+ if (!stub.processedFile?.isEncrypted) {
+ dispatch({
+ type: "UPDATE_FILE_RECORD",
+ payload: {
+ id: fileId,
+ updates: {
+ processedFile: {
+ ...stub.processedFile,
+ pages: stub.processedFile?.pages ?? [],
+ isEncrypted: true,
+ },
+ },
+ },
+ });
}
- dismissedEncryptedFilesRef.current.delete(fileId);
- deferredEncryptedFilesRef.current.delete(fileId);
-
setEncryptedQueue((prevQueue) => prevQueue.filter((id) => id !== fileId));
setActiveEncryptedFileId((currentActiveId) => {
@@ -304,8 +468,6 @@ function FileContextInner({
};
/** Bytes and stub only, no thumbnail parse (see AddFileOptions). */
skipMetadataHydration?: boolean;
- /** An editor owns the prompt; encrypted library bytes still hold policies. */
- skipAutomaticPasswordPrompt?: boolean;
},
): Promise<StirlingFile[]> => {
const stirlingFiles = await addFiles(
@@ -320,37 +482,25 @@ function FileContextInner({
},
stateRef,
filesRef,
- (action) => {
- if (
- options?.skipAutomaticPasswordPrompt &&
- action.type === "ADD_FILES"
- ) {
- const encrypted = action.payload.stirlingFileStubs.filter(
- (stub) => stub.processedFile?.isEncrypted,
- );
- for (const stub of encrypted) {
- deferredEncryptedFilesRef.current.add(stub.id);
- }
- // Policies can observe the new records before this provider's effects run.
- addPendingUnlocks(encrypted.map((stub) => stub.id));
- }
- dispatch(action);
- },
+ dispatchWithUnlock,
lifecycleManager,
enablePersistence,
);
- // Auto-select the newly added files if requested
- if (options?.selectFiles && stirlingFiles.length > 0) {
- selectFiles(stirlingFiles);
- }
if (stirlingFiles.length > 0) {
indexedDB?.bumpRevision?.();
}
-
- return stirlingFiles;
+ const admitted = await awaitAdmissions(stirlingFiles);
+ if (options?.selectFiles && admitted.length > 0) selectFiles(admitted);
+ return admitted;
},
- [enablePersistence, requestConfirmation, indexedDB],
+ [
+ enablePersistence,
+ requestConfirmation,
+ indexedDB,
+ dispatchWithUnlock,
+ awaitAdmissions,
+ ],
);
const addFilesWithOptions = useCallback(
@@ -377,22 +527,19 @@ function FileContextInner({
},
stateRef,
filesRef,
- dispatch,
+ dispatchWithUnlock,
lifecycleManager,
enablePersistence,
);
- if (options?.selectFiles && stirlingFiles.length > 0) {
- selectFiles(stirlingFiles);
- }
-
if (stirlingFiles.length > 0) {
indexedDB?.bumpRevision?.();
}
-
- return stirlingFiles;
+ const admitted = await awaitAdmissions(stirlingFiles);
+ if (options?.selectFiles && admitted.length > 0) selectFiles(admitted);
+ return admitted;
},
- [enablePersistence, indexedDB],
+ [enablePersistence, indexedDB, dispatchWithUnlock, awaitAdmissions],
);
const addStirlingFileStubsAction = useCallback(
@@ -406,18 +553,15 @@ function FileContextInner({
options,
stateRef,
filesRef,
- dispatch,
+ dispatchWithUnlock,
lifecycleManager,
);
- // Auto-select the newly added files if requested
- if (options?.selectFiles && result.length > 0) {
- selectFiles(result);
- }
-
- return result;
+ const admitted = await awaitAdmissions(result);
+ if (options?.selectFiles && admitted.length > 0) selectFiles(admitted);
+ return admitted;
},
- [],
+ [dispatchWithUnlock, awaitAdmissions],
);
const reconcileOpenFilesAction = useCallback(
@@ -427,7 +571,10 @@ function FileContextInner({
);
// Action creators
- const baseActions = useMemo(() => createFileActions(dispatch), []);
+ const baseActions = useMemo(
+ () => createFileActions(dispatchWithUnlock),
+ [dispatchWithUnlock],
+ );
// Helper functions for pinned files
const consumeFilesWrapper = useCallback(
@@ -437,22 +584,26 @@ function FileContextInner({
outputStirlingFileStubs: StirlingFileStub[],
options?: { silent?: boolean },
): Promise<FileId[]> => {
- return consumeFiles(
+ for (const file of outputStirlingFiles) bindPdfAccess(file, file.fileId);
+ await consumeFiles(
inputFileIds,
outputStirlingFiles,
outputStirlingFileStubs,
filesRef,
- dispatch,
+ dispatchWithUnlock,
options,
);
+ const admitted = await awaitAdmissions(outputStirlingFiles);
+ return admitted.map((file) => file.fileId);
},
- [],
+ [dispatchWithUnlock, awaitAdmissions],
);
- const runAutomaticPasswordRemoval = useCallback(
+ const runSessionUnlock = useCallback(
async (fileId: FileId, password: string): Promise<void> => {
const file = filesRef.current.get(fileId);
- const parentStub = stateRef.current.files.byId[fileId];
+ const pending = pendingAdmissions.current.get(fileId);
+ const parentStub = pending?.stub ?? stateRef.current.files.byId[fileId];
if (!file || !parentStub) {
throw new Error(
@@ -463,116 +614,186 @@ function FileContextInner({
);
}
- const params: RemovePasswordParameters = { password };
- const formData = buildRemovePasswordFormData(params, file);
+ const access = await unlockPdfForSession(file, password);
+ if (filesRef.current.get(fileId) !== file) {
+ return;
+ }
+ rememberPdfAccess(file, access);
+ bindPdfAccess(file, fileId);
+ const metadata = await generateProcessedFileMetadata(file);
+ if (filesRef.current.get(fileId) !== file) return;
+ const updates: Partial<StirlingFileStub> = {
+ processedFile: {
+ ...metadata,
+ pages: metadata?.pages ?? [],
+ totalPages: access.pageCount,
+ isEncrypted: access.encrypted,
+ },
+ thumbnailUrl: metadata?.thumbnailUrl,
+ };
+ if (pending) {
+ pending.stub = { ...parentStub, ...updates };
+ if (pending.publishOnUnlock)
+ dispatch({
+ type: "ADD_FILES",
+ payload: { stirlingFileStubs: [pending.stub] },
+ });
+ } else {
+ dispatch({
+ type: "UPDATE_FILE_RECORD",
+ payload: { id: fileId, updates },
+ });
+ }
+ pendingAdmissions.current.delete(fileId);
+ pending?.resolve(true);
+ },
+ [t],
+ );
- const response = await apiClient.post(
- "/api/v1/security/remove-password",
- formData,
+ const runPasswordRemoval = useCallback(
+ async (fileId: FileId, password: string): Promise<void> => {
+ const file = filesRef.current.get(fileId);
+ const pending = pendingAdmissions.current.get(fileId);
+ const sourceStub = pending?.stub ?? stateRef.current.files.byId[fileId];
+ if (!file || !sourceStub) {
+ throw new Error(
+ t(
+ "encryptedPdfUnlock.missingFile",
+ "The selected file is no longer available.",
+ ),
+ );
+ }
+ const response = await apiClient.post<Blob>(
+ REMOVE_PASSWORD_ENDPOINT,
+ buildRemovePasswordFormData({ password }, file),
{
responseType: "blob",
- suppressErrorToast: true, // Handle errors in modal UI instead of toast
+ suppressErrorToast: true,
},
);
- const responseFiles = await processResponse(response.data, [file]);
-
- const unlockedFile = responseFiles[0];
- if (!unlockedFile) {
+ 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);
+ if (filesRef.current.get(fileId) !== file) return;
+ if (metadata?.isEncrypted) {
throw new Error(
t(
- "encryptedPdfUnlock.emptyResponse",
- "Password removal did not produce a file.",
+ "removePassword.error.failed",
+ "An error occurred while removing the password from the PDF.",
),
);
}
-
- const processedMetadata =
- await generateProcessedFileMetadata(unlockedFile);
- const thumbnail = processedMetadata?.thumbnailUrl;
-
- const operation: ToolOperation = {
- toolId: "removePassword",
- timestamp: Date.now(),
- };
-
- const childStub = createChildStub(
- parentStub,
- operation,
- unlockedFile,
- thumbnail,
- processedMetadata,
+ const stub = createChildStub(
+ sourceStub,
+ { toolId: "removePassword", timestamp: Date.now() },
+ copy,
+ metadata?.thumbnailUrl,
+ metadata,
);
- const stirlingUnlockedFile = createStirlingFile(
- unlockedFile,
- childStub.id,
+ // An explicit copy must not inherit a save target that could overwrite the protected source.
+ stub.localFilePath = undefined;
+ stub.isDirty = undefined;
+ stub.diskSyncedSize = undefined;
+ stub.diskSyncedModifiedMs = undefined;
+ stub.blobUrl = undefined;
+ const output = createStirlingFile(copy, stub.id);
+ await consumeFiles(
+ [fileId],
+ [output],
+ [stub],
+ filesRef,
+ pending && !pending.publishOnUnlock ? () => {} : dispatchWithUnlock,
);
-
- await consumeFilesWrapper([fileId], [stirlingUnlockedFile], [childStub]);
-
- // The modal is the remove-password tool by another door, so it resolves the same.
- continueResolutions({
- operation: "removePassword",
- inputFileIds: [fileId],
- outputs: [
- { file: unlockedFile, fileId: childStub.id, sourceFileId: fileId },
- ],
- });
+ if (pending) pending.stub = stub;
+ pendingAdmissions.current.delete(fileId);
+ pending?.resolve(output);
+ indexedDB?.bumpRevision?.();
},
- [consumeFilesWrapper, continueResolutions, t],
+ [t, dispatchWithUnlock, indexedDB],
);
- const handleUnlockSubmit = useCallback(async () => {
- if (!activeEncryptedFileId) return;
- if (!unlockPassword.trim()) {
- setUnlockError(
- t("encryptedPdfUnlock.required", "Enter the password to continue."),
- );
- return;
- }
+ const handleUnlockSubmit = useCallback(
+ async (removePassword = false) => {
+ if (!activeEncryptedFileId || isUnlocking) return;
+ if (unlockPassword.length === 0) {
+ setUnlockError(
+ t("encryptedPdfUnlock.required", "Enter the password to continue."),
+ );
+ return;
+ }
- setIsUnlocking(true);
- setUnlockError(null);
- try {
- await runAutomaticPasswordRemoval(
- activeEncryptedFileId,
- unlockPassword.trim(),
- );
- const fileName = stateRef.current.files.byId[activeEncryptedFileId]?.name;
- alert({
- alertType: "success",
- title: t("encryptedPdfUnlock.successTitle", "Password removed"),
- body: fileName
- ? t("encryptedPdfUnlock.successBodyWithName", {
- defaultValue: "Removed password from {{fileName}}",
- fileName,
- })
- : t(
- "encryptedPdfUnlock.successBody",
- "Password removed successfully.",
- ),
- expandable: false,
- isPersistentPopup: false,
- });
- dismissedEncryptedFilesRef.current.delete(activeEncryptedFileId);
- setActiveEncryptedFileId(null);
- } catch (error) {
- const errorMessage = await handlePasswordError(
- error,
- t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),
- t(
- "removePassword.error.failed",
- "An error occurred while removing the password from the PDF.",
- ),
- );
- setUnlockError(errorMessage);
- } finally {
- setIsUnlocking(false);
- }
- }, [activeEncryptedFileId, unlockPassword, runAutomaticPasswordRemoval, t]);
+ setIsUnlocking(true);
+ setUnlockError(null);
+ try {
+ if (removePassword) {
+ await runPasswordRemoval(activeEncryptedFileId, unlockPassword);
+ } else {
+ await runSessionUnlock(activeEncryptedFileId, unlockPassword);
+ }
+ const fileName =
+ stateRef.current.files.byId[activeEncryptedFileId]?.name;
+ alert({
+ alertType: "success",
+ title: removePassword
+ ? t("encryptedPdfUnlock.copyCreated", "Unprotected copy created")
+ : t("encryptedPdfUnlock.sessionSuccessTitle", "PDF unlocked"),
+ body: removePassword
+ ? t(
+ "encryptedPdfUnlock.originalProtected",
+ "The original PDF stays protected.",
+ )
+ : 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.",
+ ),
+ 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,
+ ],
+ );
const handleUnlockAll = useCallback(async () => {
if (!activeEncryptedFileId) return;
- const pw = unlockPassword.trim();
+ const pw = unlockPassword;
if (!pw) {
setUnlockError(
t("encryptedPdfUnlock.required", "Enter the password to continue."),
@@ -589,8 +810,7 @@ function FileContextInner({
for (const fileId of allIds) {
try {
- await runAutomaticPasswordRemoval(fileId, pw);
- dismissedEncryptedFilesRef.current.delete(fileId);
+ await runSessionUnlock(fileId, pw);
successCount++;
} catch {
failedIds.push(fileId);
@@ -600,7 +820,7 @@ function FileContextInner({
if (successCount > 0) {
alert({
alertType: "success",
- title: t("encryptedPdfUnlock.successTitle", "Password removed"),
+ title: t("encryptedPdfUnlock.sessionSuccessTitle", "PDF unlocked"),
body: t("encryptedPdfUnlock.unlockAllSuccess", {
defaultValue: "Unlocked {{count}} file(s).",
count: successCount,
@@ -632,7 +852,7 @@ function FileContextInner({
activeEncryptedFileId,
encryptedQueue,
unlockPassword,
- runAutomaticPasswordRemoval,
+ runSessionUnlock,
t,
]);
@@ -647,11 +867,11 @@ function FileContextInner({
inputStirlingFileStubs,
outputFileIds,
filesRef,
- dispatch,
+ dispatchWithUnlock,
indexedDB,
);
},
- [indexedDB],
+ [indexedDB, dispatchWithUnlock],
);
// File pinning functions - use StirlingFile directly
@@ -669,6 +889,21 @@ function FileContextInner({
[baseActions],
);
+ const unlockPreviewPdf = useCallback<FileContextActions["unlockPreviewPdf"]>(
+ async (file, password, signal) => {
+ if (signal.aborted) return;
+ const access = await unlockPdfForSession(file, password);
+ if (signal.aborted) return;
+ rememberPdfAccess(file, access);
+ signal.addEventListener(
+ "abort",
+ () => forgetPreviewPdfAccess(file, access),
+ { once: true },
+ );
+ },
+ [],
+ );
+
// Complete actions object
const actions = useMemo<FileContextActions>(
() => ({
@@ -678,6 +913,8 @@ function FileContextInner({
addStirlingFileStubs: addStirlingFileStubsAction,
reconcileOpenFiles: reconcileOpenFilesAction,
removeFiles: async (fileIds: FileId[], deleteFromStorage?: boolean) => {
+ cancelPendingAdmissions(fileIds);
+ forgetPdfAccess(fileIds);
// Remove from memory and cleanup resources
lifecycleManager.removeFiles(fileIds, stateRef);
@@ -704,6 +941,8 @@ function FileContextInner({
dispatch({ type: "REORDER_FILES", payload: { orderedFileIds } });
},
clearAllFiles: async () => {
+ cancelPendingAdmissions([...pendingAdmissions.current.keys()]);
+ clearPdfAccess();
lifecycleManager.cleanupAllFiles();
filesRef.current.clear();
dispatch({ type: "RESET_CONTEXT" });
@@ -712,6 +951,8 @@ function FileContextInner({
// IndexedDB should only be cleared when explicitly requested by user
},
clearAllData: async () => {
+ cancelPendingAdmissions([...pendingAdmissions.current.keys()]);
+ clearPdfAccess();
// First clear all files from memory
lifecycleManager.cleanupAllFiles();
filesRef.current.clear();
@@ -738,6 +979,7 @@ function FileContextInner({
scheduleCleanup: (fileId: FileId, delay?: number) =>
lifecycleManager.scheduleCleanup(fileId, delay, stateRef),
openEncryptedUnlockPrompt: promptEncryptedUnlock,
+ unlockPreviewPdf,
}),
[
baseActions,
@@ -753,6 +995,8 @@ function FileContextInner({
indexedDB,
enablePersistence,
promptEncryptedUnlock,
+ unlockPreviewPdf,
+ cancelPendingAdmissions,
],
);
@@ -782,13 +1026,14 @@ function FileContextInner({
const actionsValue = useMemo<FileContextActionsValue>(
() => ({
actions,
- dispatch,
+ dispatch: dispatchWithUnlock,
}),
- [actions],
+ [actions, dispatchWithUnlock],
);
const activeEncryptedStub = activeEncryptedFileId
- ? state.files.byId[activeEncryptedFileId]
+ ? (pendingAdmissions.current.get(activeEncryptedFileId)?.stub ??
+ state.files.byId[activeEncryptedFileId])
: undefined;
const isUnlockModalOpen = Boolean(
activeEncryptedFileId && activeEncryptedStub,
@@ -808,7 +1053,13 @@ function FileContextInner({
mountedRef.current = false;
// StrictMode can replay effects after files hydrate; only an actual unmount owns cleanup.
queueMicrotask(() => {
- if (!mountedRef.current) lifecycleManager.destroy();
+ if (!mountedRef.current) {
+ for (const pending of pendingAdmissions.current.values())
+ pending.resolve(false);
+ pendingAdmissions.current.clear();
+ clearPdfAccess();
+ lifecycleManager.destroy();
+ }
});
};
}, [lifecycleManager]);
@@ -825,6 +1076,7 @@ function FileContextInner({
zipFileName={confirmationState.fileName}
/>
<EncryptedPdfUnlockModal
+ sessionUnlock
opened={isUnlockModalOpen}
fileName={activeEncryptedStub?.name}
password={unlockPassword}
@@ -832,7 +1084,8 @@ function FileContextInner({
isProcessing={isUnlocking}
remainingCount={encryptedQueue.length}
onPasswordChange={setUnlockPassword}
- onUnlock={handleUnlockSubmit}
+ onUnlock={() => void handleUnlockSubmit()}
+ onRemovePassword={() => void handleUnlockSubmit(true)}
onUnlockAll={handleUnlockAll}
onSkip={handleUnlockSkip}
/>
diff --git a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
index 29d22a7900..43550f4cb8 100644
--- a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
+++ b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
@@ -7,6 +7,9 @@ import {
} from "@app/contexts/FilesModalContext";
import {
createNewStirlingFileStub,
+ createStirlingFile,
+ type FileId,
+ type StirlingFile,
type StirlingFileStub,
} from "@app/types/fileContext";
@@ -59,10 +62,34 @@ vi.mock("@app/services/apiClient", () => ({ default: { get: state.apiGet } }));
beforeEach(() => {
vi.clearAllMocks();
+ state.addFiles.mockImplementation(async (files: File[]) =>
+ files.map((file) => createStirlingFile(file, "uploaded" as FileId)),
+ );
+ state.addStirlingFileStubs.mockImplementation(
+ async (stubs: StirlingFileStub[]) =>
+ stubs.map((stub) =>
+ createStirlingFile(new File(["stored"], stub.name), stub.id),
+ ),
+ );
state.workbench = "fileEditor";
});
describe("file picker caller contract", () => {
+ it("cancelled unlocks neither select a file nor navigate away", async () => {
+ state.addFiles.mockResolvedValueOnce([]);
+ state.addStirlingFileStubs.mockResolvedValueOnce([]);
+ const { result } = renderHook(useFilesModalContext, {
+ wrapper: FilesModalProvider,
+ });
+ await act(() =>
+ result.current.onRecentFileSelect(
+ [createNewStirlingFileStub(new File(["locked"], "Stored.pdf"))],
+ [new File(["locked"], "Upload.pdf")],
+ ),
+ );
+ expect(state.setSelectedFiles).toHaveBeenCalledWith(["already-open"]);
+ expect(state.setWorkbench).not.toHaveBeenCalled();
+ });
it("clears a caller's format and count restrictions when the next picker opens", () => {
const { result } = renderHook(useFilesModalContext, {
wrapper: FilesModalProvider,
@@ -307,8 +334,8 @@ describe("file picker caller contract", () => {
it("does not close a reopened picker when a previous import finishes", async () => {
let finishImport!: () => void;
state.addFiles.mockReturnValueOnce(
- new Promise<void>((resolve) => {
- finishImport = resolve;
+ new Promise<StirlingFile[]>((resolve) => {
+ finishImport = () => resolve([]);
}),
);
const { result } = renderHook(useFilesModalContext, {
@@ -336,8 +363,8 @@ describe("file picker caller contract", () => {
it("closes a direct upload immediately and leaves a subsequently opened picker alone", async () => {
let finishImport!: () => void;
state.addFiles.mockReturnValueOnce(
- new Promise<void>((resolve) => {
- finishImport = resolve;
+ new Promise<StirlingFile[]>((resolve) => {
+ finishImport = () => resolve([]);
}),
);
const { result } = renderHook(useFilesModalContext, {
diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsx
index 7e9b8d2987..1f7eb8117e 100644
--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx
@@ -280,7 +280,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
reportUnavailable();
return;
}
- if (uploads.length > 0) await addFiles(uploads);
+ const uploadedFiles = uploads.length > 0 ? await addFiles(uploads) : [];
const localStubs: StirlingFileStub[] = [];
const requestedIds: FileId[] = [];
@@ -289,7 +289,6 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
const remote = await downloadRemoteFile(stub);
if (!remote) {
localStubs.push(stub);
- requestedIds.push(stub.id);
continue;
}
const importedIds = await importBundleToWorkbench(
@@ -310,12 +309,14 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
}
}
- if (localStubs.length)
- await actions.addStirlingFileStubs(localStubs, { selectFiles: false });
+ if (localStubs.length) {
+ const admitted = await actions.addStirlingFileStubs(localStubs, {
+ selectFiles: false,
+ });
+ requestedIds.push(...admitted.map((file) => file.fileId));
+ }
// Adding an input must preserve a tool's existing selection.
- const uploadedIds = uploads
- .map((file) => fileCtx.findFileId(file))
- .filter((id): id is FileId => Boolean(id));
+ const uploadedIds = uploadedFiles.map((file) => file.fileId);
const currentSelected = fileCtx.selectors
.getSelectedStirlingFileStubs()
.map((s) => s.id);
@@ -325,7 +326,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
),
);
- const totalAdded = requestedIds.length + uploads.length;
+ const totalAdded = requestedIds.length + uploadedIds.length;
if (!staysOnAdd && totalAdded > 0) {
navActions.setWorkbench(totalAdded === 1 ? "viewer" : "fileEditor");
}
diff --git a/frontend/editor/src/core/contexts/IndexedDBContext.tsx b/frontend/editor/src/core/contexts/IndexedDBContext.tsx
index 5dc8f78bcd..ec25482889 100644
--- a/frontend/editor/src/core/contexts/IndexedDBContext.tsx
+++ b/frontend/editor/src/core/contexts/IndexedDBContext.tsx
@@ -49,7 +49,11 @@ interface IndexedDBContextValue {
available: number;
fileCount: number;
}>;
- updateThumbnail: (fileId: FileId, thumbnail: string) => Promise<boolean>;
+ updateThumbnail: (
+ fileId: FileId,
+ thumbnail: string,
+ isEncrypted?: boolean,
+ ) => Promise<boolean>;
markFileAsProcessed: (fileId: FileId) => Promise<boolean>;
// Folder operations
@@ -242,8 +246,16 @@ export function IndexedDBProvider({ children }: IndexedDBProviderProps) {
}, []);
const updateThumbnail = useCallback(
- async (fileId: FileId, thumbnail: string): Promise<boolean> => {
- const result = await fileStorage.updateThumbnail(fileId, thumbnail);
+ async (
+ fileId: FileId,
+ thumbnail: string,
+ isEncrypted?: boolean,
+ ): Promise<boolean> => {
+ const result = await fileStorage.updateThumbnail(
+ fileId,
+ thumbnail,
+ isEncrypted,
+ );
if (result) bumpRevision();
return result;
},
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 55a0ca9d96..cf7fd15080 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -2,6 +2,7 @@
* File actions - Unified file operations with single addFiles helper
*/
+import { bindPdfAccess, getPdfAccess } from "@app/services/pdfPasswordStore";
import {
StirlingFileStub,
FileContextAction,
@@ -159,9 +160,11 @@ export async function generateProcessedFileMetadata(
// Use rotated thumbnail for file manager
processedFile.thumbnailUrl = rotatedResult.thumbnail;
- if (unrotatedResult.isEncrypted || rotatedResult.isEncrypted) {
- processedFile.isEncrypted = true;
- }
+ processedFile.isEncrypted = Boolean(
+ getPdfAccess(file)?.encrypted ||
+ unrotatedResult.isEncrypted ||
+ rotatedResult.isEncrypted,
+ );
return processedFile;
} catch (error) {
@@ -495,12 +498,12 @@ export async function addFiles(
// Early encryption detection for PDFs — set the flag before dispatch so the
// viewer gate and modal queue pick it up immediately instead of after hydration
- if (file.type === "application/pdf") {
+ if (file.type === "application/pdf" || /\.pdf$/i.test(file.name)) {
try {
- if (await FileAnalyzer.isPDFUserPasswordProtected(file)) {
- fileStub.processedFile = fileStub.processedFile || { pages: [] };
- fileStub.processedFile.isEncrypted = true;
- }
+ fileStub.processedFile = {
+ pages: [],
+ isEncrypted: await FileAnalyzer.isPDFUserPasswordProtected(file),
+ };
} catch (error) {
// Never block upload on analysis failure — but log so it's debuggable
// if an unencrypted file later appears to "hang" during processing.
@@ -539,7 +542,10 @@ export async function addFiles(
let thumbnail: string | undefined;
if (targetFile.type.startsWith("application/pdf")) {
- if (fileStub.processedFile?.isEncrypted) {
+ if (
+ fileStub.processedFile?.isEncrypted &&
+ !getPdfAccess(targetFile)
+ ) {
// Pre-dispatch detection already flagged this PDF as encrypted; PDF.js
// can't produce thumbnails/metadata without the password, so re-parsing
// here would just duplicate work. Metadata is refreshed after unlock.
@@ -921,7 +927,7 @@ export async function addStirlingFileStubs(
});
}
- const loadedFiles: StirlingFile[] = [];
+ const loads: Promise<StirlingFile | undefined>[] = [];
let firstFileDispatched = false;
// Process and dispatch files one by one for progressive UI updates
@@ -930,6 +936,9 @@ export async function addStirlingFileStubs(
// name|size|lastModified (and therefore quickKey), so quickKey dedup
// here would silently drop a legitimately different file.
if (stateRef.current.files.byId[stub.id]) {
+ const existing = filesRef.current.get(stub.id);
+ if (existing)
+ loads.push(Promise.resolve(createStirlingFile(existing, stub.id)));
if (DEBUG)
console.log(
`📄 Skipping already-loaded StirlingFileStub: ${stub.name}`,
@@ -945,9 +954,6 @@ export async function addStirlingFileStubs(
record.insertAfterPageId = options.insertAfterPageId;
}
- // Dispatch each file immediately as we process it (progressive loading)
- dispatch({ type: "ADD_FILES", payload: { stirlingFileStubs: [record] } });
-
// Clear loading indicator after first file appears
if (!firstFileDispatched) {
firstFileDispatched = true;
@@ -965,71 +971,91 @@ export async function addStirlingFileStubs(
// Load and publish the File, ahead of any parsing. NOT queued: whether a
// file opens at all must not wait on other files' parses.
- void (async () => {
- // A storage read that never settles renders as a file that silently won't
- // open. Name it in the console rather than leaving the user guessing.
- const stall = setTimeout(
- () =>
- console.error(
- `[Hydration] ${stub.name} (${fileId}) has been loading for ${STALLED_LOAD_MS / 1000}s - the IndexedDB read has not settled`,
- ),
- STALLED_LOAD_MS,
- );
- // A record can be a cache of something outside the app, so settle it
- // BEFORE serving it, or an edit made out there stays invisible and a
- // file deleted out there still opens.
- const port = reconcilePort(stateRef, filesRef, lifecycleManager);
- const decision = await reconcileBeforeOpen(stub, port);
- if (decision.drop) {
- lifecycleManager.removeFiles([fileId], stateRef);
- clearTimeout(stall);
- return;
- }
- // Bytes the reconciler holds win over the stored copy.
- const stirlingFile = await (
- decision.file
- ? Promise.resolve(createStirlingFile(decision.file, fileId))
- : fileStorage.getStirlingFile(fileId)
- ).finally(() => clearTimeout(stall));
- if (!stirlingFile) {
- // A row with no bytes renders empty and its clicks look dead, so take it
- // back out. Storage keeps the record; fileStorage has said why.
- console.error(
- `[Hydration] No readable data for ${stub.name} (${fileId}); removing it from the workbench`,
+ loads.push(
+ (async () => {
+ // A storage read that never settles renders as a file that silently won't
+ // open. Name it in the console rather than leaving the user guessing.
+ const stall = setTimeout(
+ () =>
+ console.error(
+ `[Hydration] ${stub.name} (${fileId}) has been loading for ${STALLED_LOAD_MS / 1000}s - the IndexedDB read has not settled`,
+ ),
+ STALLED_LOAD_MS,
);
- lifecycleManager.removeFiles([fileId], stateRef);
- return;
- }
+ // A record can be a cache of something outside the app, so settle it
+ // BEFORE serving it, or an edit made out there stays invisible and a
+ // file deleted out there still opens.
+ const port = reconcilePort(stateRef, filesRef, lifecycleManager);
+ const decision = await reconcileBeforeOpen(stub, port);
+ if (decision.drop) {
+ lifecycleManager.removeFiles([fileId], stateRef);
+ clearTimeout(stall);
+ return;
+ }
+ // Bytes the reconciler holds win over the stored copy.
+ const stirlingFile = await (
+ decision.file
+ ? Promise.resolve(createStirlingFile(decision.file, fileId))
+ : fileStorage.getStirlingFile(fileId)
+ ).finally(() => clearTimeout(stall));
+ if (!stirlingFile) {
+ // A row with no bytes renders empty and its clicks look dead, so take it
+ // back out. Storage keeps the record; fileStorage has said why.
+ console.error(
+ `[Hydration] No readable data for ${stub.name} (${fileId}); removing it from the workbench`,
+ );
+ lifecycleManager.removeFiles([fileId], stateRef);
+ return;
+ }
- filesRef.current.set(fileId, stirlingFile);
+ filesRef.current.set(fileId, stirlingFile);
+ bindPdfAccess(stirlingFile, fileId);
+ Object.assign(record, decision.updates);
+ if (
+ (stirlingFile.type === "application/pdf" ||
+ /\.pdf$/i.test(stirlingFile.name)) &&
+ (decision.contentReplaced ||
+ record.processedFile?.isEncrypted === undefined)
+ ) {
+ record.processedFile = {
+ pages: [],
+ isEncrypted:
+ await FileAnalyzer.isPDFUserPasswordProtected(stirlingFile),
+ };
+ }
+ dispatch({
+ type: "ADD_FILES",
+ payload: { stirlingFileStubs: [record] },
+ });
- // Workbench selectors only see the file once something dispatches, and
- // updateStirlingFileStub drops updates for a file not yet in filesRef,
- // so this must follow the write above - and must happen even when the
- // reconciler had nothing to say, or the bytes never become visible.
- lifecycleManager.updateStirlingFileStub(
- fileId,
- decision.updates ?? {},
- stateRef,
- );
- decision.afterPublish?.();
-
- const needsProcessing =
- // Bytes just changed underneath us, so whatever was cached is stale.
- decision.contentReplaced === true ||
- !stub.processedFile ||
- !stub.processedFile.pages ||
- stub.processedFile.pages.length === 0 ||
- stub.processedFile.totalPages !== stub.processedFile.pages.length;
- if (needsProcessing) {
- scheduleMetadataFor(stirlingFile);
- }
- })().catch((error) =>
- console.error(`[Hydration] Failed to load ${fileId}:`, error),
+ // Admission can defer the state record; source-link persistence still belongs to these loaded bytes.
+ if (decision.updates && Object.keys(decision.updates).length > 0)
+ lifecycleManager.updateStirlingFileStub(fileId, decision.updates);
+
+ decision.afterPublish?.();
+
+ const needsProcessing =
+ // Bytes just changed underneath us, so whatever was cached is stale.
+ decision.contentReplaced === true ||
+ !stub.processedFile ||
+ !stub.processedFile.pages ||
+ stub.processedFile.pages.length === 0 ||
+ stub.processedFile.totalPages !== stub.processedFile.pages.length;
+ if (needsProcessing) {
+ scheduleMetadataFor(stirlingFile);
+ }
+ return stirlingFile;
+ })().catch((error) => {
+ console.error(`[Hydration] Failed to load ${fileId}:`, error);
+ return undefined;
+ }),
);
}
- return loadedFiles;
+ const loadedFiles = await Promise.all(loads);
+ return loadedFiles.filter(
+ (file): file is StirlingFile => file !== undefined,
+ );
} finally {
addFilesMutex.unlock();
}
diff --git a/frontend/editor/src/core/contexts/file/fileSelectors.ts b/frontend/editor/src/core/contexts/file/fileSelectors.ts
index 6a53b11a48..cbef938f48 100644
--- a/frontend/editor/src/core/contexts/file/fileSelectors.ts
+++ b/frontend/editor/src/core/contexts/file/fileSelectors.ts
@@ -20,6 +20,7 @@ export function createFileSelectors(
): FileContextSelectors {
return {
getFile: (id: FileId) => {
+ if (!stateRef.current.files.byId[id]) return undefined;
const file = filesRef.current.get(id);
return file ? createStirlingFile(file, id) : undefined;
},
@@ -27,6 +28,7 @@ export function createFileSelectors(
getFiles: (ids?: FileId[]) => {
const currentIds = ids || stateRef.current.files.ids;
return currentIds
+ .filter((id) => Boolean(stateRef.current.files.byId[id]))
.map((id) => {
const file = filesRef.current.get(id);
return file ? createStirlingFile(file, id) : undefined;
diff --git a/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts b/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
index c4bdda01c1..d94fdc0afd 100644
--- a/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
+++ b/frontend/editor/src/core/contexts/file/hydrationPublish.test.ts
@@ -48,8 +48,9 @@ async function harness(ids: string[]) {
const stateRef = { current: state };
const filesRef = { current: new Map<FileId, File>() };
const published: FileId[] = [];
+ const updateStirlingFileStub = vi.fn();
const lifecycleManager = {
- updateStirlingFileStub: (fileId: FileId) => published.push(fileId),
+ updateStirlingFileStub,
removeFiles: () => {},
trackBlobUrl: () => {},
};
@@ -59,19 +60,29 @@ async function harness(ids: string[]) {
{},
stateRef,
filesRef,
- () => {},
+ (action) => {
+ if (action.type === "ADD_FILES")
+ published.push(
+ ...action.payload.stirlingFileStubs.map((stub) => stub.id),
+ );
+ },
lifecycleManager as never,
);
- return { filesRef, published };
+ return { filesRef, published, updateStirlingFileStub };
}
describe("workbench hydration — a stalled parse can't hide the file", () => {
test("publishes every file's bytes while their parses hang", async () => {
// Three, because the parse queue only runs two at a time: the third proves
// loading isn't queued behind parses that never finish.
- const { filesRef, published } = await harness(["a", "b", "c"]);
+ const { filesRef, published, updateStirlingFileStub } = await harness([
+ "a",
+ "b",
+ "c",
+ ]);
await vi.waitFor(() => expect(published).toHaveLength(3));
expect([...filesRef.current.keys()]).toEqual(["a", "b", "c"]);
+ expect(updateStirlingFileStub).not.toHaveBeenCalled();
});
});
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.test.ts b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
index 397d9be479..c2401619c5 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.test.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
@@ -1,9 +1,16 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { FileLifecycleManager } from "@app/contexts/file/lifecycle";
import type { FileId } from "@app/types/file";
+import { createStirlingFile } from "@app/types/fileContext";
+import {
+ clearPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
describe("FileLifecycleManager", () => {
+ afterEach(clearPdfAccess);
beforeEach(() => {
vi.clearAllMocks();
});
@@ -52,4 +59,33 @@ describe("FileLifecycleManager", () => {
expect(filesRef.current.get(fileId)).toBe(original);
});
+
+ it("keeps session access across a rename without retaining access after cleanup", async () => {
+ const fileId = "protected-rename" as FileId;
+ const original = createStirlingFile(
+ new File(["encrypted bytes"], "old.pdf"),
+ fileId,
+ );
+ const access = {
+ password: "rename-test",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ };
+ rememberPdfAccess(original, access);
+ const filesRef = { current: new Map<FileId, File>([[fileId, original]]) };
+ const manager = new FileLifecycleManager(filesRef, vi.fn());
+ manager.updateStirlingFileStub(fileId, { name: "renamed.pdf" });
+ const renamed = filesRef.current.get(fileId);
+ expect(await renamed?.text()).toBe("encrypted bytes");
+ expect(getPdfAccess(renamed)).toEqual(access);
+ expect(getPdfAccess(fileId)).toEqual(access);
+ manager.cleanupAllFiles();
+ expect(getPdfAccess(renamed)).toBeUndefined();
+ expect(getPdfAccess(fileId)).toBeUndefined();
+ });
});
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.ts b/frontend/editor/src/core/contexts/file/lifecycle.ts
index 96b892b865..0f694d5505 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.ts
@@ -5,6 +5,11 @@
import { FileId } from "@app/types/file";
import { releaseSharedDocumentWhenIdle } from "@app/services/pdfiumService";
import { releaseDocumentBytes } from "@app/services/documentBytesCache";
+import {
+ forgetPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
import {
FileContextAction,
FileContextState,
@@ -72,6 +77,7 @@ export class FileLifecycleManager {
* Clean up all files and resources
*/
cleanupAllFiles = (): void => {
+ forgetPdfAccess([...this.filesRef.current.keys()]);
// Revoke all blob URLs
this.blobUrls.forEach((url) => {
try {
@@ -158,6 +164,7 @@ export class FileLifecycleManager {
fileId: FileId,
stateRef?: React.RefObject<FileContextState>,
): void => {
+ forgetPdfAccess([fileId]);
const file = this.filesRef.current.get(fileId);
this.filesRef.current.delete(fileId);
@@ -222,11 +229,14 @@ export class FileLifecycleManager {
// must replace it or the next tool run brings the old name back.
const held = this.filesRef.current.get(fileId);
if (held && updates.name !== undefined && updates.name !== held.name) {
+ const access = getPdfAccess(held);
const renamed = new File([held], updates.name, {
type: held.type,
lastModified: held.lastModified,
});
- this.filesRef.current.set(fileId, createStirlingFile(renamed, fileId));
+ const renamedFile = createStirlingFile(renamed, fileId);
+ this.filesRef.current.set(fileId, renamedFile);
+ if (access) rememberPdfAccess(renamedFile, access);
}
this.dispatch({
diff --git a/frontend/editor/src/core/hooks/tools/extractPages/useExtractPagesOperation.ts b/frontend/editor/src/core/hooks/tools/extractPages/useExtractPagesOperation.ts
index 67ddb52594..fc860280d0 100644
--- a/frontend/editor/src/core/hooks/tools/extractPages/useExtractPagesOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/extractPages/useExtractPagesOperation.ts
@@ -37,6 +37,7 @@ async function resolveSelectionToCsv(
export const extractPagesOperationConfig = defineCustomTool({
validateParams: validateExtractPagesParameters,
operationType: "extractPages",
+ endpoint: "/api/v1/general/rearrange-pages",
customProcessor: async (
parameters: ExtractPagesParameters,
files: File[],
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
index 09313c6b35..4d066bd44d 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolApiCalls.ts
@@ -9,6 +9,10 @@ import { isEmptyOutput } from "@app/services/errorUtils";
import type { ProcessingProgress } from "@app/hooks/tools/shared/useToolState";
import type { StirlingFile, FileId } from "@app/types/fileContext";
import { isSignupRequiredError } from "@app/utils/toolErrorHandler";
+import {
+ prepareUnlockedFile,
+ protectUnlockedResults,
+} from "@app/services/pdfSessionUnlock";
/** An input that did not survive the batch, with the error it failed on. */
export interface FailedInput {
@@ -80,7 +84,8 @@ export const useToolApiCalls = <TParams = void>() => {
onStatus(`Processing ${file.name} (${i + 1}/${total})`);
try {
- const formData = config.buildFormData(params, file);
+ 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",
@@ -118,7 +123,9 @@ export const useToolApiCalls = <TParams = void>() => {
}
continue;
}
- processedFiles.push(...responseFiles);
+ processedFiles.push(
+ ...(await protectUnlockedResults(responseFiles, [file], endpoint)),
+ );
// record source id as successful
successSourceIds.push(file.fileId);
console.debug("[processFiles] Success", {
diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
index a3fdaf124a..604377e658 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts
@@ -9,6 +9,10 @@ import { useFileContext } from "@app/contexts/FileContext";
import { useNavigationActions } from "@app/contexts/NavigationContext";
import { ViewerContext } from "@app/contexts/ViewerContext";
import { toolAcceptsFile } from "@app/utils/toolIOCompat";
+import {
+ prepareUnlockedFile,
+ protectUnlockedResults,
+} from "@app/services/pdfSessionUnlock";
import { useToolState } from "@app/hooks/tools/shared/useToolState";
import {
useToolApiCalls,
@@ -326,7 +330,14 @@ export const useToolOperation = <TParams>(
let unprocessedSourceIds: FileId[] = [];
// Use original files directly (no PDF metadata injection - history stored in IndexedDB)
- const filesForAPI = extractFiles(validFiles);
+ const filesForAPI: File[] = [];
+ for (const file of validFiles) {
+ filesForAPI.push(
+ config.toolType === ToolType.singleFile
+ ? file
+ : await prepareUnlockedFile(file, runtimeEndpoint),
+ );
+ }
switch (config.toolType) {
case ToolType.singleFile: {
@@ -459,6 +470,32 @@ export const useToolOperation = <TParams>(
}
}
+ if (config.toolType !== ToolType.singleFile) {
+ if (config.operationType === "extractPages") {
+ if (processedFiles.length !== validFiles.length)
+ throw new Error(
+ "Unable to match extracted pages to their protection source.",
+ );
+ const protectedFiles: File[] = [];
+ for (const [index, file] of processedFiles.entries()) {
+ protectedFiles.push(
+ ...(await protectUnlockedResults(
+ [file],
+ [validFiles[index]],
+ runtimeEndpoint,
+ )),
+ );
+ }
+ processedFiles = protectedFiles;
+ } else {
+ processedFiles = await protectUnlockedResults(
+ processedFiles,
+ validFiles,
+ runtimeEndpoint,
+ );
+ }
+ }
+
// Normalize error flags across tool types: mark failures, clear successes
try {
const allInputIds = validFiles.map((f) => f.fileId);
diff --git a/frontend/editor/src/core/hooks/useFileThumbnail.ts b/frontend/editor/src/core/hooks/useFileThumbnail.ts
index e564142c7c..ce13b773b7 100644
--- a/frontend/editor/src/core/hooks/useFileThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useFileThumbnail.ts
@@ -1,5 +1,6 @@
import { StirlingFileStub } from "@app/types/fileContext";
import { useIndexedDBThumbnail } from "@app/hooks/useIndexedDBThumbnail";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
export function useFileThumbnail(
fileStub: StirlingFileStub | null | undefined,
@@ -8,7 +9,8 @@ export function useFileThumbnail(
thumbnail: string | null;
isGenerating: boolean;
} {
- const isEncrypted = Boolean(fileStub?.processedFile?.isEncrypted);
+ const access = usePdfAccess(fileStub?.id);
+ const isEncrypted = Boolean(fileStub?.processedFile?.isEncrypted) && !access;
const { thumbnail: indexedDBThumb, isGenerating } = useIndexedDBThumbnail(
isEncrypted ? null : fileStub,
);
diff --git a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
index 6f0a043866..1bf1205739 100644
--- a/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useIndexedDBThumbnail.ts
@@ -2,7 +2,8 @@ import { useState, useEffect } from "react";
import { StirlingFileStub } from "@app/types/fileContext";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
-import { useFileManagement } from "@app/contexts/FileContext";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { useFileManagement, useFileSelectors } from "@app/contexts/FileContext";
/**
* Hook for IndexedDB-aware thumbnail loading
@@ -18,6 +19,7 @@ export function useIndexedDBThumbnail(
const [generating, setGenerating] = useState(false);
const indexedDB = useIndexedDB();
const { updateStirlingFileStub } = useFileManagement();
+ const selectors = useFileSelectors();
useEffect(() => {
let cancelled = false;
@@ -52,7 +54,8 @@ export function useIndexedDBThumbnail(
);
}
- const loadedFile = await indexedDB.loadFile(file.id);
+ const loadedFile =
+ selectors.getFile(file.id) ?? (await indexedDB.loadFile(file.id));
if (!loadedFile) {
throw new Error("not in IndexedDB (likely remote-only stub)");
}
@@ -64,7 +67,11 @@ export function useIndexedDBThumbnail(
if (file.id && indexedDB && thumbnail) {
try {
- await indexedDB.updateThumbnail(file.id, thumbnail);
+ await indexedDB.updateThumbnail(
+ file.id,
+ thumbnail,
+ getPdfAccess(loadedFile)?.encrypted ?? false,
+ );
// Also sync the in-memory stub so subsequent re-mounts hit tier 1
// instead of regenerating. IndexedDB persistence alone only helps
// the next page load; the current session reads file.thumbnailUrl
@@ -92,7 +99,14 @@ export function useIndexedDBThumbnail(
// set by this effect, and including it caused the effect to cancel
// itself mid-flight (orphaning the render and leaving generating=true
// stuck forever).
- }, [file, file?.thumbnailUrl, file?.id, indexedDB, updateStirlingFileStub]);
+ }, [
+ file,
+ file?.thumbnailUrl,
+ file?.id,
+ indexedDB,
+ updateStirlingFileStub,
+ selectors,
+ ]);
return { thumbnail: thumb, isGenerating: generating };
}
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
index 542e1f7c78..382ab8d94e 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
@@ -1,97 +1,161 @@
-import { renderHook, waitFor } from "@testing-library/react";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import type { FileId } from "@app/types/file";
+import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
import { useLazyThumbnail } from "@app/hooks/useLazyThumbnail";
-
-const mocks = vi.hoisted(() => ({
+import { createStirlingFile, type FileId } from "@app/types/fileContext";
+import {
+ clearPdfAccess,
+ forgetPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
+
+const storage = vi.hoisted(() => ({
loadFile: vi.fn(),
updateThumbnail: vi.fn(),
- updateStirlingFileStub: vi.fn(),
- generateThumbnailForFile: vi.fn(),
}));
-
+const management = vi.hoisted(() => ({ updateStirlingFileStub: vi.fn() }));
+const selectors = vi.hoisted(() => ({ getFile: vi.fn() }));
vi.mock("@app/contexts/IndexedDBContext", () => ({
- useIndexedDB: () => ({
- loadFile: mocks.loadFile,
- updateThumbnail: mocks.updateThumbnail,
- }),
+ useIndexedDB: () => storage,
}));
-
vi.mock("@app/contexts/FileContext", () => ({
- useFileManagement: () => ({
- updateStirlingFileStub: mocks.updateStirlingFileStub,
- }),
+ useFileManagement: () => management,
+ useFileSelectors: () => selectors,
}));
-
vi.mock("@app/utils/thumbnailUtils", () => ({
- generateThumbnailForFile: (...args: unknown[]) =>
- mocks.generateThumbnailForFile(...args),
+ generateThumbnailForFile: vi.fn(),
}));
-vi.mock("@app/services/localFolderContents", () => ({
- readDiskFile: vi.fn(),
-}));
+const access = {
+ password: "secret",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+};
+const id = "protected-preview" as FileId;
+const thumbnail = "data:image/png;base64,cached";
-const FILE_ID = "file-abc" as FileId;
+afterEach(() => {
+ cleanup();
+ clearPdfAccess();
+ vi.resetAllMocks();
+});
-function storeFile(): File {
- return new File([new Uint8Array(8)], "picture.png", { type: "image/png" });
-}
+describe("protected cached thumbnails", () => {
+ it("requires this session's unlock, and hides the preview again on close or logout", () => {
+ const file = createStirlingFile(new File(["encrypted"], "private.pdf"), id);
+ const { result } = renderHook(() =>
+ useLazyThumbnail(id, file.size, thumbnail, true),
+ );
+ expect(result.current).toBeUndefined();
+ expect(storage.loadFile).not.toHaveBeenCalled();
+ act(() => rememberPdfAccess(file, access));
+ expect(result.current).toBe(thumbnail);
+ act(() => forgetPdfAccess([id]));
+ expect(result.current).toBeUndefined();
+ act(() => rememberPdfAccess(file, access));
+ expect(result.current).toBe(thumbnail);
+ act(() => clearPdfAccess());
+ expect(result.current).toBeUndefined();
+ });
-afterEach(() => {
- vi.clearAllMocks();
+ it("does not reuse the old row's preview when a different protected version replaces it", () => {
+ const initialProps: {
+ fileId: FileId;
+ encrypted: boolean;
+ url: string | undefined;
+ } = { fileId: id, encrypted: false, url: thumbnail };
+ const { result, rerender } = renderHook(
+ ({ fileId, encrypted, url }) =>
+ useLazyThumbnail(fileId, 42, url, encrypted),
+ { initialProps },
+ );
+ expect(result.current).toBe(thumbnail);
+ rerender({
+ fileId: "new-version" as FileId,
+ encrypted: true,
+ url: undefined,
+ });
+ expect(result.current).toBeUndefined();
+ });
+
+ it("starts thumbnail generation after unlocking when the locked row has no cache", async () => {
+ const file = createStirlingFile(new File(["encrypted"], "private.pdf"), id);
+ selectors.getFile.mockReturnValue(file);
+ const { generateThumbnailForFile } =
+ await import("@app/utils/thumbnailUtils");
+ vi.mocked(generateThumbnailForFile).mockResolvedValue(thumbnail);
+ const { result, rerender } = renderHook(() =>
+ useLazyThumbnail(id, file.size, undefined, true),
+ );
+ expect(storage.loadFile).not.toHaveBeenCalled();
+ act(() => rememberPdfAccess(file, access));
+ await waitFor(() => expect(result.current).toBe(thumbnail));
+ expect(storage.loadFile).not.toHaveBeenCalled();
+ management.updateStirlingFileStub = vi.fn();
+ await act(async () => rerender());
+ expect(generateThumbnailForFile).toHaveBeenCalledTimes(1);
+ expect(storage.updateThumbnail).toHaveBeenCalledWith(id, thumbnail, true);
+ act(() => clearPdfAccess());
+ expect(result.current).toBeUndefined();
+ });
});
describe("useLazyThumbnail gating", () => {
it("queues no generation while the row is disabled", async () => {
const { result } = renderHook(() =>
- useLazyThumbnail(FILE_ID, 2048, undefined, false),
+ useLazyThumbnail(id, 2048, undefined, false, false),
);
await new Promise((resolve) => setTimeout(resolve, 20));
- expect(mocks.loadFile).not.toHaveBeenCalled();
- expect(mocks.generateThumbnailForFile).not.toHaveBeenCalled();
+ expect(storage.loadFile).not.toHaveBeenCalled();
+ expect(vi.mocked(generateThumbnailForFile)).not.toHaveBeenCalled();
expect(result.current).toBeUndefined();
});
it("generates once when a disabled row becomes enabled", async () => {
- mocks.loadFile.mockResolvedValue(storeFile());
- mocks.generateThumbnailForFile.mockResolvedValue(
+ storage.loadFile.mockResolvedValue(new File(["image"], "image.png"));
+ vi.mocked(generateThumbnailForFile).mockResolvedValue(
"data:image/png;base64,thumb",
);
const { result, rerender } = renderHook(
({ enabled }: { enabled: boolean }) =>
- useLazyThumbnail(FILE_ID, 2048, undefined, enabled),
+ useLazyThumbnail(id, 2048, undefined, false, enabled),
{ initialProps: { enabled: false } },
);
await new Promise((resolve) => setTimeout(resolve, 20));
- expect(mocks.loadFile).not.toHaveBeenCalled();
+ expect(storage.loadFile).not.toHaveBeenCalled();
rerender({ enabled: true });
await waitFor(() => {
expect(result.current).toBe("data:image/png;base64,thumb");
});
- expect(mocks.loadFile).toHaveBeenCalledTimes(1);
- expect(mocks.generateThumbnailForFile).toHaveBeenCalledTimes(1);
- expect(mocks.updateThumbnail).toHaveBeenCalledWith(
- FILE_ID,
+ expect(storage.loadFile).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(generateThumbnailForFile)).toHaveBeenCalledTimes(1);
+ expect(storage.updateThumbnail).toHaveBeenCalledWith(
+ id,
"data:image/png;base64,thumb",
+ false,
);
});
it("does not regenerate after re-enabling a row that already ran", async () => {
- mocks.loadFile.mockResolvedValue(storeFile());
- mocks.generateThumbnailForFile.mockResolvedValue(
+ storage.loadFile.mockResolvedValue(new File(["image"], "image.png"));
+ vi.mocked(generateThumbnailForFile).mockResolvedValue(
"data:image/png;base64,thumb",
);
const { result, rerender } = renderHook(
({ enabled }: { enabled: boolean }) =>
- useLazyThumbnail(FILE_ID, 2048, undefined, enabled),
+ useLazyThumbnail(id, 2048, undefined, false, enabled),
{ initialProps: { enabled: true } },
);
@@ -103,7 +167,7 @@ describe("useLazyThumbnail gating", () => {
rerender({ enabled: true });
await new Promise((resolve) => setTimeout(resolve, 20));
- expect(mocks.loadFile).toHaveBeenCalledTimes(1);
- expect(mocks.generateThumbnailForFile).toHaveBeenCalledTimes(1);
+ expect(storage.loadFile).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(generateThumbnailForFile)).toHaveBeenCalledTimes(1);
});
});
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.ts b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
index 2a8971dc67..403e379b56 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
@@ -1,9 +1,11 @@
import { useEffect, useRef, useState } from "react";
import type { FileId } from "@app/types/file";
-import { useFileManagement } from "@app/contexts/FileContext";
+import { useFileManagement, useFileSelectors } from "@app/contexts/FileContext";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { generateThumbnailForFile } from "@app/utils/thumbnailUtils";
import { readDiskFile } from "@app/services/localFolderContents";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
const THUMBNAIL_SIZE_LIMIT = 100 * 1024 * 1024; // 100MB
@@ -70,49 +72,82 @@ export function useLazyThumbnail(
fileId: FileId,
size: number,
thumbnailUrl?: string,
+ isEncrypted = false,
enabled = true,
): string | undefined {
- const [thumb, setThumb] = useState<string | undefined>(thumbnailUrl);
- const attempted = useRef(false);
+ const access = usePdfAccess(fileId);
+ const locked = isEncrypted && !access;
+ const [generated, setGenerated] = useState<{
+ fileId: FileId;
+ thumbnail: string;
+ }>();
const indexedDB = useIndexedDB();
const { updateStirlingFileStub } = useFileManagement();
+ const selectors = useFileSelectors();
+ const attempted = useRef<FileId | undefined>(undefined);
useEffect(() => {
- if (thumbnailUrl) setThumb(thumbnailUrl);
- }, [thumbnailUrl]);
-
- useEffect(() => {
- if (thumbnailUrl || attempted.current || size >= THUMBNAIL_SIZE_LIMIT)
+ if (locked) {
+ attempted.current = undefined;
+ return;
+ }
+ if (
+ !enabled ||
+ thumbnailUrl ||
+ size >= THUMBNAIL_SIZE_LIMIT ||
+ attempted.current === fileId
+ )
return;
- if (!enabled) return;
- attempted.current = true;
+ attempted.current = fileId;
let cancelled = false;
+ let completed = false;
scheduleLazyThumb(async () => {
// Row unmounted (or a hydration delivered the thumbnail) while this sat
// in the queue — skip the expensive byte load entirely.
if (cancelled) return;
try {
- const file = await indexedDB.loadFile(fileId);
+ const file =
+ selectors.getFile(fileId) ?? (await indexedDB.loadFile(fileId));
if (!file || cancelled) return;
const thumbnail = await generateThumbnailForFile(file);
- if (!thumbnail) return;
- if (!cancelled) setThumb(thumbnail);
- void indexedDB.updateThumbnail(fileId, thumbnail);
+ if (!thumbnail || cancelled) return;
+ setGenerated({ fileId, thumbnail });
+ void indexedDB.updateThumbnail(
+ fileId,
+ thumbnail,
+ getPdfAccess(file)?.encrypted ?? false,
+ );
queueStubThumbUpdate(fileId, thumbnail, (id, url) =>
updateStirlingFileStub(id, { thumbnailUrl: url }),
);
} catch {
// non-critical
+ } finally {
+ if (!cancelled) completed = true;
}
});
return () => {
cancelled = true;
+ if (!completed && attempted.current === fileId)
+ attempted.current = undefined;
};
- }, [fileId, size, thumbnailUrl, indexedDB, updateStirlingFileStub, enabled]);
-
- return thumb;
+ }, [
+ fileId,
+ size,
+ thumbnailUrl,
+ locked,
+ enabled,
+ indexedDB,
+ updateStirlingFileStub,
+ selectors,
+ ]);
+
+ return locked
+ ? undefined
+ : (thumbnailUrl ??
+ (generated?.fileId === fileId ? generated.thumbnail : undefined));
}
// Keyed by path + mtime + size: an unchanged file never renders twice, an edited one does.
diff --git a/frontend/editor/src/core/hooks/usePdfAccess.ts b/frontend/editor/src/core/hooks/usePdfAccess.ts
new file mode 100644
index 0000000000..6f07299a1d
--- /dev/null
+++ b/frontend/editor/src/core/hooks/usePdfAccess.ts
@@ -0,0 +1,16 @@
+import { useSyncExternalStore } from "react";
+import {
+ getPdfAccess,
+ pdfAccessRevision,
+ subscribePdfAccess,
+} from "@app/services/pdfPasswordStore";
+
+/** Observe session access without persisting the password in document metadata. */
+export function usePdfAccess(file: Blob | string | null | undefined) {
+ useSyncExternalStore(
+ subscribePdfAccess,
+ pdfAccessRevision,
+ pdfAccessRevision,
+ );
+ return getPdfAccess(file);
+}
diff --git a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts b/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
index cf2393b3f5..1cf4d01f74 100644
--- a/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
+++ b/frontend/editor/src/core/hooks/useThumbnailGeneration.ts
@@ -4,7 +4,7 @@ import {
type ThumbnailResult,
} from "@app/services/thumbnailGenerationService";
import { getDocumentBytes } from "@app/services/documentBytesCache";
-import { createQuickKey } from "@app/types/fileContext";
+import { createQuickKey, isStirlingFile } from "@app/types/fileContext";
import { FileId } from "@app/types/file";
// Request queue to handle concurrent thumbnail requests
@@ -79,7 +79,9 @@ async function processRequestQueue() {
const arrayBuffer = await getDocumentBytes(file);
// Use quickKey for PDF document caching (same metadata, consistent format)
- const fileId = createQuickKey(file) as FileId;
+ const fileId = isStirlingFile(file)
+ ? file.fileId
+ : (createQuickKey(file) as FileId);
const results = await thumbnailGenerationService.generateThumbnails(
fileId,
diff --git a/frontend/editor/src/core/services/fileStorage.encryption.test.ts b/frontend/editor/src/core/services/fileStorage.encryption.test.ts
new file mode 100644
index 0000000000..1a9be0c6b8
--- /dev/null
+++ b/frontend/editor/src/core/services/fileStorage.encryption.test.ts
@@ -0,0 +1,98 @@
+import "fake-indexeddb/auto";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ fileStorage,
+ type StoredStirlingFileRecord,
+} from "@app/services/fileStorage";
+import {
+ indexedDBManager,
+ DATABASE_CONFIGS,
+} from "@app/services/indexedDBManager";
+import {
+ createNewStirlingFileStub,
+ createStirlingFile,
+} from "@app/types/fileContext";
+import {
+ clearPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
+
+afterEach(async () => {
+ clearPdfAccess();
+ await fileStorage.clearAll();
+});
+
+describe("stored PDF protection metadata", () => {
+ it("reading a saved copy does not revoke the active document's session", async () => {
+ const file = new File(["encrypted bytes"], "private.pdf", {
+ type: "application/pdf",
+ });
+ const stub = createNewStirlingFileStub(file);
+ const original = createStirlingFile(file, stub.id);
+ rememberPdfAccess(original, {
+ password: "secret",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ });
+ await fileStorage.storeStirlingFile(original, stub);
+ const copy = await fileStorage.getStirlingFile(stub.id);
+ expect(copy).not.toBe(original);
+ expect(getPdfAccess(stub.id)?.password).toBe("secret");
+ expect(getPdfAccess(copy)).toBeUndefined();
+ });
+ it("retains encryption through all library read paths without retaining session access", async () => {
+ const file = new File(["encrypted bytes"], "private.pdf", {
+ type: "application/pdf",
+ });
+ const stub = createNewStirlingFileStub(file);
+ stub.processedFile = { pages: [], isEncrypted: true };
+ stub.thumbnailUrl = "data:image/png;base64,private";
+ await fileStorage.storeStirlingFile(
+ createStirlingFile(file, stub.id),
+ stub,
+ );
+ clearPdfAccess();
+ const reads = [
+ await fileStorage.getStirlingFileStub(stub.id),
+ ...(await fileStorage.getAllStirlingFileStubs()),
+ ...(await fileStorage.getLeafStirlingFileStubs()),
+ ];
+ expect(reads).toHaveLength(3);
+ for (const read of reads)
+ expect(read?.processedFile?.isEncrypted).toBe(true);
+ });
+
+ it("discards legacy PDF previews whose encryption status was never stored", async () => {
+ const file = new File(["protected legacy bytes"], "legacy.pdf", {
+ type: "application/pdf",
+ });
+ const stub = createNewStirlingFileStub(file);
+ const record: StoredStirlingFileRecord = {
+ ...stub,
+ fileId: stub.id,
+ quickKey: "legacy",
+ data: new Uint8Array([1, 2]).buffer,
+ thumbnail: "data:image/png;base64,private",
+ thumbnailStoredAt: Date.now(),
+ };
+ const db = await indexedDBManager.openDatabase(DATABASE_CONFIGS.FILES);
+ await new Promise<void>((resolve, reject) => {
+ const transaction = db.transaction("files", "readwrite");
+ transaction.objectStore("files").put(record);
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => reject(transaction.error);
+ });
+ const reads = [
+ await fileStorage.getStirlingFileStub(stub.id),
+ ...(await fileStorage.getAllStirlingFileStubs()),
+ ...(await fileStorage.getLeafStirlingFileStubs()),
+ ];
+ for (const read of reads) expect(read?.thumbnailUrl).toBeUndefined();
+ });
+});
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index e1835c2c2e..83855d23e0 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -18,6 +18,7 @@ import {
} from "@app/services/indexedDBManager";
import { alert } from "@app/components/toast";
import i18n from "i18next";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
/**
* Storage record - single source of truth
@@ -33,6 +34,8 @@ export interface StoredStirlingFileRecord extends BaseFileMetadata {
quickKey: string; // Matches runtime StirlingFile.quickKey exactly
thumbnail?: string;
thumbnailStoredAt?: number; // Epoch ms - sliding 30-day TTL
+ /** Whether opening these bytes requires a password; undefined for legacy records. */
+ isEncrypted?: boolean;
url?: string; // For compatibility with existing components
// Disk path this file came from (desktop only). Persisted so the link to the
// real file survives a reload - without it every restart drops to the stored copy.
@@ -285,6 +288,12 @@ class FileStorageService {
/** Returns thumbnail if within TTL, otherwise undefined. */
private isThumbnailFresh(record: StoredStirlingFileRecord): boolean {
+ // Legacy PDF previews predate encryption metadata and cannot prove the file is openable.
+ if (
+ record.isEncrypted === undefined &&
+ (record.type === "application/pdf" || /\.pdf$/i.test(record.name))
+ )
+ return false;
if (!record.thumbnail) return false;
if (!record.thumbnailStoredAt) return false;
return Date.now() - record.thumbnailStoredAt < THUMBNAIL_TTL_MS;
@@ -371,6 +380,9 @@ class FileStorageService {
: await copyBlobBytes(stirlingFile),
thumbnail: stub.thumbnailUrl,
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
+ isEncrypted:
+ getPdfAccess(stirlingFile)?.encrypted ??
+ stub.processedFile?.isEncrypted,
localFilePath: stub.localFilePath,
diskSyncedSize: stub.diskSyncedSize,
diskSyncedModifiedMs: stub.diskSyncedModifiedMs,
@@ -733,7 +745,9 @@ class FileStorageService {
this.reportIfUnreadable(record);
// Convert to StirlingFile with preserved IDs
- return createStirlingFile(fileFromRecord(record), record.fileId);
+ return createStirlingFile(fileFromRecord(record), record.fileId, {
+ bindSessionAccess: false,
+ });
}
/**
@@ -785,6 +799,10 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ processedFile:
+ record.isEncrypted === undefined
+ ? undefined
+ : { pages: [], isEncrypted: record.isEncrypted },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
@@ -861,6 +879,10 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ processedFile:
+ record.isEncrypted === undefined
+ ? undefined
+ : { pages: [], isEncrypted: record.isEncrypted },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
@@ -969,6 +991,10 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ processedFile:
+ record.isEncrypted === undefined
+ ? undefined
+ : { pages: [], isEncrypted: record.isEncrypted },
localFilePath: record.localFilePath,
diskSyncedSize: record.diskSyncedSize,
diskSyncedModifiedMs: record.diskSyncedModifiedMs,
@@ -1177,12 +1203,17 @@ class FileStorageService {
/**
* Update thumbnail for existing file
*/
- async updateThumbnail(id: FileId, thumbnail: string): Promise<boolean> {
+ async updateThumbnail(
+ id: FileId,
+ thumbnail: string,
+ isEncrypted?: boolean,
+ ): Promise<boolean> {
// Reports failure as `false` rather than rejecting; callers just need an answer.
try {
return await this.updateRecord(id, (record) => {
record.thumbnail = thumbnail;
record.thumbnailStoredAt = Date.now();
+ if (isEncrypted !== undefined) record.isEncrypted = isEncrypted;
});
} catch (error) {
console.error("Failed to update thumbnail:", error);
diff --git a/frontend/editor/src/core/services/pdfPasswordStore.ts b/frontend/editor/src/core/services/pdfPasswordStore.ts
new file mode 100644
index 0000000000..51ae028438
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfPasswordStore.ts
@@ -0,0 +1,94 @@
+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;
+ encrypted: boolean;
+ signed: boolean;
+ ownerAuthenticated: boolean;
+ permissions: number;
+ /** Older servers omit these; native exports must reject unverifiable protection. */
+ encryptionKeyLength?: number;
+ encryptionRevision?: number;
+ canModify: boolean;
+ canAssemble: boolean;
+ pageCount: number;
+}
+
+let accessByFile = new WeakMap<Blob, PdfAccess>();
+const filesById = new Map<string, Blob>();
+const listeners = new Set<() => void>();
+let revision = 0;
+
+function publish(): void {
+ revision++;
+ for (const listener of listeners) listener();
+}
+
+/** Look up credentials for these exact bytes; a replacement with the same filename must unlock separately. */
+export function getPdfAccess(
+ file: Blob | string | null | undefined,
+): PdfAccess | undefined {
+ if (!file) return undefined;
+ const blob = typeof file === "string" ? filesById.get(file) : file;
+ return blob ? accessByFile.get(blob) : undefined;
+}
+
+/** Retain access for the current session, without changing the original file. */
+export function rememberPdfAccess(file: Blob, access: PdfAccess): void {
+ accessByFile.set(file, access);
+ if ("fileId" in file && typeof file.fileId === "string")
+ filesById.set(file.fileId, file);
+ publish();
+}
+
+/** Bind a newly assigned FileContext identity to credentials already attached to its bytes. */
+export function bindPdfAccess(file: Blob, id: FileId): void {
+ const previous = filesById.get(id);
+ if (previous && previous !== file) {
+ accessByFile.delete(previous);
+ filesById.delete(id);
+ }
+ if (accessByFile.has(file)) filesById.set(id, file);
+}
+
+/** Closing a document drops its credential; reopening requires authentication again. */
+export function forgetPdfAccess(ids: readonly string[]): void {
+ for (const id of ids) {
+ const file = filesById.get(id);
+ if (file) accessByFile.delete(file);
+ filesById.delete(id);
+ }
+ publish();
+}
+
+/** Drop preview-owned access unless the same bytes have since entered FileContext. */
+export function forgetPreviewPdfAccess(file: Blob, access: PdfAccess): void {
+ if (
+ accessByFile.get(file) !== access ||
+ [...filesById.values()].includes(file)
+ )
+ return;
+ accessByFile.delete(file);
+ publish();
+}
+
+/** Clear all credentials on logout or FileContext teardown. */
+export function clearPdfAccess(): void {
+ accessByFile = new WeakMap();
+ filesById.clear();
+ publish();
+}
+
+/** Subscribe to unlock/lock changes without exposing credentials in React state. */
+export function subscribePdfAccess(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** Monotonic snapshot for useSyncExternalStore. */
+export function pdfAccessRevision(): number {
+ return revision;
+}
diff --git a/frontend/editor/src/core/services/pdfPermissions.ts b/frontend/editor/src/core/services/pdfPermissions.ts
new file mode 100644
index 0000000000..34d949533a
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfPermissions.ts
@@ -0,0 +1,15 @@
+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. */
+export function canPrintPdf(
+ access:
+ | Pick<PdfAccess, "encrypted" | "ownerAuthenticated" | "permissions">
+ | undefined,
+): boolean {
+ return (
+ !access?.encrypted ||
+ access.ownerAuthenticated ||
+ (access.permissions & PdfPermissionFlag.Print) !== 0
+ );
+}
diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.test.ts b/frontend/editor/src/core/services/pdfSessionUnlock.test.ts
new file mode 100644
index 0000000000..df52fcac74
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfSessionUnlock.test.ts
@@ -0,0 +1,360 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import apiClient from "@app/services/apiClient";
+import JSZip from "jszip";
+import { zipFileService } from "@app/services/zipFileService";
+import { handlePasswordError } from "@app/utils/toolErrorHandler";
+import { createStirlingFile } from "@app/types/fileContext";
+import {
+ clearPdfAccess,
+ forgetPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+} from "@app/services/pdfPasswordStore";
+import {
+ prepareUnlockedFile,
+ protectUnlockedResults,
+ unlockPdfForSession,
+ verifyEditedPdfProtection,
+ assertPdfSessionEditable,
+} from "@app/services/pdfSessionUnlock";
+
+vi.mock("@app/services/apiClient", () => ({ default: { post: vi.fn() } }));
+const post = vi.mocked(apiClient.post);
+const access: PdfAccess = {
+ password: " password\n",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: false,
+ permissions: -4,
+ encryptionKeyLength: 256,
+ encryptionRevision: 6,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 2,
+};
+const rotate = "/api/v1/general/rotate-pdf";
+
+beforeEach(() => {
+ clearPdfAccess();
+ post.mockReset();
+});
+afterEach(clearPdfAccess);
+
+describe("session PDF access", () => {
+ it("authenticates without rewriting bytes or retaining credentials before adoption", async () => {
+ const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));
+ const { password, ...info } = access;
+ post.mockResolvedValueOnce({ data: info });
+ expect(await unlockPdfForSession(original, password)).toEqual(access);
+ expect(post).toHaveBeenCalledOnce();
+ expect(post.mock.calls[0][0]).toBe("/api/v1/security/inspect-pdf-security");
+ const form = post.mock.calls[0][1] as FormData;
+ expect(form.get("fileInput")).toBe(original);
+ expect(form.get("password")).toBe(password);
+ expect(getPdfAccess(original)).toBeUndefined();
+ });
+
+ it("does not cache a rejected password", async () => {
+ const original = new File(["encrypted"], "locked.pdf");
+ post.mockRejectedValueOnce(new Error("Incorrect password"));
+ await expect(unlockPdfForSession(original, "wrong")).rejects.toThrow(
+ "Incorrect password",
+ );
+ expect(getPdfAccess(original)).toBeUndefined();
+ });
+
+ it("strips password-bearing request objects while preserving password errors", async () => {
+ const form = new FormData();
+ form.set("password", "secret");
+ const config = { data: form };
+ const original = Object.assign(new Error("Bad request"), {
+ isAxiosError: true,
+ config,
+ request: { config },
+ response: { status: 400, data: { type: "/errors/pdf-password" }, config },
+ });
+ post.mockRejectedValueOnce(original);
+ const error = await unlockPdfForSession(
+ new File(["pdf"], "test.pdf"),
+ "secret",
+ ).catch((error: unknown) => error);
+ expect(error).not.toBe(original);
+ expect(error).not.toHaveProperty("config");
+ expect(error).not.toHaveProperty("request");
+ expect(error).not.toHaveProperty("response.config");
+ expect(error).not.toHaveProperty("cause");
+ expect(
+ await handlePasswordError(error, "Incorrect password", "Failed"),
+ ).toBe("Incorrect password");
+ });
+
+ it.each([
+ { encrypted: false },
+ { permissions: -44 },
+ { encryptionKeyLength: 128 },
+ { encryptionRevision: 4 },
+ { ownerAuthenticated: true },
+ { encryptionKeyLength: undefined },
+ ])("rejects a native export with changed protection: %j", async (changed) => {
+ const output = new File(["export"], "edited.pdf");
+ post.mockResolvedValueOnce({ data: { ...access, ...changed } });
+ await expect(verifyEditedPdfProtection(output, access)).rejects.toThrow(
+ "Unable to preserve PDF protection",
+ );
+ expect(getPdfAccess(output)).toBeUndefined();
+ });
+
+ it("adopts a verified native export and blocks signed protected edits", async () => {
+ const output = new File(["export"], "edited.pdf");
+ post.mockResolvedValueOnce({ data: access });
+ await verifyEditedPdfProtection(output, access);
+ expect(getPdfAccess(output)).toEqual(access);
+ await expect(
+ verifyEditedPdfProtection(output, { ...access, signed: true }),
+ ).rejects.toThrow("digital signatures");
+ expect(post).toHaveBeenCalledOnce();
+ expect(() =>
+ assertPdfSessionEditable({ encrypted: false, signed: true }),
+ ).not.toThrow();
+ });
+
+ it("rejects native exports when the source protection cannot be verified", async () => {
+ post.mockResolvedValueOnce({ data: access });
+ const output = new File(["export"], "edited.pdf");
+ await expect(
+ verifyEditedPdfProtection(output, {
+ ...access,
+ encryptionKeyLength: undefined,
+ }),
+ ).rejects.toThrow("Unable to preserve PDF protection");
+ expect(getPdfAccess(output)).toBeUndefined();
+ });
+
+ it("isolates same-name files and drops access when a document closes", () => {
+ const first = createStirlingFile(new File(["one"], "locked.pdf"));
+ const second = createStirlingFile(new File(["two"], "locked.pdf"));
+ rememberPdfAccess(first, access);
+ expect(getPdfAccess(first.fileId)).toEqual(access);
+ expect(getPdfAccess(second)).toBeUndefined();
+ expect(Object.keys(first)).not.toContain("password");
+ forgetPdfAccess([first.fileId]);
+ expect(getPdfAccess(first)).toBeUndefined();
+ expect(getPdfAccess(first.fileId)).toBeUndefined();
+ });
+
+ it("uses a temporary decrypted copy without transferring credentials to it", async () => {
+ const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));
+ rememberPdfAccess(original, access);
+ post.mockResolvedValueOnce({ data: new Blob(["decrypted"]) });
+ const working = await prepareUnlockedFile(original, rotate);
+ expect(working).not.toBe(original);
+ expect(working.name).toBe(original.name);
+ expect(getPdfAccess(working)).toBeUndefined();
+ expect(getPdfAccess(original.fileId)).toEqual(access);
+ });
+
+ it("requires a fresh unlock when different bytes replace an existing file identity", () => {
+ const original = createStirlingFile(new File(["old"], "locked.pdf"));
+ rememberPdfAccess(original, access);
+ const replacement = createStirlingFile(
+ new File(["new"], "locked.pdf"),
+ original.fileId,
+ );
+ expect(getPdfAccess(replacement)).toBeUndefined();
+ expect(getPdfAccess(original.fileId)).toBeUndefined();
+ expect(getPdfAccess(original)).toBeUndefined();
+ });
+
+ it.each([
+ ["/api/v1/security/auto-redact", access, "does not yet support"],
+ [rotate, { ...access, signed: true }, "digital signatures"],
+ [rotate, { ...access, canAssemble: false }, "restricts"],
+ ])(
+ "rejects unsupported or restricted processing before decrypting",
+ async (endpoint, permission, message) => {
+ const original = createStirlingFile(
+ new File(["encrypted"], "locked.pdf"),
+ );
+ rememberPdfAccess(original, permission);
+ await expect(prepareUnlockedFile(original, endpoint)).rejects.toThrow(
+ message,
+ );
+ expect(post).not.toHaveBeenCalled();
+ },
+ );
+
+ it("decrypts a mixed-password merge independently and inherits its first protected input", async () => {
+ const first = createStirlingFile(new File(["a"], "first.pdf"));
+ const second = createStirlingFile(new File(["b"], "second.pdf"));
+ rememberPdfAccess(first, access);
+ rememberPdfAccess(second, { ...access, password: "second-password" });
+ post.mockResolvedValue({ data: new Blob(["result"]) });
+ 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);
+ });
+
+ it("returns no partial output if protection restoration fails", async () => {
+ const original = new File(["encrypted"], "locked.pdf");
+ rememberPdfAccess(original, access);
+ const outputs = [
+ new File(["one"], "one.pdf"),
+ new File(["two"], "two.pdf"),
+ ];
+ post
+ .mockResolvedValueOnce({ data: new Blob(["protected"]) })
+ .mockRejectedValueOnce(new Error("qpdf unavailable"));
+ await expect(
+ protectUnlockedResults(outputs, [original], rotate),
+ ).rejects.toThrow("No unprotected result was saved");
+ expect(outputs.every((file) => !getPdfAccess(file))).toBe(true);
+ });
+
+ it("leaves explicit Remove Password output unprotected", async () => {
+ const original = createStirlingFile(new File(["encrypted"], "locked.pdf"));
+ rememberPdfAccess(original, access);
+ const endpoint = "/api/v1/security/remove-password";
+ const outputs = [new File(["plain"], "plain.pdf")];
+ expect(await prepareUnlockedFile(original, endpoint)).toBe(original);
+ expect(await protectUnlockedResults(outputs, [original], endpoint)).toBe(
+ outputs,
+ );
+ expect(post).not.toHaveBeenCalled();
+ });
+});
+
+function readBlobBytes(blob: Blob): Promise<ArrayBuffer> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as ArrayBuffer);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsArrayBuffer(blob);
+ });
+}
+
+async function splitArchive(count: number): Promise<File> {
+ const zip = new JSZip();
+ for (let page = 1; page <= count; page++) {
+ zip.file(`pages/page-${page}.pdf`, `%PDF-1.7\npage ${page}`);
+ }
+ return new File(
+ [await zip.generateAsync({ type: "arraybuffer" })],
+ "split.zip",
+ {
+ type: "application/zip",
+ },
+ );
+}
+
+describe("protected split archives", () => {
+ beforeEach(() => {
+ vi.spyOn(Blob.prototype, "arrayBuffer").mockImplementation(
+ function (this: Blob) {
+ return readBlobBytes(this);
+ },
+ );
+ vi.spyOn(File.prototype, "arrayBuffer").mockImplementation(
+ function (this: File) {
+ return readBlobBytes(this);
+ },
+ );
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("preserves ZIP output and protects all ten entries with the source password", async () => {
+ const source = new File(["encrypted"], "source.pdf");
+ rememberPdfAccess(source, access);
+ const archive = await splitArchive(10);
+ const outputs = await zipFileService.extractWithPreferences(archive, {
+ autoUnzip: true,
+ autoUnzipFileLimit: 4,
+ });
+ expect(outputs).toEqual([archive]);
+ post.mockImplementation(async (_url, body) => {
+ const entry = (body as FormData).get("fileInput") as File;
+ return { data: new Blob([`%PDF-1.7\nprotected ${entry.name}`]) };
+ });
+ const [protectedZip] = await protectUnlockedResults(
+ outputs,
+ [source],
+ "/api/v1/general/split-by-size-or-count",
+ );
+ expect(protectedZip.name).toBe("split.zip");
+ expect(protectedZip.type).toBe("application/zip");
+ const zip = await JSZip.loadAsync(await readBlobBytes(protectedZip));
+ const entries = Object.values(zip.files).filter((entry) => !entry.dir);
+ expect(entries).toHaveLength(10);
+ for (const entry of entries) {
+ expect(await entry.async("string")).toBe(
+ `%PDF-1.7\nprotected ${entry.name}`,
+ );
+ }
+ expect(post).toHaveBeenCalledTimes(10);
+ for (const [endpoint, body] of post.mock.calls) {
+ expect(endpoint).toBe("/api/v1/security/restore-pdf-protection");
+ expect((body as FormData).get("sourceFile")).toBe(source);
+ expect((body as FormData).get("password")).toBe(access.password);
+ }
+ expect(getPdfAccess(protectedZip)).toBeUndefined();
+ });
+
+ it("returns no ZIP if any entry fails protection", async () => {
+ const source = new File(["encrypted"], "source.pdf");
+ rememberPdfAccess(source, access);
+ post
+ .mockResolvedValueOnce({ data: new Blob(["protected"]) })
+ .mockRejectedValueOnce(new Error("protection failed"));
+ await expect(
+ protectUnlockedResults([await splitArchive(10)], [source], rotate),
+ ).rejects.toThrow("No unprotected result was saved");
+ expect(post).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects incomplete ZIP extraction instead of silently losing entries", async () => {
+ const source = new File(["encrypted"], "source.pdf");
+ rememberPdfAccess(source, access);
+ vi.spyOn(zipFileService, "extractAllFiles").mockResolvedValue({
+ success: true,
+ extractedFiles: [new File(["one"], "one.pdf")],
+ errors: ["Unreadable second entry"],
+ totalFiles: 2,
+ extractedCount: 1,
+ });
+ await expect(
+ protectUnlockedResults([await splitArchive(2)], [source], rotate),
+ ).rejects.toThrow("No unprotected result was saved");
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it("rejects non-PDF entries instead of returning unprotected content", async () => {
+ const source = new File(["encrypted"], "source.pdf");
+ rememberPdfAccess(source, access);
+ const zip = new JSZip();
+ zip.file("content.txt", "unprotected content");
+ const output = new File(
+ [await zip.generateAsync({ type: "arraybuffer" })],
+ "result.zip",
+ { type: "application/zip" },
+ );
+ await expect(
+ protectUnlockedResults([output], [source], rotate),
+ ).rejects.toThrow("No unprotected result was saved");
+ expect(post).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/services/pdfSessionUnlock.ts b/frontend/editor/src/core/services/pdfSessionUnlock.ts
new file mode 100644
index 0000000000..3bb66920d0
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfSessionUnlock.ts
@@ -0,0 +1,234 @@
+import apiClient from "@app/services/apiClient";
+import axios from "axios";
+import i18n from "i18next";
+import {
+ getPdfAccess,
+ rememberPdfAccess,
+ type PdfAccess,
+} from "@app/services/pdfPasswordStore";
+import type { StirlingFile } from "@app/types/fileContext";
+import { zipFileService } from "@app/services/zipFileService";
+
+const SUPPORTED_ENDPOINTS = new Set([
+ "/api/v1/general/rotate-pdf",
+ "/api/v1/general/remove-pages",
+ "/api/v1/general/rearrange-pages",
+ "/api/v1/general/merge-pdfs",
+ "/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",
+ "/api/v1/misc/compress-pdf",
+]);
+
+async function requestWorkingPdf(
+ endpoint: string,
+ form: FormData,
+ message: string,
+): Promise<Blob> {
+ try {
+ const response = await apiClient.post<Blob>(endpoint, form, {
+ responseType: "blob",
+ suppressErrorToast: true,
+ });
+ return response.data;
+ } catch {
+ // Axios errors carry the password-bearing request form into tool logs and failure history.
+ throw new Error(message);
+ }
+}
+
+/** These interactive operations restore protection before exposing or persisting any result. */
+export function supportsSessionUnlock(endpoint: string | undefined): boolean {
+ return endpoint !== undefined && SUPPORTED_ENDPOINTS.has(endpoint);
+}
+
+/** Authenticate without rewriting the uploaded document. The password stays outside file metadata. */
+export async function unlockPdfForSession(
+ file: File,
+ password: string,
+): Promise<PdfAccess> {
+ const form = new FormData();
+ form.append("fileInput", file);
+ form.append("password", password);
+ try {
+ const response = await apiClient.post<Omit<PdfAccess, "password">>(
+ "/api/v1/security/inspect-pdf-security",
+ form,
+ { suppressErrorToast: true },
+ );
+ return { ...response.data, password };
+ } catch (error) {
+ const sanitized = new Error(
+ error instanceof Error ? error.message : "Unable to unlock this PDF.",
+ );
+ if (axios.isAxiosError(error)) {
+ // Keep password-error classification without retaining the request or its FormData.
+ Object.assign(sanitized, {
+ isAxiosError: true,
+ response: error.response
+ ? { status: error.response.status, data: error.response.data }
+ : undefined,
+ });
+ }
+ throw sanitized;
+ }
+}
+
+/** Signed protected PDFs remain view-only until their edits can preserve signatures. */
+export function assertPdfSessionEditable(
+ access: Pick<PdfAccess, "encrypted" | "signed"> | undefined,
+): void {
+ if (access?.encrypted && access.signed)
+ throw new Error(
+ i18n.t(
+ "encryptedPdfUnlock.signedReadOnly",
+ "This PDF has digital signatures. Session unlocking supports viewing it, but processing signed PDFs is not supported yet.",
+ ),
+ );
+}
+
+/** Native exports must retain source protection before storage or download can receive them. */
+export async function verifyEditedPdfProtection(
+ output: File,
+ sourceAccess: PdfAccess | undefined,
+): Promise<void> {
+ if (!sourceAccess?.encrypted) return;
+ assertPdfSessionEditable(sourceAccess);
+ const access = await unlockPdfForSession(output, sourceAccess.password);
+ if (
+ !access.encrypted ||
+ access.permissions !== sourceAccess.permissions ||
+ access.ownerAuthenticated !== sourceAccess.ownerAuthenticated ||
+ sourceAccess.encryptionKeyLength === undefined ||
+ access.encryptionKeyLength !== sourceAccess.encryptionKeyLength ||
+ sourceAccess.encryptionRevision === undefined ||
+ access.encryptionRevision !== sourceAccess.encryptionRevision
+ )
+ throw new Error(
+ i18n.t(
+ "encryptedPdfUnlock.restoreFailed",
+ "Unable to preserve PDF protection. No unprotected result was saved.",
+ ),
+ );
+ rememberPdfAccess(output, access);
+}
+
+/** Decrypted bytes belong only to this operation. They must never enter FileContext or persistence. */
+export async function prepareUnlockedFile(
+ file: StirlingFile,
+ endpoint: string | undefined,
+): Promise<File> {
+ const access = getPdfAccess(file);
+ if (!access?.encrypted || endpoint === "/api/v1/security/remove-password")
+ 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.",
+ ),
+ );
+ if (access.signed)
+ throw new Error(
+ i18n.t(
+ "encryptedPdfUnlock.signedReadOnly",
+ "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)
+ throw new Error(
+ i18n.t(
+ "encryptedPdfUnlock.restrictedOperation",
+ "This PDF restricts this operation. Reopen it with the owner password to continue.",
+ ),
+ );
+ const form = new FormData();
+ form.append("fileInput", file);
+ form.append("password", access.password);
+ const bytes = await requestWorkingPdf(
+ "/api/v1/security/remove-password",
+ form,
+ i18n.t(
+ "encryptedPdfUnlock.prepareFailed",
+ "Unable to prepare this protected PDF for processing.",
+ ),
+ );
+ return new File([bytes], file.name, { type: "application/pdf" });
+}
+
+function protectionRestoreError(): Error {
+ return new Error(
+ i18n.t(
+ "encryptedPdfUnlock.restoreFailed",
+ "Unable to preserve PDF protection. No unprotected result was saved.",
+ ),
+ );
+}
+
+async function protectPdfOutput(
+ output: File,
+ source: File,
+ access: PdfAccess,
+): Promise<File> {
+ if (
+ output.type !== "application/pdf" &&
+ !output.name.toLowerCase().endsWith(".pdf")
+ )
+ throw protectionRestoreError();
+ const form = new FormData();
+ form.append("fileInput", output);
+ form.append("sourceFile", source);
+ form.append("password", access.password);
+ const bytes = await requestWorkingPdf(
+ "/api/v1/security/restore-pdf-protection",
+ form,
+ protectionRestoreError().message,
+ );
+ const file = new File([bytes], output.name, { type: "application/pdf" });
+ rememberPdfAccess(file, { ...access, signed: false });
+ return file;
+}
+
+/** Restore protection before results reach downloads or storage, including every PDF in a ZIP. Merges inherit the first protected input. */
+export async function protectUnlockedResults(
+ outputs: File[],
+ inputs: readonly File[],
+ endpoint: string | undefined,
+): Promise<File[]> {
+ if (endpoint === "/api/v1/security/remove-password") return outputs;
+ const source = inputs.find((file) => getPdfAccess(file)?.encrypted);
+ if (!source) return outputs;
+ const access = getPdfAccess(source)!;
+ const protectedFiles: File[] = [];
+ for (const output of outputs) {
+ if (await zipFileService.isZipResponse(output)) {
+ const extracted = await zipFileService.extractAllFiles(output);
+ if (
+ !extracted.success ||
+ extracted.errors.length > 0 ||
+ extracted.extractedCount !== extracted.totalFiles ||
+ extracted.extractedFiles.length === 0
+ )
+ throw protectionRestoreError();
+ const protectedEntries: File[] = [];
+ for (const entry of extracted.extractedFiles) {
+ protectedEntries.push(await protectPdfOutput(entry, source, access));
+ }
+ const { zipFile } = await zipFileService.createZipFromFiles(
+ protectedEntries,
+ output.name,
+ );
+ protectedFiles.push(zipFile);
+ } else {
+ protectedFiles.push(await protectPdfOutput(output, source, access));
+ }
+ }
+ return protectedFiles;
+}
diff --git a/frontend/editor/src/core/services/thumbnailGenerationService.ts b/frontend/editor/src/core/services/thumbnailGenerationService.ts
index e653361566..5e96c31433 100644
--- a/frontend/editor/src/core/services/thumbnailGenerationService.ts
+++ b/frontend/editor/src/core/services/thumbnailGenerationService.ts
@@ -3,6 +3,7 @@
*/
import { FileId } from "@app/types/file";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
import {
openRawDocumentSafe,
closeRawDocument,
@@ -70,7 +71,10 @@ export class ThumbnailGenerationService {
this.evictLeastRecentlyUsedPDF();
}
- const docPtr = await openRawDocumentSafe(pdfArrayBuffer);
+ const docPtr = await openRawDocumentSafe(
+ pdfArrayBuffer,
+ getPdfAccess(fileId)?.password,
+ );
this.pdfDocumentCache.set(fileId, {
docPtr,
diff --git a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
index 242b6910fc..4f529800d5 100644
--- a/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
+++ b/frontend/editor/src/core/tests/ToolFileSelection.test.tsx
@@ -1,6 +1,12 @@
import { createContext, type ReactNode } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import { render, renderHook, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ render,
+ renderHook,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MantineProvider } from "@mantine/core";
import Compress from "@app/tools/Compress";
@@ -26,6 +32,10 @@ import { FileItem } from "@app/components/shared/FileSidebarFileItem";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import { useCompressOperation } from "@app/hooks/tools/compress/useCompressOperation";
import { defaultParameters as compressParameters } from "@app/hooks/tools/compress/useCompressParameters";
+import {
+ rememberPdfAccess,
+ clearPdfAccess,
+} from "@app/services/pdfPasswordStore";
const workspace = {
files: [] as StirlingFile[],
@@ -40,6 +50,7 @@ const selectors = {
const loadRecentFiles = vi.fn().mockResolvedValue([]);
const onFileClick = vi.fn();
const onPreviewRender = vi.fn();
+const handleToolSelect = vi.fn();
const pdfWorker = vi.hoisted(() => ({
createDocument: vi.fn(),
@@ -100,6 +111,9 @@ vi.mock("@app/contexts/NavigationContext", () => ({
useNavigationState: () => navigation,
useNavigationActions: () => ({ actions: {} }),
}));
+vi.mock("@app/contexts/ToolWorkflowContext", () => ({
+ useToolWorkflowActions: () => ({ handleToolSelect }),
+}));
vi.mock("@app/contexts/PreferencesContext", () => ({
usePreferences: () => ({ preferences: {} }),
}));
@@ -189,6 +203,53 @@ beforeEach(() => {
});
describe("tool file selection", () => {
+ test("explains why an unlocked protected PDF is excluded", async () => {
+ workspace.fileStubs[0].processedFile = { pages: [], isEncrypted: true };
+ rememberPdfAccess(workspace.files[0], {
+ password: "secret",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ });
+ try {
+ render(
+ <MantineProvider>
+ <EmptyFileSelectionTool filesVisible />
+ </MantineProvider>,
+ );
+ const fileList = await screen.findByTestId("tool-file-list");
+ expect(fileList).toContainElement(screen.getByRole("listitem"));
+ expect(screen.getByRole("listitem")).toHaveTextContent("report.pdf");
+ expect(
+ screen.queryByText(/Add files to the workbench/),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
+ act(() =>
+ screen
+ .getByRole("button", { name: "Why report.pdf is unavailable" })
+ .focus(),
+ );
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "This tool doesn't support encrypted PDFs. Remove the password first.",
+ );
+ const removePassword = screen.getByRole("button", {
+ name: "Remove Password",
+ });
+ act(() => removePassword.focus());
+ const help = await screen.findByText(
+ "Open Remove Password to create an unprotected copy.",
+ );
+ await waitFor(() => expect(help).toBeVisible());
+ await userEvent.click(removePassword);
+ expect(handleToolSelect).toHaveBeenCalledWith("removePassword");
+ } finally {
+ act(() => clearPdfAccess());
+ }
+ });
test("eligible selections keep their identity until file objects or order change", () => {
const secondPdf = createTestStirlingFile(
"second.pdf",
diff --git a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
index affb5eb799..2991312aa6 100644
--- a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
+++ b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx
@@ -164,6 +164,16 @@ describe("Convert Tool Integration Tests", () => {
"encrypted",
"application/pdf",
);
+ rememberPdfAccess(locked, {
+ password: "test",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ });
const files = [locked, pdf];
const customProcessor = vi.fn().mockResolvedValue({ files: [pdf] });
const { result } = renderHook(
@@ -247,6 +257,16 @@ describe("Convert Tool Integration Tests", () => {
"encrypted",
"application/pdf",
);
+ rememberPdfAccess(locked, {
+ password: "test",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ });
const files = [image, locked, pdf, svg];
await act(async () => {
result.current.context.dispatch({
@@ -1352,3 +1372,4 @@ describe("Convert Tool Integration Tests", () => {
* - Test graceful degradation when endpoints are disabled
* - Test dynamic endpoint configuration updates
*/
+import { rememberPdfAccess } from "@app/services/pdfPasswordStore";
diff --git a/frontend/editor/src/core/tests/live/encrypted-unlock-then-tool.spec.ts b/frontend/editor/src/core/tests/live/encrypted-unlock-then-tool.spec.ts
index d1b3641962..b458c01d66 100644
--- a/frontend/editor/src/core/tests/live/encrypted-unlock-then-tool.spec.ts
+++ b/frontend/editor/src/core/tests/live/encrypted-unlock-then-tool.spec.ts
@@ -50,7 +50,7 @@ test.describe("Encrypted PDF: unlock then merge", () => {
);
return;
}
- await passwordInput.fill("test");
+ await passwordInput.fill("testpass123");
await page
.getByRole("button", { name: /unlock/i })
.first()
diff --git a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
index 26dbd836c8..6814e892d7 100644
--- a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
@@ -1,6 +1,5 @@
import path from "path";
import { test, expect } from "@app/tests/helpers/stub-test-base";
-import { uploadFiles } from "@app/tests/helpers/ui-helpers";
// A bulk upload must classify every file in the browser and group it - no file
// may be stranded in "Other" by races between the upload wave and delivery.
@@ -59,21 +58,23 @@ test("a 10-file upload wave classifies every file into its group", async ({
timeout: 120_000,
});
- await uploadFiles(
- page,
- [
- "invoice_acme.pdf",
- "bank_statement.pdf",
- "purchase_order.pdf",
- "nda_mutual.pdf",
- "service_agreement.pdf",
- "resume_jane_doe.pdf",
- "cover_letter.pdf",
- "offer_letter.pdf",
- "generic_notes.pdf",
- "spanish_contrato.pdf",
- ].map((f) => path.join(FIXTURES, f)),
- );
+ await page.getByTestId("files-button").click();
+ await page
+ .locator('[data-testid="file-input"]')
+ .setInputFiles(
+ [
+ "invoice_acme.pdf",
+ "bank_statement.pdf",
+ "purchase_order.pdf",
+ "nda_mutual.pdf",
+ "service_agreement.pdf",
+ "resume_jane_doe.pdf",
+ "cover_letter.pdf",
+ "offer_letter.pdf",
+ "generic_notes.pdf",
+ "spanish_contrato.pdf",
+ ].map((f) => path.join(FIXTURES, f)),
+ );
const header = (name: string, count: number) =>
page.getByRole("button", { name: `${name} ${count}`, exact: true });
diff --git a/frontend/editor/src/core/tests/stubbed/compare.spec.ts b/frontend/editor/src/core/tests/stubbed/compare.spec.ts
index c3c6a990a1..180bfbbae0 100644
--- a/frontend/editor/src/core/tests/stubbed/compare.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/compare.spec.ts
@@ -125,7 +125,10 @@ test.describe("Compare tool slot selection", () => {
);
// Compare button should be enabled now that both slots are set.
- const compareButton = page.getByRole("button", { name: "Compare" });
+ const compareButton = page.getByRole("button", {
+ name: "Compare",
+ exact: true,
+ });
await expect(compareButton).toBeEnabled();
});
@@ -192,7 +195,10 @@ test.describe("Compare tool slot selection", () => {
"compare_sample_b.pdf",
);
- const compareButton = page.getByRole("button", { name: "Compare" });
+ const compareButton = page.getByRole("button", {
+ name: "Compare",
+ exact: true,
+ });
await expect(compareButton).toBeEnabled();
});
diff --git a/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts b/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
index c2844bba29..c7a6f5bbf1 100644
--- a/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/encrypted-pdf-unlock.spec.ts
@@ -1,54 +1,40 @@
/**
- * End-to-End Tests for Encrypted PDF Password Prompting
- *
- * Tests the EncryptedPdfUnlockModal flow when uploading password-protected PDFs.
- * All backend API calls are mocked via page.route() - no real backend required.
- *
- * Coverage trimmed to 5 high-value cases:
- * 1. Modal renders with the expected title/inputs/buttons.
- * 2. Successful unlock removes the modal and shows the success toast.
- * 3. Wrong password keeps the modal open with an inline error.
- * 4. Pressing Enter in the password field triggers unlock.
- * 5. Multiple encrypted files surface the "Use for all" affordance and
- * unlocking via that path resolves the modal.
- *
- * Removed previously: input-disabled-when-empty, input-enabled-after-fill,
- * skip-button-closes, normal-PDF-doesn't-prompt, single-file-hides-use-for-all,
- * unlock-all-wrong-password - all transitively covered or low-value.
+ * Backend-free coverage for session unlocks and cached preview privacy.
+ * Security inspection is stubbed; EmbedPDF renders the actual encrypted fixture.
*/
import { test, expect, type Page } from "@playwright/test";
import path from "path";
import fs from "fs";
+import { createHash } from "node:crypto";
+import { PDFDocument } from "@cantoo/pdf-lib";
+import JSZip from "jszip";
import { mockAppApis } from "@app/tests/helpers/api-stubs";
import { suppressNativeFilePicker } from "@app/tests/helpers/ui-helpers";
const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");
const ENCRYPTED_PDF = path.join(FIXTURES_DIR, "encrypted.pdf");
-const FAKE_UNLOCKED_PDF = Buffer.from(
- "%PDF-1.4\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n" +
- "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n" +
- "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n" +
- "xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n" +
- "0000000115 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n190\n%%EOF",
-);
-
-function mockRemovePasswordSuccess(page: Page) {
- return page.route("**/api/v1/security/remove-password", (route) =>
+function mockUnlockSuccess(page: Page, pageCount = 1) {
+ return page.route("**/api/v1/security/inspect-pdf-security", (route) =>
route.fulfill({
status: 200,
- contentType: "application/pdf",
- headers: {
- "Content-Disposition": 'attachment; filename="encrypted.pdf"',
- },
- body: FAKE_UNLOCKED_PDF,
+ contentType: "application/json",
+ body: JSON.stringify({
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount,
+ }),
}),
);
}
-function mockRemovePasswordWrongPassword(page: Page) {
- return page.route("**/api/v1/security/remove-password", (route) =>
+function mockUnlockWrongPassword(page: Page) {
+ return page.route("**/api/v1/security/inspect-pdf-security", (route) =>
route.fulfill({
status: 400,
contentType: "application/problem+json",
@@ -71,9 +57,9 @@ async function uploadEncryptedFile(page: Page, filePath: string) {
await page.locator('[data-testid="file-input"]').setInputFiles(filePath);
}
-const MODAL_TITLE = "Remove password to continue";
+const MODAL_TITLE = /^Unlock PDF/;
const PASSWORD_PLACEHOLDER = "Enter the PDF password";
-const UNLOCK_BUTTON_TEXT = "Unlock & Continue";
+const UNLOCK_BUTTON_TEXT = /^Unlock$/;
/**
* Fill the password field and wait until the modal has registered it: the
@@ -109,42 +95,317 @@ test.describe("Encrypted PDF Unlock Modal", () => {
}
});
+ test("Viewer Download preserves the original encrypted PDF", async ({
+ page,
+ }, testInfo) => {
+ const source = path.join(FIXTURES_DIR, "encrypted-ten-pages.pdf");
+ await mockUnlockSuccess(page, 10);
+ await uploadEncryptedFile(page, source);
+ await fillPassword(page, "james");
+ await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ await expect(page.locator('[data-page-index="0"] img').first()).toBeVisible(
+ { timeout: 30_000 },
+ );
+
+ const downloadPromise = page.waitForEvent("download");
+ await page
+ .getByRole("button", { name: /download|export/i })
+ .first()
+ .click();
+ const download = await downloadPromise;
+ const destination = testInfo.outputPath("protected-viewer-download.pdf");
+ await download.saveAs(destination);
+ expect(download.suggestedFilename()).toBe("encrypted-ten-pages.pdf");
+ expect(fs.readFileSync(destination)).toEqual(fs.readFileSync(source));
+ });
+
+ test("Split keeps ten protected results in a downloadable ZIP", async ({
+ page,
+ }, testInfo) => {
+ const plain = await PDFDocument.create();
+ for (let index = 0; index < 10; index++) plain.addPage([300, 400]);
+ const workingPdf = Buffer.from(await plain.save());
+ const singlePage = await PDFDocument.create();
+ singlePage.addPage([300, 400]);
+ const splitPage = await singlePage.save();
+ singlePage.encrypt({ userPassword: "james", ownerPassword: "james" });
+ const protectedPage = Buffer.from(await singlePage.save());
+ const zip = new JSZip();
+ for (let index = 1; index <= 10; index++)
+ zip.file(`page-${index}.pdf`, splitPage);
+ const splitZip = await zip.generateAsync({ type: "nodebuffer" });
+ const restoredNames: string[] = [];
+ await mockUnlockSuccess(page, 10);
+ await page.route("**/api/v1/security/remove-password", (route) =>
+ route.fulfill({ contentType: "application/pdf", body: workingPdf }),
+ );
+ await page.route(
+ "**/api/v1/general/split-by-size-or-count",
+ async (route) => {
+ const request = new Request(route.request().url(), {
+ method: "POST",
+ headers: route.request().headers(),
+ body: new Uint8Array(route.request().postDataBuffer()!),
+ });
+ const form = await request.formData();
+ expect(form.get("splitType")).toBe("1");
+ expect(form.get("splitValue")).toBe("1");
+ await route.fulfill({ contentType: "application/zip", body: splitZip });
+ },
+ );
+ await page.route(
+ "**/api/v1/security/restore-pdf-protection",
+ async (route) => {
+ const request = new Request(route.request().url(), {
+ method: "POST",
+ headers: route.request().headers(),
+ body: new Uint8Array(route.request().postDataBuffer()!),
+ });
+ const form = await request.formData();
+ expect(form.get("password")).toBe("james");
+ const source = form.get("sourceFile") as File;
+ expect(source.name).toBe("encrypted-ten-pages.pdf");
+ restoredNames.push((form.get("fileInput") as File).name);
+ await route.fulfill({
+ contentType: "application/pdf",
+ body: protectedPage,
+ });
+ },
+ );
+ await page.goto("/split?bypassOnboarding=true");
+ await uploadEncryptedFile(
+ page,
+ path.join(FIXTURES_DIR, "encrypted-ten-pages.pdf"),
+ );
+ await fillPassword(page, "james");
+ await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ await page
+ .getByText(/Page Count/i)
+ .first()
+ .click();
+ await page.getByPlaceholder("e.g. 5, 10").fill("1");
+ await page.getByRole("button", { name: "Split", exact: true }).click();
+ await expect.poll(() => restoredNames.length).toBe(10);
+ await page
+ .locator("label")
+ .filter({ hasText: /^Active Files$/ })
+ .click();
+ await expect(
+ page.getByText("result.zip", { exact: true }).first(),
+ ).toBeVisible();
+
+ const downloadPromise = page.waitForEvent("download");
+ await page
+ .getByRole("button", { name: /download|export/i })
+ .first()
+ .click();
+ const download = await downloadPromise;
+ const destination = testInfo.outputPath("protected-split.zip");
+ await download.saveAs(destination);
+ const downloadedZip = await JSZip.loadAsync(fs.readFileSync(destination));
+ const entries = Object.values(downloadedZip.files).filter(
+ (entry) => !entry.dir,
+ );
+ expect(entries).toHaveLength(10);
+ expect(entries.map((entry) => entry.name).sort()).toEqual(
+ restoredNames.sort(),
+ );
+ for (const entry of entries) {
+ const bytes = await entry.async("nodebuffer");
+ expect(bytes).toEqual(protectedPage);
+ await expect(PDFDocument.load(bytes)).rejects.toThrow(/encrypted/i);
+ const document = await PDFDocument.load(bytes, { password: "james" });
+ expect(document.getPageCount()).toBe(1);
+ }
+ });
+
test("modal renders with title, password input, and action buttons", async ({
page,
}) => {
await uploadEncryptedFile(page, ENCRYPTED_PDF);
- await expect(page.getByText(MODAL_TITLE)).toBeVisible({ timeout: 10000 });
+ 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);
+ 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();
+ await expect(
+ page.getByText("Unlock for this session.", { exact: true }),
+ ).toHaveCount(0);
+ const details = page.getByRole("heading").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 page.getByPlaceholder(PASSWORD_PLACEHOLDER).focus();
+ await expect(sessionDetails).toBeHidden();
+ });
+
+ test("Remove Password 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) => {
+ 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 expect(removePassword).toBeDisabled();
+ await fillPassword(page, "testpass123");
+ await expect(removePassword).toBeEnabled();
+ await removePassword.click();
+ await expect(dialog).toBeHidden();
+ await expect(
+ page.getByText("Unprotected copy created", { exact: true }),
+ ).toBeVisible();
+ await expect(page.locator('[data-page-index="0"] img').first()).toBeVisible(
+ { timeout: 30_000 },
+ );
+ expect(removals).toBe(1);
+ const stored = await page.evaluate(async () => {
+ const db = await new Promise<IDBDatabase>((resolve, reject) => {
+ const request = indexedDB.open("stirling-pdf-files");
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ const records = await new Promise<
+ Array<{
+ name: string;
+ isEncrypted: boolean;
+ data: Blob | ArrayBuffer;
+ }>
+ >((resolve, reject) => {
+ const request = db
+ .transaction("files", "readonly")
+ .objectStore("files")
+ .getAll();
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ db.close();
+ return Promise.all(
+ records.map(async (record) => {
+ const bytes =
+ record.data instanceof Blob
+ ? await record.data.arrayBuffer()
+ : record.data;
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
+ return {
+ name: record.name,
+ encrypted: record.isEncrypted,
+ hash: Array.from(new Uint8Array(digest), (byte) =>
+ byte.toString(16).padStart(2, "0"),
+ ).join(""),
+ };
+ }),
+ );
+ });
+ expect(stored).toEqual(
+ expect.arrayContaining([
+ {
+ name: "encrypted.pdf",
+ encrypted: true,
+ hash: createHash("sha256")
+ .update(fs.readFileSync(ENCRYPTED_PDF))
+ .digest("hex"),
+ },
+ {
+ name: "encrypted_unprotected.pdf",
+ encrypted: false,
+ hash: createHash("sha256").update(sample).digest("hex"),
+ },
+ ]),
+ );
});
test("successful unlock removes the modal and shows success alert", async ({
page,
}) => {
- await mockRemovePasswordSuccess(page);
+ test.setTimeout(90_000);
+ const removalRequests: string[] = [];
+ page.on("request", (request) => {
+ if (request.url().includes("/security/remove-password"))
+ removalRequests.push(request.url());
+ });
+ await mockUnlockSuccess(page);
await uploadEncryptedFile(page, ENCRYPTED_PDF);
- await expect(page.getByText(MODAL_TITLE)).toBeVisible({ timeout: 10000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible({ timeout: 10000 });
await fillPassword(page, "testpass123");
await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
- await expect(page.getByText(MODAL_TITLE)).toBeHidden({ timeout: 10000 });
await expect(
- page.getByText("Password removed", { exact: true }),
- ).toBeVisible({ timeout: 5000 });
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden({ timeout: 10000 });
+ await expect(page.getByText("PDF unlocked", { exact: true })).toBeVisible({
+ timeout: 5000,
+ });
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 45000,
+ });
+ const renderedPage = page.locator('[data-page-index="0"] img').first();
+ await expect(renderedPage).toBeVisible({ timeout: 15000 });
+ await expect
+ .poll(() =>
+ renderedPage.evaluate(
+ (element: HTMLImageElement) => element.naturalWidth,
+ ),
+ )
+ .toBeGreaterThan(0);
+ expect(removalRequests).toEqual([]);
+ await page
+ .locator("label")
+ .filter({ hasText: /^Active Files$/ })
+ .click();
+ const unlockedIndicator = page
+ .getByTestId("file-thumbnail")
+ .getByRole("img", { name: "PDF unlocked", exact: true });
+ await expect(unlockedIndicator).toBeVisible();
+ await unlockedIndicator.hover();
+ await expect(page.getByRole("tooltip")).toHaveText(
+ "Unlocked for this session. Password protection is retained.",
+ );
});
test("incorrect password keeps the modal open with an inline error", async ({
page,
}) => {
- await mockRemovePasswordWrongPassword(page);
+ await mockUnlockWrongPassword(page);
await uploadEncryptedFile(page, ENCRYPTED_PDF);
- await expect(page.getByText(MODAL_TITLE)).toBeVisible({ timeout: 10000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible({ timeout: 10000 });
await fillPassword(page, "wrongpassword");
await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
@@ -152,27 +413,152 @@ test.describe("Encrypted PDF Unlock Modal", () => {
await expect(page.getByText("Incorrect password")).toBeVisible({
timeout: 5000,
});
- await expect(page.getByText(MODAL_TITLE)).toBeVisible();
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible();
+ });
+
+ test("unsupported tools show the protected file with details in a tooltip", async ({
+ page,
+ }) => {
+ await page.route("**/api/v1/ui-data/ocr-pdf", (route) =>
+ route.fulfill({ json: { languages: ["eng"] } }),
+ );
+ await page.goto("/ocr");
+ await mockUnlockSuccess(page);
+ await uploadEncryptedFile(page, ENCRYPTED_PDF);
+ await fillPassword(page, "testpass123");
+ await page.getByRole("button", { name: UNLOCK_BUTTON_TEXT }).click();
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden();
+ const notice = page.getByTestId("tool-file-list");
+ await expect(notice.getByRole("listitem")).toHaveText("encrypted.pdf");
+ await expect(notice.getByText(/Add files to the workbench/)).toHaveCount(0);
+ await notice
+ .getByRole("button", { name: "Why encrypted.pdf is unavailable" })
+ .hover();
+ const details = page.getByRole("tooltip").filter({
+ hasText:
+ "This tool doesn't support encrypted PDFs. Remove the password first.",
+ });
+ 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" });
+ await removePassword.hover();
+ await expect(
+ page.getByRole("tooltip").filter({
+ hasText: "Open Remove Password to create an unprotected copy.",
+ }),
+ ).toBeVisible();
+ 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();
});
+ for (const legacy of [false, true]) {
+ test(`cached protected previews stay hidden after reload${legacy ? " for legacy records" : ""}`, async ({
+ page,
+ }) => {
+ await uploadEncryptedFile(page, ENCRYPTED_PDF);
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible();
+ await expect(page.locator('[data-page-index="0"]')).toHaveCount(0);
+ await expect(
+ page.getByRole("button", { name: "Skip for now" }),
+ ).toHaveCount(0);
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Close", exact: true })
+ .click();
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden();
+ await expect
+ .poll(() =>
+ page.evaluate(async (legacyRecord) => {
+ const db = await new Promise<IDBDatabase>((resolve, reject) => {
+ const request = indexedDB.open("stirling-pdf-files");
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ const found = await new Promise<boolean>((resolve, reject) => {
+ const transaction = db.transaction("files", "readwrite");
+ const store = transaction.objectStore("files");
+ let saved = false;
+ const request = store.getAll();
+ request.onsuccess = () => {
+ for (const record of request.result) {
+ if (record.name !== "encrypted.pdf") continue;
+ record.thumbnail =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==";
+ record.thumbnailStoredAt = Date.now();
+ if (legacyRecord) delete record.isEncrypted;
+ else record.isEncrypted = true;
+ store.put(record);
+ saved = true;
+ }
+ };
+ transaction.oncomplete = () => resolve(saved);
+ transaction.onerror = () => reject(transaction.error);
+ });
+ db.close();
+ return found;
+ }, legacy),
+ )
+ .toBe(true);
+ await page.goto("/files");
+ await page.getByRole("button", { name: "Recents", exact: true }).click();
+ await page
+ .locator('.files-page-view-toggle-icon[title="Grid view"]')
+ .click();
+ const card = page.locator('.files-page-card[aria-label="encrypted.pdf"]');
+ await expect(card).toBeVisible();
+ await expect(card.locator("img")).toHaveCount(0);
+ await card.dblclick();
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible();
+ await expect(page.locator('[data-page-index="0"]')).toHaveCount(0);
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Close", exact: true })
+ .click();
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden();
+ });
+ }
+
test("pressing Enter in the password field triggers unlock", async ({
page,
}) => {
- await mockRemovePasswordSuccess(page);
+ await mockUnlockSuccess(page);
await uploadEncryptedFile(page, ENCRYPTED_PDF);
- await expect(page.getByText(MODAL_TITLE)).toBeVisible({ timeout: 10000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible({ timeout: 10000 });
await fillPassword(page, "testpass123");
await page.getByPlaceholder(PASSWORD_PLACEHOLDER).press("Enter");
- await expect(page.getByText(MODAL_TITLE)).toBeHidden({ timeout: 10000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden({ timeout: 10000 });
});
test("multi-file unlock-all closes the modal after one password entry", async ({
page,
}) => {
- await mockRemovePasswordSuccess(page);
+ await mockUnlockSuccess(page);
// `files-button`'s native picker is mocked globally; click it, then set
// the files on the hidden input directly.
@@ -190,7 +576,9 @@ test.describe("Encrypted PDF Unlock Modal", () => {
},
]);
- await expect(page.getByText(MODAL_TITLE)).toBeVisible({ timeout: 15000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeVisible({ timeout: 15000 });
// The "Use for all" affordance only appears once BOTH files have been
// detected as encrypted. PDF.js encryption probing runs per-file and
// can lag the modal opening (which fires as soon as the first file
@@ -202,6 +590,8 @@ test.describe("Encrypted PDF Unlock Modal", () => {
await fillPassword(page, "testpass123");
await unlockAllBtn.click();
- await expect(page.getByText(MODAL_TITLE)).toBeHidden({ timeout: 15000 });
+ await expect(
+ page.getByRole("heading", { name: MODAL_TITLE, exact: true }),
+ ).toBeHidden({ timeout: 15000 });
});
});
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
index 4ab05974e6..327d2bde4b 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
@@ -30,10 +30,154 @@ async function upload(page: Page, file: string): Promise<void> {
}
test.describe("PDF text editor - encrypted PDF password prompt", () => {
+ for (const protectedOutput of [true, false]) {
+ test(
+ protectedOutput
+ ? "reuses the session unlock when opening and saving a workbench PDF"
+ : "refuses to save or download an export that lost its protection",
+ async ({ page }) => {
+ await page.route("**/encode-charcodes", (route) => route.abort());
+ let inspections = 0;
+ await page.route("**/api/v1/security/inspect-pdf-security", (route) => {
+ inspections++;
+ return route.fulfill({
+ json: {
+ encrypted: inspections === 1 || protectedOutput,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ encryptionKeyLength: 256,
+ encryptionRevision: 6,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ },
+ });
+ });
+ await page.goto("/editor");
+ await page
+ .locator('[data-testid="file-input"]')
+ .setInputFiles(ENCRYPTED);
+ await page
+ .getByPlaceholder("Enter the PDF password")
+ .fill(ENCRYPTED_PASSWORD);
+ await page.getByRole("button", { name: "Unlock", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect(
+ page.getByTestId("pdf-editor-password-modal"),
+ ).toBeHidden();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ expect(inspections).toBe(1);
+
+ await page.evaluate(() => {
+ const run = document.querySelector<HTMLElement>(
+ '[data-testid^="pdf-editor-run-"]',
+ );
+ if (!run) throw new Error("Expected an editable text run");
+ run.focus();
+ const range = document.createRange();
+ range.selectNodeContents(run);
+ range.collapse(false);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ document.execCommand("insertText", false, " Test");
+ });
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+ await page.getByTestId("pdf-editor-download").click();
+ await expect(
+ page.getByTestId("pdf-editor-save-risk-modal"),
+ ).toContainText(/encryption/i);
+ if (!protectedOutput) {
+ const downloads: string[] = [];
+ page.on("download", (download) =>
+ downloads.push(download.suggestedFilename()),
+ );
+ await page.getByTestId("pdf-editor-save-risk-confirm").click();
+ await expect(
+ page.getByText(
+ "Unable to preserve PDF protection. No unprotected result was saved.",
+ ),
+ ).toBeVisible();
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+ expect(downloads).toEqual([]);
+ expect(inspections).toBe(2);
+ return;
+ }
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-save-risk-confirm").click();
+ const download = await downloadPromise;
+ expect(download.suggestedFilename()).toBe("encrypted_edited.pdf");
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden();
+ expect(inspections).toBe(2);
+ },
+ );
+ }
+
+ test("keeps an unlocked signed PDF out of the text editor", async ({
+ page,
+ }) => {
+ await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
+ route.fulfill({
+ json: {
+ encrypted: true,
+ signed: true,
+ ownerAuthenticated: true,
+ permissions: -4,
+ encryptionKeyLength: 256,
+ encryptionRevision: 6,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ },
+ }),
+ );
+ await page.goto("/editor");
+ await page.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);
+ await page
+ .getByPlaceholder("Enter the PDF password")
+ .fill(ENCRYPTED_PASSWORD);
+ await page.getByRole("button", { name: "Unlock", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await expect(
+ page.getByText(
+ /Session unlocking supports viewing it, but processing signed PDFs is not supported yet/,
+ ),
+ ).toBeVisible();
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ });
+
test("wrong password re-prompts, correct password opens the document", async ({
page,
}) => {
test.setTimeout(90_000);
+ await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
+ route.fulfill({
+ json: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ encryptionKeyLength: 256,
+ encryptionRevision: 6,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ },
+ }),
+ );
await gotoEditor(page);
await upload(page, ENCRYPTED);
@@ -65,17 +209,17 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {
await expect(page.getByRole("dialog")).toHaveCount(0);
});
- test("cancel dismisses the prompt without loading a document", async ({
+ test("closing the unlock prompt does not load a document", async ({
page,
}) => {
test.setTimeout(60_000);
await gotoEditor(page);
await upload(page, ENCRYPTED);
- const cancel = page.getByTestId("pdf-editor-password-cancel");
- await expect(cancel).toBeVisible({ timeout: 20_000 });
- await cancel.click();
- await expect(cancel).toBeHidden();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible({ timeout: 20_000 });
+ await dialog.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(dialog).toBeHidden();
expect(await page.getByTestId("pdf-editor-page-0").count()).toBe(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.ts
new file mode 100644
index 0000000000..d0bbea2c61
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
@@ -0,0 +1,84 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
+import path from "path";
+
+// qpdf --encrypt scan-password scan-password 256 -- scanned-no-ocr.pdf scanned-no-ocr-encrypted.pdf
+const SCAN = path.join(
+ import.meta.dirname,
+ "../test-fixtures/scanned-no-ocr-encrypted.pdf",
+);
+
+for (const source of ["workbench", "disk"] as const) {
+ test(`unlocked ${source} scan explains OCR and offers Remove Password`, async ({
+ page,
+ }) => {
+ const ocrRequests: string[] = [];
+ page.on("request", (request) => {
+ if (request.url().includes("/api/v1/misc/ocr-pdf"))
+ ocrRequests.push(request.url());
+ });
+ await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
+ route.fulfill({
+ json: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ encryptionKeyLength: 256,
+ encryptionRevision: 6,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ },
+ }),
+ );
+ if (source === "workbench") {
+ await page.goto("/editor");
+ await page.getByTestId("file-input").setInputFiles(SCAN);
+ await page
+ .getByPlaceholder("Enter the PDF password")
+ .fill("scan-password");
+ await page.getByRole("button", { name: "Unlock", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ } else {
+ await page.goto("/pdf-text-editor");
+ await page.getByTestId("pdf-editor-file-input").setInputFiles(SCAN);
+ await page
+ .getByTestId("pdf-editor-password-modal")
+ .locator("input")
+ .first()
+ .fill("scan-password");
+ await page.getByTestId("pdf-editor-password-submit").click();
+ }
+ await waitForEditorReady(page);
+ const hint = page.getByTestId("pdf-editor-scan-hint");
+ const ocr = hint.getByRole("button", { name: "Run OCR", exact: true });
+ 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.",
+ );
+ await expect(ocr).toHaveAccessibleDescription(/password protection/);
+ const removePassword = hint.getByRole("button", {
+ name: "Remove Password",
+ exact: true,
+ });
+ await expect(removePassword).toBeVisible();
+ await page.getByTestId("pdf-editor-root").screenshot({
+ path: test.info().outputPath("protected-ocr-sidebar.png"),
+ });
+ 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/pdf-text-editor-table-roundtrip.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
index c5a1b7e56c..c9aa440a35 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
@@ -1,4 +1,6 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import { mockAppApis } from "@app/tests/helpers/api-stubs";
import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
import { readFileSync } from "node:fs";
import path from "node:path";
@@ -14,6 +16,34 @@ const corpus: string[] = process.env.PDF_TABLE_CORPUS
test.use({ autoGoto: false });
+async function waitForFirstPage(page: Page): Promise<void> {
+ await page.waitForFunction(
+ () => {
+ const store = (window as unknown as { __editor_store?: EditorStore })
+ .__editor_store;
+ return store?.getState().firstPageRendered && !store.getState().loading;
+ },
+ undefined,
+ { timeout: 30_000 },
+ );
+}
+
+async function reopenExport(
+ page: Page,
+ saved: string,
+ errors?: string[],
+): Promise<Page> {
+ // A fresh tab isolates exported bytes from the original editor and avoids
+ // WebKit's page-teardown errors from interrupted thumbnail blob reads.
+ const reopened = await page.context().newPage();
+ if (errors) reopened.on("pageerror", (error) => errors.push(error.message));
+ await mockAppApis(reopened);
+ await reopened.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await reopened.getByTestId("pdf-editor-file-input").setInputFiles(saved);
+ await waitForFirstPage(reopened);
+ return reopened;
+}
+
function readMergedTable() {
const store = (window as unknown as { __editor_store: EditorStore })
.__editor_store;
@@ -71,11 +101,7 @@ test("merged cells retain their borders after a structural edit and export", asy
"../test-fixtures/merged-table-sample.pdf",
),
);
- await page.waitForFunction(() => {
- const store = (window as unknown as { __editor_store: EditorStore })
- .__editor_store;
- return store.getState().firstPageRendered && !store.getState().loading;
- });
+ await waitForFirstPage(page);
await page
.locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
.first()
@@ -121,18 +147,12 @@ test("merged cells retain their borders after a structural edit and export", asy
path: saved,
contentType: "application/pdf",
});
- await page.reload({ waitUntil: "domcontentloaded" });
- await page.getByTestId("pdf-editor-file-input").setInputFiles(saved);
- await page.waitForFunction(() => {
- const store = (window as unknown as { __editor_store: EditorStore })
- .__editor_store;
- return store.getState().firstPageRendered && !store.getState().loading;
- });
- await page
+ const reopenedPage = await reopenExport(page, saved);
+ await reopenedPage
.locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
.first()
.click();
- const reopened = await page.evaluate(readMergedTable);
+ const reopened = await reopenedPage.evaluate(readMergedTable);
expect({ rows: reopened.rows, cols: reopened.cols }).toEqual({
rows: 8,
cols: 5,
@@ -147,7 +167,7 @@ test("merged cells retain their borders after a structural edit and export", asy
).toEqual(expectedSpans);
for (const span of reopened.spans)
expectNoRulesInside(span.rect, reopened.rules);
- await page.screenshot({
+ await reopenedPage.screenshot({
path: testInfo.outputPath("merged-reopened.png"),
fullPage: true,
});
@@ -167,11 +187,7 @@ for (const file of [fixture, ...corpus]) {
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
- await page.waitForFunction(() => {
- const store = (window as unknown as { __editor_store: EditorStore })
- .__editor_store;
- return store.getState().firstPageRendered && !store.getState().loading;
- });
+ await waitForFirstPage(page);
const contentBefore = await page.evaluate(() => {
const store = (window as unknown as { __editor_store: EditorStore })
.__editor_store;
@@ -248,20 +264,8 @@ for (const file of [fixture, ...corpus]) {
path: saved,
contentType: "application/pdf",
});
- // WebKit reports the old page's blob reads cut off by the reload as errors.
- page.off("pageerror", onPageError);
- await page.reload({ waitUntil: "domcontentloaded" });
- page.on("pageerror", onPageError);
- await page.getByTestId("pdf-editor-file-input").setInputFiles(saved);
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
- });
- await page.waitForFunction(() => {
- const store = (window as unknown as { __editor_store: EditorStore })
- .__editor_store;
- return store.getState().firstPageRendered && !store.getState().loading;
- });
- const contentAfter = await page.evaluate(() => {
+ const reopenedPage = await reopenExport(page, saved, errors);
+ const contentAfter = await reopenedPage.evaluate(() => {
const store = (window as unknown as { __editor_store: EditorStore })
.__editor_store;
return store.getState().pages.map((p) => ({
@@ -276,8 +280,8 @@ for (const file of [fixture, ...corpus]) {
}));
});
expect(contentAfter).toEqual(contentBefore);
- await expect(page.getByTestId("pdf-editor-error")).toHaveCount(0);
- await page.screenshot({
+ await expect(reopenedPage.getByTestId("pdf-editor-error")).toHaveCount(0);
+ await reopenedPage.screenshot({
path: testInfo.outputPath("reopened.png"),
fullPage: true,
});
diff --git a/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts
new file mode 100644
index 0000000000..7cbebec89f
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/unlocked-pdf-annotations.spec.ts
@@ -0,0 +1,132 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "node:path";
+
+const fixtures = path.join(import.meta.dirname, "../test-fixtures");
+
+async function unlockFixture(page: Page, filename: string, pageCount: number) {
+ await page.route("**/api/v1/security/inspect-pdf-security", (route) =>
+ route.fulfill({
+ json: {
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount,
+ },
+ }),
+ );
+ await page.goto("/annotate", { waitUntil: "domcontentloaded" });
+ await page.getByTestId("files-button").click();
+ await page
+ .getByTestId("file-input")
+ .setInputFiles(path.join(fixtures, filename));
+ const dialog = page.getByRole("dialog");
+ await expect(async () => {
+ await dialog
+ .getByPlaceholder("Enter the PDF password")
+ .fill("annotation-test");
+ await expect(
+ dialog.getByRole("button", { name: "Unlock", exact: true }),
+ ).toBeEnabled({ timeout: 1000 });
+ }).toPass();
+ await dialog.getByRole("button", { name: "Unlock", exact: true }).click();
+ await expect(dialog).toBeHidden();
+}
+
+test("unlocked annotations render before opening comments and remain read-only", async ({
+ page,
+}) => {
+ await unlockFixture(page, "encrypted-annotations.pdf", 3);
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ const annotations = firstPage.locator("[data-no-interaction]");
+ await expect(annotations).toHaveCount(4, { timeout: 30_000 });
+ await expect(annotations.first().locator("img")).toBeVisible();
+ await expect
+ .poll(() =>
+ annotations
+ .locator("img")
+ .evaluateAll((images: HTMLImageElement[]) =>
+ images.every((image) => image.complete && image.naturalWidth > 0),
+ ),
+ )
+ .toBe(true);
+ await expect(
+ page.getByRole("button", { name: "Highlight", exact: true }),
+ ).toHaveCount(0);
+ await expect(
+ page.getByRole("button", { name: "Remove Password", exact: true }),
+ ).toBeVisible();
+
+ await page.getByRole("button", { name: "Comments", exact: true }).click();
+ const comments = page.locator(".comments-sidebar");
+ await expect(comments).toBeVisible();
+ await expect(comments.locator("[data-comment-card]")).toHaveCount(12);
+ await expect(comments).toContainText("Annotation A on page 1");
+ await expect(
+ comments.locator("textarea, input:not([placeholder='Search comments'])"),
+ ).toHaveCount(0);
+ await expect(
+ comments.getByRole("button", { name: /More actions|Add comment/ }),
+ ).toHaveCount(0);
+ await comments
+ .getByRole("button", { name: "Locate in document" })
+ .first()
+ .click();
+ await expect(page.locator("[data-annotation-selection-menu]")).toHaveCount(0);
+ await page.keyboard.press("Delete");
+ await expect(comments.locator("[data-comment-card]")).toHaveCount(12);
+ await comments
+ .getByRole("button", { name: "Close comments sidebar" })
+ .click();
+ await expect(comments).toBeHidden();
+ await expect(annotations).toHaveCount(4);
+ await page.getByRole("button", { name: "Comments", exact: true }).click();
+ await expect(comments).toBeVisible();
+ await expect(comments.locator("[data-comment-card]")).toHaveCount(12);
+
+ await page.getByTestId("files-button").click();
+ await page
+ .getByTestId("file-input")
+ .setInputFiles(path.join(fixtures, "annotations_out_of_order.pdf"));
+ await expect(
+ page.getByRole("button", { name: "Highlight", exact: true }),
+ ).toBeVisible();
+ await expect(comments.getByPlaceholder("Add reply...").first()).toBeVisible();
+ await expect(
+ comments.getByRole("button", { name: "More actions" }).first(),
+ ).toBeVisible();
+});
+
+test("unlocked links remain navigable and text selection only offers copying", async ({
+ page,
+}) => {
+ await unlockFixture(page, "encrypted-links.pdf", 2);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ const links = firstPage.locator(".pdf-link-overlay");
+ await expect(links).toHaveCount(4, { timeout: 30_000 });
+ await links.first().hover();
+ const linkToolbar = page.locator(".pdf-link-toolbar");
+ await expect(linkToolbar).toBeVisible();
+ await expect(
+ linkToolbar.getByRole("button", { name: "Delete link" }),
+ ).toHaveCount(0);
+ await expect(linkToolbar.locator(".pdf-link-toolbar-btn--go")).toBeEnabled();
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("PDF page has no bounds");
+ const y = box.y + box.height * 0.042;
+ await page.mouse.move(box.x + box.width * 0.065, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.6, y, { steps: 15 });
+ await page.mouse.up();
+ const selectionMenu = page.locator("[data-text-selection-menu]");
+ await expect(selectionMenu).toBeVisible();
+ await expect(
+ selectionMenu.getByRole("button", { name: "Copy", exact: true }),
+ ).toBeVisible();
+ await expect(selectionMenu.getByRole("button")).toHaveCount(1);
+});
diff --git a/frontend/editor/src/core/tests/test-fixtures/README.md b/frontend/editor/src/core/tests/test-fixtures/README.md
index 079bd401d0..4b4920abda 100644
--- a/frontend/editor/src/core/tests/test-fixtures/README.md
+++ b/frontend/editor/src/core/tests/test-fixtures/README.md
@@ -2,6 +2,15 @@
This directory contains sample files for testing the convert tool functionality.
+## Encrypted annotation fixtures
+
+`encrypted-annotations.pdf` and `encrypted-links.pdf` use `annotation-test` as both the user and owner password. They preserve the comments and links from the corresponding unprotected fixtures. Regenerate them with qpdf:
+
+```sh
+qpdf --encrypt annotation-test annotation-test 256 -- annotations_out_of_order.pdf encrypted-annotations.pdf
+qpdf --encrypt annotation-test annotation-test 256 -- link-annotations-sample.pdf encrypted-links.pdf
+```
+
## Required Test Files
To run the full test suite, please add the following test files to this directory:
@@ -129,4 +138,4 @@ These are test files only and should not contain any sensitive information. They
When updating the convert tool with new formats:
1. Add corresponding test files to this directory
2. Update the test files list above
-3. Update the test cases to include the new formats
\ No newline at end of file
+3. Update the test cases to include the new formats
diff --git a/frontend/editor/src/core/tests/test-fixtures/encrypted-annotations.pdf b/frontend/editor/src/core/tests/test-fixtures/encrypted-annotations.pdf
new file mode 100644
index 0000000000..2e4f7ffa48
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/encrypted-annotations.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/encrypted-links.pdf b/frontend/editor/src/core/tests/test-fixtures/encrypted-links.pdf
new file mode 100644
index 0000000000..4828b53df7
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/encrypted-links.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/encrypted-ten-pages.pdf b/frontend/editor/src/core/tests/test-fixtures/encrypted-ten-pages.pdf
new file mode 100644
index 0000000000..e6d3aafff4
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/encrypted-ten-pages.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/scanned-no-ocr-encrypted.pdf b/frontend/editor/src/core/tests/test-fixtures/scanned-no-ocr-encrypted.pdf
new file mode 100644
index 0000000000..349eae627a
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/scanned-no-ocr-encrypted.pdf differ
diff --git a/frontend/editor/src/core/tools/Annotate.tsx b/frontend/editor/src/core/tools/Annotate.tsx
index e2df10b4d4..b35cb4b6c7 100644
--- a/frontend/editor/src/core/tools/Annotate.tsx
+++ b/frontend/editor/src/core/tools/Annotate.tsx
@@ -4,7 +4,9 @@ import { useTranslation } from "react-i18next";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import { useNavigation } from "@app/contexts/NavigationContext";
-import { useAllFiles } from "@app/contexts/FileContext";
+import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
import { BaseToolProps } from "@app/types/tool";
import { useSignature } from "@app/contexts/SignatureContext";
import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";
@@ -77,7 +79,11 @@ const Annotate = (_props: BaseToolProps) => {
const { t } = useTranslation();
const { selectedTool, workbench, hasUnsavedChanges, setHasUnsavedChanges } =
useNavigation();
- const { files: allFiles } = useAllFiles();
+ const scopedFiles = useViewScopedFiles();
+ usePdfAccess(undefined);
+ const editableFiles = scopedFiles.filter(
+ (file) => !getPdfAccess(file)?.encrypted,
+ );
const {
signatureApiRef,
annotationApiRef,
@@ -347,6 +353,7 @@ const Annotate = (_props: BaseToolProps) => {
}, [activeFileIndex, activeTool, setPlacementMode, setSignatureConfig]);
const activateAnnotationTool = (toolId: AnnotationToolId) => {
+ if (editableFiles.length === 0) return;
// If leaving stamp tool, clean up placement mode
if (activeTool === "stamp" && toolId !== "stamp") {
setPlacementMode(false);
@@ -808,7 +815,7 @@ const Annotate = (_props: BaseToolProps) => {
]);
const steps =
- allFiles.length === 0
+ editableFiles.length === 0
? []
: [
{
@@ -852,7 +859,7 @@ const Annotate = (_props: BaseToolProps) => {
];
return createToolFlow({
files: {
- selectedFiles: allFiles,
+ selectedFiles: editableFiles,
isCollapsed: false,
},
steps,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
index 7d2a33dfdf..c80d243249 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -7,8 +7,18 @@ import { Alert, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { downloadFile } from "@app/services/downloadService";
+import {
+ assertPdfSessionEditable,
+ unlockPdfForSession,
+ verifyEditedPdfProtection,
+} from "@app/services/pdfSessionUnlock";
+import {
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
import { useFileContext, useFileSelection } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
+import { useToolWorkflowActions } from "@app/contexts/ToolWorkflowContext";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import type { FileId } from "@app/types/file";
import type { ToolId } from "@app/types/toolId";
@@ -44,6 +54,7 @@ import { jpegExifOrientation } from "@app/utils/jpegOrientation";
import { MergeRunsCommand } from "@app/tools/pdfTextEditor/commands/MergeRunsCommand";
import { UngroupParagraphCommand } from "@app/tools/pdfTextEditor/commands/UngroupParagraphCommand";
import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";
+import { assertEditorOcrAllowed } from "@app/tools/pdfTextEditor/util/ocrProtection";
import { clampRenderScale } from "@app/tools/pdfTextEditor/util/fitToWidth";
import {
detectSaveRisks,
@@ -94,6 +105,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
}, []);
const { addFiles, consumeFiles, selectors } = useFileContext();
const { setSelectedFiles } = useFileSelection();
+ const { handleToolSelect } = useToolWorkflowActions();
// Saving replaces the workbench file, so for a moment the selection points at
// a file the editor has not adopted yet. Auto-load must sit that out.
const [applying, setApplying] = useState(false);
@@ -125,13 +137,11 @@ export default function PdfTextEditor(_props: BaseToolProps) {
},
[pinWorkbench, setSourceFile, store],
);
- const { openFile: openWorkbenchFile, adopt: adoptFile } = useAutoLoadFile(
- load,
- handleFileChosen,
- sourceFileId,
- applying,
- state,
- );
+ const {
+ openFile: openWorkbenchFile,
+ adopt: adoptFile,
+ cancel: cancelAutoLoad,
+ } = useAutoLoadFile(load, handleFileChosen, sourceFileId, applying, state);
useEffect(() => store.selection.subscribe(setSelection), [store]);
@@ -171,6 +181,12 @@ export default function PdfTextEditor(_props: BaseToolProps) {
assertFilesNotBlocked(policyIds);
setApplying(true);
try {
+ if (toolId === "ocr")
+ assertEditorOcrAllowed(store.document, sourceId, t);
+ const sourceAccess = getPdfAccess(sourceId);
+ if (toolId === "pdfTextEditor" && sourceAccess?.encrypted) {
+ await verifyEditedPdfProtection(edited, sourceAccess);
+ }
if (sourceId && parentStub) {
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(
[edited],
@@ -179,6 +195,8 @@ export default function PdfTextEditor(_props: BaseToolProps) {
);
if (!isCurrent()) return null;
assertFilesNotBlocked(policyIds);
+ if (toolId === "ocr")
+ assertEditorOcrAllowed(store.document, sourceId, t);
await consumeFiles([sourceId], stirlingFiles, stubs);
// Claim the replacement before releasing the hold, otherwise the
// editor sees an unfamiliar selection and re-opens the file it just
@@ -203,7 +221,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
setApplying(false);
}
},
- [addFiles, adoptFile, consumeFiles, selectors, setSourceFile],
+ [addFiles, adoptFile, consumeFiles, selectors, setSourceFile, store, t],
);
const applyOcrResult = useCallback(
@@ -234,6 +252,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const sourceId = sourceFileIdRef.current;
try {
assertFilesNotBlocked([sourceId ?? undefined]);
+ assertPdfSessionEditable(getPdfAccess(sourceId));
// Yield once so React can paint the disabled/saving state before the
// synchronous PDFium serialize blocks the main thread.
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -247,11 +266,12 @@ export default function PdfTextEditor(_props: BaseToolProps) {
// Apply first and unconditionally. Gating the write-back on the browser
// download dialog meant cancelling it silently discarded the save.
assertFilesNotBlocked([sourceId ?? undefined]);
- await applyToWorkbench(blob, filename);
+ const saved = await applyToWorkbench(blob, filename);
+ if (!saved) return;
store.markSaved(exported);
if (download) {
assertFilesNotBlocked([sourceId ?? undefined]);
- await downloadFile({ data: blob, filename });
+ await downloadFile({ data: saved, filename });
}
} catch (err) {
// Surface the failure instead of silently dropping it - the user
@@ -567,14 +587,18 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const loading = load(file, password);
const token = store.currentLoadToken;
void loading
- .then(() => {
+ .then(async () => {
if (!mountedRef.current || !store.isCurrentLoad(token)) return null;
const opened = store.getState();
if (!opened.hasDocument || opened.error || opened.passwordPrompt)
return null;
+ if (password !== undefined) {
+ const access = await unlockPdfForSession(file, password);
+ if (!mountedRef.current || !store.isCurrentLoad(token)) return null;
+ rememberPdfAccess(file, access);
+ }
return addFiles([file], {
selectFiles: false,
- skipAutomaticPasswordPrompt: password !== undefined,
});
})
.then((added) => {
@@ -687,9 +711,11 @@ export default function PdfTextEditor(_props: BaseToolProps) {
);
const handleCancelPassword = useCallback(() => {
+ const file = store.pendingPasswordFile;
+ if (file) cancelAutoLoad(file);
pendingDiskFileRef.current = null;
store.clearPasswordPrompt();
- }, [store]);
+ }, [store, cancelAutoLoad]);
const sidebarProps = {
store,
@@ -707,6 +733,13 @@ export default function PdfTextEditor(_props: BaseToolProps) {
},
ocrRunning: ocr.running,
ocrAvailable: state.loading && !ocr.running ? null : ocr.available,
+ ocrBlockedReason: ocr.blockedReason,
+ onRemovePassword: sourceFileId
+ ? () => {
+ setSelectedFiles([sourceFileId]);
+ handleToolSelect("removePassword");
+ }
+ : undefined,
};
return (
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/documentRisks.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/documentRisks.test.ts
index c1a38b3062..89e1a44ba9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/documentRisks.test.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/documentRisks.test.ts
@@ -115,7 +115,7 @@ describe("detectSaveRisks", () => {
expect(r.encrypted).toBe(true);
expect(hasSaveRisks(r)).toBe(true);
expect(describeSaveRisks(r)).toContain(
- "This PDF is encrypted; the saved copy will NOT be encrypted (password and access restrictions are removed).",
+ "Saving this PDF may change its encryption or access restrictions.",
);
expect(detectSaveRisks(mkDoc({ throwOnEncrypt: true })).encrypted).toBe(
false,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 6e6d4802a9..ecf1bb5fac 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -52,6 +52,8 @@ export function EditorSidebar({
onRunOcr,
ocrRunning,
ocrAvailable,
+ ocrBlockedReason,
+ onRemovePassword,
initialTab = "selected",
}: SidebarProps) {
const { t } = useTranslation();
@@ -129,6 +131,8 @@ export function EditorSidebar({
onRunOcr={onRunOcr}
ocrRunning={ocrRunning}
ocrAvailable={ocrAvailable}
+ ocrBlockedReason={ocrBlockedReason}
+ onRemovePassword={onRemovePassword}
/>
)}
</Tabs.Panel>
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.test.tsx
index a21ece45fd..2b00c8a1ca 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,7 @@ describe("password retry dismissal", () => {
</MantineProvider>
);
const { rerender } = render(modal(true));
- expect(screen.getByTestId("pdf-editor-password-cancel")).toBeDisabled();
+ expect(screen.queryByTestId("pdf-editor-password-cancel")).toBeNull();
expect(document.querySelector(".mantine-Modal-close")).toBeNull();
fireEvent.keyDown(document.body, { key: "Escape" });
const overlay = document.querySelector(".mantine-Modal-overlay");
@@ -27,8 +27,8 @@ describe("password retry dismissal", () => {
expect(onCancel).not.toHaveBeenCalled();
rerender(modal(false));
- expect(screen.getByTestId("pdf-editor-password-cancel")).toBeEnabled();
- fireEvent.click(document.querySelector(".mantine-Modal-close")!);
+ expect(screen.getByRole("button", { name: /^close$/i })).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: /^close$/i }));
expect(onCancel).toHaveBeenCalledTimes(1);
fireEvent.keyDown(document.body, { key: "Escape" });
expect(onCancel).toHaveBeenCalledTimes(2);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
index 56982dc151..6a516ee606 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
@@ -1,19 +1,15 @@
import { useEffect, useState } from "react";
-import { Modal, Stack, Text, Group, PasswordInput } from "@mantine/core";
-import { Button } from "@app/ui/Button";
import { useTranslation } from "react-i18next";
+import EncryptedPdfUnlockModal from "@app/components/shared/EncryptedPdfUnlockModal";
interface PasswordPromptModalProps {
/** Non-null opens the modal; null keeps it closed. */
prompt: { fileName: string; retry: boolean } | null;
- /** True while a retry load is running, so inputs disable. */
loading: boolean;
onSubmit: (password: string) => void;
onCancel: () => void;
}
-// Asks the user for a password to open an encrypted PDF, then retries the load.
-// `prompt.retry` means the previous password was wrong.
export function PasswordPromptModal({
prompt,
loading,
@@ -22,81 +18,31 @@ export function PasswordPromptModal({
}: PasswordPromptModalProps) {
const { t } = useTranslation();
const [password, setPassword] = useState("");
-
- // Clear the field whenever the prompt opens/closes so a new file (or a
- // wrong-password reprompt) never shows the previous attempt.
useEffect(() => {
setPassword("");
}, [prompt?.fileName, prompt?.retry]);
- const submit = () => {
- if (!password || loading) return;
- onSubmit(password);
- };
-
return (
- <Modal
+ <EncryptedPdfUnlockModal
opened={!!prompt}
- onClose={onCancel}
- withCloseButton={!loading}
- closeOnEscape={!loading}
- closeOnClickOutside={!loading}
- title={t("pdfTextEditor.password.title", "Password required")}
- size="sm"
- data-testid="pdf-editor-password-modal"
- >
- <Stack gap="md">
- <Text size="sm">
- {prompt?.fileName
- ? t(
- "pdfTextEditor.password.protectedNamed",
- '"{{fileName}}" is password-protected.',
- { fileName: prompt.fileName },
- )
- : t(
- "pdfTextEditor.password.protected",
- "This PDF is password-protected.",
- )}
- </Text>
- <PasswordInput
- label={t("pdfTextEditor.password.label", "Password")}
- value={password}
- onChange={(e) => setPassword(e.currentTarget.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") submit();
- }}
- error={
- prompt?.retry
- ? t(
- "pdfTextEditor.password.incorrect",
- "Incorrect password - try again.",
- )
- : undefined
- }
- disabled={loading}
- data-autofocus
- data-testid="pdf-editor-password-input"
- />
- <Group justify="flex-end" gap="sm">
- <Button
- variant="secondary"
- accent="neutral"
- onClick={onCancel}
- disabled={loading}
- data-testid="pdf-editor-password-cancel"
- >
- {t("pdfTextEditor.password.cancel", "Cancel")}
- </Button>
- <Button
- onClick={submit}
- loading={loading}
- disabled={!password}
- data-testid="pdf-editor-password-submit"
- >
- {t("pdfTextEditor.password.open", "Open")}
- </Button>
- </Group>
- </Stack>
- </Modal>
+ fileName={prompt?.fileName}
+ password={password}
+ sessionUnlock
+ isProcessing={loading}
+ onPasswordChange={setPassword}
+ onUnlock={() => {
+ if (password && !loading) onSubmit(password);
+ }}
+ onSkip={onCancel}
+ errorMessage={
+ prompt?.retry
+ ? t(
+ "pdfTextEditor.password.incorrect",
+ "Incorrect password - try again.",
+ )
+ : undefined
+ }
+ testIdPrefix="pdf-editor-password"
+ />
);
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.test.tsx
index 114e1e1537..5ac79a029c 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.test.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.test.tsx
@@ -14,6 +14,39 @@ function scanPage(hasText = false): PageSnapshot {
}
describe("scan hint action", () => {
+ it("keeps OCR visible, explains protection, and offers Remove Password", () => {
+ const onRunOcr = vi.fn();
+ const onRemovePassword = vi.fn();
+ const reason =
+ "OCR cannot keep this PDF's password protection. Use Remove Password to create an unprotected copy first.";
+ render(
+ <MantineProvider env="test">
+ <ScanHint
+ pages={[scanPage()]}
+ onRunOcr={onRunOcr}
+ ocrRunning={false}
+ ocrAvailable
+ ocrBlockedReason={reason}
+ onRemovePassword={onRemovePassword}
+ />
+ </MantineProvider>,
+ );
+ const ocr = screen.getByTestId("pdf-editor-scan-hint-ocr");
+ expect(ocr).toBeVisible();
+ expect(ocr).toBeDisabled();
+ expect(ocr).toHaveAccessibleDescription(reason);
+ expect(screen.getByRole("note")).toBeVisible();
+ expect(
+ screen.queryByText("pdfTextEditor.inspector.ocrUnavailable"),
+ ).not.toBeInTheDocument();
+ fireEvent.click(ocr);
+ expect(onRunOcr).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "removePassword.submit" }),
+ );
+ expect(onRemovePassword).toHaveBeenCalledTimes(1);
+ });
+
it("runs the supplied OCR action in one click", () => {
const onRunOcr = vi.fn();
render(
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx
index ed52f1ea27..e3c94f4f39 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/ScanHint.tsx
@@ -1,5 +1,8 @@
+import { useId } from "react";
import { Stack, Text } from "@mantine/core";
+import { Tooltip } from "@app/components/shared/Tooltip";
import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
import { useTranslation } from "react-i18next";
import type { PageSnapshot } from "@app/tools/pdfTextEditor/types";
@@ -18,6 +21,8 @@ export interface ScanHintProps {
onRunOcr: () => void;
ocrRunning: boolean;
ocrAvailable: boolean | null;
+ ocrBlockedReason?: string | null;
+ onRemovePassword?: () => void;
}
export function ScanHint({
@@ -25,8 +30,11 @@ export function ScanHint({
onRunOcr,
ocrRunning,
ocrAvailable,
+ ocrBlockedReason,
+ onRemovePassword,
}: ScanHintProps) {
const { t } = useTranslation();
+ const reasonId = useId();
const scans = pages.filter(isUnreadScan).length;
if (scans === 0) return null;
return (
@@ -45,11 +53,40 @@ export function ScanHint({
variant="secondary"
onClick={onRunOcr}
loading={ocrRunning}
- disabled={!ocrAvailable}
+ disabled={!ocrAvailable || !!ocrBlockedReason}
+ aria-describedby={ocrBlockedReason ? reasonId : undefined}
data-testid="pdf-editor-scan-hint-ocr"
>
{t("pdfTextEditor.inspector.runOcr", "Run OCR")}
</Button>
+ {ocrBlockedReason && (
+ <Stack gap={6} align="center">
+ <Text id={reasonId} size="xs" ta="center" role="note">
+ {ocrBlockedReason}
+ </Text>
+ {onRemovePassword && (
+ <Tooltip
+ content={t(
+ "encryptedPdfUnlock.removePasswordHelp",
+ "Open Remove Password to create an unprotected copy.",
+ )}
+ position="top"
+ maxWidth={230}
+ arrow
+ >
+ <Button
+ size="sm"
+ variant="tertiary"
+ leftSection={<Icon name="lock-open" size={16} />}
+ onClick={onRemovePassword}
+ disabled={ocrRunning}
+ >
+ {t("removePassword.submit", "Remove Password")}
+ </Button>
+ </Tooltip>
+ )}
+ </Stack>
+ )}
{ocrAvailable === false && !ocrRunning && (
<Text size="xs" c="dimmed" ta="center">
{t(
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts
new file mode 100644
index 0000000000..38e13edfa5
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts
@@ -0,0 +1,77 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { createStirlingFile, type StirlingFile } from "@app/types/fileContext";
+import {
+ useAutoLoadFile,
+ type EditorLoadState,
+} from "@app/tools/pdfTextEditor/hooks/useAutoLoadFile";
+
+const files = vi.hoisted(() => ({
+ selected: [] as StirlingFile[],
+ all: [] as StirlingFile[],
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileSelection: () => ({ selectedFiles: files.selected }),
+ useAllFiles: () => ({ files: files.all }),
+}));
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationState: () => ({ selectedTool: "pdfTextEditor" }),
+}));
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => ({ activeFileId: null }),
+}));
+beforeEach(() => {
+ files.selected = [createStirlingFile(new File(["pdf"], "locked.pdf"))];
+ files.all = files.selected;
+});
+afterEach(cleanup);
+
+it("keeps a cancelled workbench password prompt closed until explicit retry", () => {
+ const file = files.selected[0];
+ const load = vi.fn();
+ const choose = vi.fn();
+ const initial: EditorLoadState = {
+ hasDocument: false,
+ loading: false,
+ error: null,
+ passwordPrompt: null,
+ };
+ const view = renderHook(
+ (editor: EditorLoadState) =>
+ useAutoLoadFile(load, choose, file.fileId, false, editor),
+ { initialProps: initial },
+ );
+ expect(load).toHaveBeenCalledOnce();
+ view.rerender({
+ ...initial,
+ passwordPrompt: { fileName: file.name, retry: true },
+ });
+ act(() => view.result.current.cancel(file));
+ view.rerender(initial);
+ view.rerender({ ...initial });
+ expect(load).toHaveBeenCalledOnce();
+ act(() => view.result.current.openFile(file));
+ expect(load).toHaveBeenCalledTimes(2);
+});
+
+it("allows another selected file to load after cancelling a password prompt", () => {
+ const file = files.selected[0];
+ const load = vi.fn();
+ const choose = vi.fn();
+ const initial: EditorLoadState = {
+ hasDocument: false,
+ loading: false,
+ error: null,
+ };
+ const view = renderHook(
+ (editor: EditorLoadState) =>
+ useAutoLoadFile(load, choose, file.fileId, false, editor),
+ { initialProps: initial },
+ );
+ act(() => view.result.current.cancel(file));
+ files.selected = [createStirlingFile(new File(["other"], "other.pdf"))];
+ files.all = [...files.all, ...files.selected];
+ view.rerender({ ...initial });
+ expect(load).toHaveBeenLastCalledWith(files.selected[0]);
+ expect(load).toHaveBeenCalledTimes(2);
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
index 14d5447f21..6864a45b08 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
@@ -21,6 +21,8 @@ interface AutoLoad {
openFile: (file: File) => void;
/** Record a document the editor loaded by other means, so auto-open stands down. */
adopt: (file: File) => void;
+ /** Keep a cancelled password request closed until another file or an explicit open. */
+ cancel: (file: File) => void;
}
/** The slice of the editor's state that decides whether it needs a file. */
@@ -28,6 +30,7 @@ export interface EditorLoadState {
hasDocument: boolean;
loading: boolean;
error: string | null;
+ passwordPrompt?: { fileName: string; retry: boolean } | null;
}
/**
@@ -84,7 +87,12 @@ export function useAutoLoadFile(
!allFiles.some((f) => (f as WorkbenchFile).fileId === currentFileId);
const lastKeyRef = useRef<string | null>(null);
+ const cancelledKeyRef = useRef<string | null>(null);
+ const cancel = useCallback((file: File) => {
+ cancelledKeyRef.current = fileKey(file);
+ }, []);
const adopt = useCallback((file: File) => {
+ cancelledKeyRef.current = null;
lastKeyRef.current = fileKey(file);
}, []);
const openFile = useCallback(
@@ -99,16 +107,19 @@ export function useAutoLoadFile(
useEffect(() => {
if (!autoLoadFile || hold) return;
if (navigationState.selectedTool !== "pdfTextEditor") return;
+ const cancelled = cancelledKeyRef.current;
+ if (cancelled === fileKey(autoLoadFile)) return;
+ cancelledKeyRef.current = null;
// A document is open: leave it, and the user's unsaved edits, alone.
if (editor.hasDocument && !documentGone) return;
- // An open is already in flight; landing it is what clears hasDocument.
- if (editor.loading) return;
+ // Restarting a pending open would reset its password prompt.
+ if (editor.loading || editor.passwordPrompt) return;
// Recovery: the store dropped a document this hook had already opened.
// Re-open THAT file, and do it quietly - no pin, no filename change. The
// canvas can be dropped because the user went to Active Files, and pinning
// it back would yank them out of the list they just asked for.
- const recovering = lastKeyRef.current !== null;
+ const recovering = lastKeyRef.current !== null && cancelled === null;
if (recovering) {
const same = allFiles.find(
(f) => (f as WorkbenchFile).fileId === currentFileId,
@@ -132,6 +143,7 @@ export function useAutoLoadFile(
editor.error,
editor.hasDocument,
editor.loading,
+ editor.passwordPrompt,
hold,
navigationState.selectedTool,
openFile,
@@ -141,5 +153,8 @@ export function useAutoLoadFile(
load,
]);
- return useMemo(() => ({ openFile, adopt }), [openFile, adopt]);
+ return useMemo(
+ () => ({ openFile, adopt, cancel }),
+ [openFile, adopt, cancel],
+ );
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index f9f5289ffa..b1cf8e313c 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -7,6 +7,9 @@ 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 { detectSaveRisks } from "@app/tools/pdfTextEditor/util/documentRisks";
const EAGER_PAGE_LIMIT = 5;
@@ -18,6 +21,7 @@ const yieldToBrowser = () =>
export function useDocumentLoader(store: EditorStore) {
return useCallback(
async (file: File, password?: string): Promise<void> => {
+ const documentPassword = password ?? getPdfAccess(file)?.password;
// Each load claims a token.
const token = store.beginLoad();
store.setLoading(true);
@@ -27,6 +31,7 @@ export function useDocumentLoader(store: EditorStore) {
total: 0,
});
try {
+ assertPdfSessionEditable(getPdfAccess(file));
await yieldToBrowser();
const bytes = new Uint8Array(await file.arrayBuffer());
if (!store.isCurrentLoad(token)) return;
@@ -36,7 +41,17 @@ export function useDocumentLoader(store: EditorStore) {
total: 0,
});
await yieldToBrowser();
- const doc = await EditorDocument.open(bytes, password);
+ const doc = await EditorDocument.open(bytes, documentPassword);
+ try {
+ const risks = detectSaveRisks(doc);
+ assertPdfSessionEditable({
+ encrypted: risks.encrypted,
+ signed: risks.signatures > 0,
+ });
+ } catch (error) {
+ doc.dispose();
+ throw error;
+ }
if (!store.isCurrentLoad(token)) {
// A newer load superseded us before we installed our doc - free
// it ourselves (setDocument never took ownership).
@@ -106,7 +121,7 @@ export function useDocumentLoader(store: EditorStore) {
err instanceof PdfiumOpenError &&
err.code === FPDF_ERR_PASSWORD
) {
- store.setPasswordRequired(file, password !== undefined);
+ store.setPasswordRequired(file, documentPassword !== undefined);
} else {
store.setError(err instanceof Error ? err.message : String(err));
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
index 0a67cdd5a5..0d52bed693 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx
@@ -4,6 +4,11 @@ import { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
import { useEditorOcr } from "@app/tools/pdfTextEditor/hooks/useEditorOcr";
import type { FileId } from "@app/types/file";
+import {
+ bindPdfAccess,
+ clearPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
const mocks = vi.hoisted(() => ({
get: vi.fn(),
@@ -45,8 +50,9 @@ vi.mock("react-i18next", () => ({
}),
}));
-function makeDoc(): EditorDocument {
+function makeDoc(encrypted = false): EditorDocument {
return {
+ module: { FPDF_GetSecurityHandlerRevision: () => (encrypted ? 6 : -1) },
pageCount: 0,
loadedPages: () => [],
dispose: vi.fn(),
@@ -70,9 +76,27 @@ function deferred<T>() {
return { promise, resolve };
}
-async function setup() {
+function protectSource() {
+ const file = new File(["protected source"], "scan.pdf");
+ rememberPdfAccess(file, {
+ password: "test-password",
+ encrypted: true,
+ signed: false,
+ ownerAuthenticated: true,
+ permissions: -4,
+ canModify: true,
+ canAssemble: true,
+ pageCount: 1,
+ });
+ bindPdfAccess(file, "source-id" as FileId);
+}
+
+async function setup(
+ doc = makeDoc(),
+ fileId: FileId | null = "source-id" as FileId,
+) {
const store = new EditorStore();
- await store.setDocument(makeDoc());
+ await store.setDocument(doc);
const onComplete = vi.fn(async (_file: File, isCurrent: () => boolean) => {
expect(isCurrent()).toBe(true);
});
@@ -80,7 +104,7 @@ async function setup() {
useEditorOcr({
store,
fileName: "scan.pdf",
- fileId: "source-id" as FileId,
+ fileId,
onComplete,
}),
);
@@ -90,6 +114,7 @@ async function setup() {
describe("editor inline OCR", () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearPdfAccess();
mocks.enabled = true;
mocks.locale = "en-GB";
mocks.get.mockResolvedValue({ data: { languages: ["eng", "deu", "osd"] } });
@@ -112,6 +137,69 @@ describe("editor inline OCR", () => {
afterEach(() => vi.restoreAllMocks());
+ it.each(["session", "native"])(
+ "blocks protected %s documents before exporting or checking credits",
+ async (source) => {
+ if (source === "session") protectSource();
+ const { result, store, onComplete } = await setup(
+ makeDoc(source === "native"),
+ source === "native" ? null : ("source-id" as FileId),
+ );
+ expect(result.current.available).toBe(true);
+ expect(result.current.blockedReason).toContain("password protection");
+ await act(() => result.current.runOcr());
+ expect(mocks.checkCredits).not.toHaveBeenCalled();
+ expect(mocks.exportPdf).not.toHaveBeenCalled();
+ expect(mocks.get).not.toHaveBeenCalled();
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(store.getState()).toMatchObject({
+ loading: false,
+ error: result.current.blockedReason,
+ });
+ },
+ );
+
+ it("blocks upload if protection is discovered during export", async () => {
+ mocks.exportPdf.mockImplementationOnce(async () => {
+ protectSource();
+ return { blob: new Blob(["%PDF-1.7"]), filename: "scan.pdf" };
+ });
+ const { result, store, onComplete } = await setup();
+ await act(() => result.current.runOcr());
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(store.getState().error).toContain("password protection");
+ });
+
+ it("rejects OCR output if source protection changes while the request is pending", async () => {
+ const response = deferred<{ data: Blob }>();
+ mocks.post.mockReturnValueOnce(response.promise);
+ const { result, store, onComplete } = await setup();
+ let pending!: Promise<void>;
+ act(() => {
+ pending = result.current.runOcr();
+ });
+ await waitFor(() => expect(mocks.post).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ protectSource();
+ response.resolve({ data: new Blob(["%PDF-1.7"]) });
+ await pending;
+ });
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(store.getState()).toMatchObject({
+ loading: false,
+ error: expect.stringContaining("password protection"),
+ });
+ });
+
+ it("updates the explanation when session access changes without a document reload", async () => {
+ const { result } = await setup();
+ expect(result.current.blockedReason).toBeNull();
+ act(protectSource);
+ expect(result.current.blockedReason).toContain("password protection");
+ });
+
it("posts the current editor bytes through the app client and applies the OCR PDF", async () => {
mocks.locale = "de-DE";
const { result, store, onComplete } = await setup();
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.ts
index 2f8f80349c..39385c0e90 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorOcr.ts
@@ -4,6 +4,7 @@ import apiClient from "@app/services/apiClient";
import { ensureBackendReady } from "@app/services/backendReadinessGuard";
import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
import { useEndpointEnabled } from "@app/hooks/useEndpointConfig";
+import { usePdfAccess } from "@app/hooks/usePdfAccess";
import { useCreditCheck } from "@app/hooks/useCreditCheck";
import { useToolResources } from "@app/hooks/tools/shared/useToolResources";
import {
@@ -15,6 +16,10 @@ import { defaultParameters } from "@app/hooks/tools/ocr/useOCRParameters";
import { getAutoOcrLanguage } from "@app/utils/languageMapping";
import { extractErrorMessage } from "@app/utils/toolErrorHandler";
import { exportToBlob } from "@app/tools/pdfTextEditor/util/exportPdf";
+import {
+ assertEditorOcrAllowed,
+ getEditorOcrBlockedReason,
+} from "@app/tools/pdfTextEditor/util/ocrProtection";
import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
import type { FileId } from "@app/types/file";
@@ -39,6 +44,8 @@ export function useEditorOcr({
}: EditorOcrOptions) {
const { t, i18n } = useTranslation();
const { enabled } = useEndpointEnabled("ocr-pdf");
+ usePdfAccess(fileId);
+ const blockedReason = getEditorOcrBlockedReason(store.document, fileId, t);
const { checkCredits } = useCreditCheck("ocr", OCR_ENDPOINT);
const { extractZipFiles } = useToolResources();
const [running, setRunning] = useState(false);
@@ -92,6 +99,7 @@ export function useEditorOcr({
});
try {
+ assertEditorOcrAllowed(doc, fileId, t);
assertFilesNotBlocked([fileId ?? undefined]);
const creditError = await checkCredits(OCR_ENDPOINT);
if (!isCurrent()) return;
@@ -128,6 +136,7 @@ export function useEditorOcr({
type: "application/pdf",
});
assertFilesNotBlocked([fileId ?? undefined]);
+ assertEditorOcrAllowed(doc, fileId, t);
const response = await apiClient.post<Blob>(
OCR_ENDPOINT,
buildOCRFormData(
@@ -153,6 +162,7 @@ export function useEditorOcr({
);
}
assertFilesNotBlocked([fileId ?? undefined]);
+ assertEditorOcrAllowed(doc, fileId, t);
await onComplete(pdfs[0], isCurrent);
} catch (error) {
if (isSameDocument()) store.setError(extractErrorMessage(error));
@@ -188,5 +198,6 @@ export function useEditorOcr({
runOcr,
running,
available: enabled,
+ blockedReason,
};
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/documentRisks.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/documentRisks.ts
index 0556a8957f..9a06d91b6b 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/documentRisks.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/documentRisks.ts
@@ -66,7 +66,7 @@ export function describeSaveRisks(r: SaveRisks): string[] {
if (r.xfaForm) out.push("Interactive XFA form data may be lost.");
if (r.encrypted) {
out.push(
- "This PDF is encrypted; the saved copy will NOT be encrypted (password and access restrictions are removed).",
+ "Saving this PDF may change its encryption or access restrictions.",
);
}
if (r.droppedChars.length > 0) {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts
new file mode 100644
index 0000000000..5c065bcbd0
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/ocrProtection.ts
@@ -0,0 +1,33 @@
+import type { TFunction } from "i18next";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { detectSaveRisks } from "@app/tools/pdfTextEditor/util/documentRisks";
+import type { FileId } from "@app/types/file";
+
+/** Checks native encryption too: a disk-opened document may not have a FileContext ID yet. */
+export function getEditorOcrBlockedReason(
+ doc: EditorDocument | null,
+ fileId: FileId | null,
+ t: TFunction,
+): string | null {
+ if (
+ getPdfAccess(fileId)?.encrypted ||
+ (doc && detectSaveRisks(doc).encrypted)
+ ) {
+ return t(
+ "pdfTextEditor.inspector.ocrProtected",
+ "OCR cannot keep this PDF's password protection. Use Remove Password to create an unprotected copy first.",
+ );
+ }
+ return null;
+}
+
+/** Rejects OCR input and output while the source remains protected, even after session unlock. */
+export function assertEditorOcrAllowed(
+ doc: EditorDocument | null,
+ fileId: FileId | null,
+ t: TFunction,
+): void {
+ const reason = getEditorOcrBlockedReason(doc, fileId, t);
+ if (reason) throw new Error(reason);
+}
diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.ts
index d133c366ba..482d7c1acc 100644
--- a/frontend/editor/src/core/types/fileContext.ts
+++ b/frontend/editor/src/core/types/fileContext.ts
@@ -5,6 +5,11 @@
import { PageOperation } from "@app/types/pageEditor";
import { FileId, BaseFileMetadata } from "@app/types/file";
import { generateId } from "@app/utils/generateId";
+import {
+ bindPdfAccess,
+ getPdfAccess,
+ rememberPdfAccess,
+} from "@app/services/pdfPasswordStore";
import type { DiskUnavailableReason } from "@app/services/desktopFileLink";
// Re-export FileId for convenience
@@ -180,8 +185,12 @@ export function documentBytesReplaced(
return previous.id === current.id && previous.key !== current.key;
}
-// Create a StirlingFile from a regular File object
-export function createStirlingFile(file: File, id?: FileId): StirlingFile {
+/** Storage reads opt out of rebinding: reading a copy must not revoke access to the active bytes. */
+export function createStirlingFile(
+ file: File,
+ id?: FileId,
+ options?: { bindSessionAccess?: boolean },
+): StirlingFile {
// If the file already has Stirling metadata and we aren't trying to override it,
// return as–is. When a new id is requested we clone the File so we can embed
// the fresh identifier without mutating the original object.
@@ -190,10 +199,12 @@ export function createStirlingFile(file: File, id?: FileId): StirlingFile {
return file;
}
+ const access = getPdfAccess(file);
file = new File([file], file.name, {
type: file.type,
lastModified: file.lastModified,
});
+ if (access) rememberPdfAccess(file, access);
}
const fileId = id || createFileId();
@@ -215,6 +226,7 @@ export function createStirlingFile(file: File, id?: FileId): StirlingFile {
configurable: false,
});
+ if (options?.bindSessionAccess !== false) bindPdfAccess(file, fileId);
return file as StirlingFile;
}
@@ -391,8 +403,6 @@ export interface FileContextActions {
options?: {
insertAfterPageId?: string;
selectFiles?: boolean;
- /** Suppress the duplicate modal while retaining a policy hold on encrypted bytes. */
- skipAutomaticPasswordPrompt?: boolean;
skipUploadTracking?: boolean;
/**
* Produced in-app rather than uploaded, which stops the policy auto-run enforcing an upload
@@ -474,6 +484,12 @@ export interface FileContextActions {
scheduleCleanup: (fileId: FileId, delay?: number) => void;
cleanupFile: (fileId: FileId) => void;
openEncryptedUnlockPrompt: (fileId: FileId) => void;
+ /** Authenticates preview bytes without adding a library record. Abort when the preview closes. */
+ unlockPreviewPdf: (
+ file: File,
+ password: string,
+ signal: AbortSignal,
+ ) => Promise<void>;
}
// File selectors (separate from actions to avoid re-renders)
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.ts
index 9131c0ce9b..8b24979ebe 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts
@@ -11,6 +11,7 @@ import {
} from "@app/utils/pdfiumPageRender";
import { jpegExifOrientation } from "@app/utils/jpegOrientation";
import { getDocumentBytes } from "@app/services/documentBytesCache";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
export interface ThumbnailWithMetadata {
thumbnail: string; // Always returns a thumbnail (placeholder if needed)
@@ -97,7 +98,7 @@ export function containsEncryptMarker(bytes: Uint8Array): boolean {
* the head and the main one at the tail, so both windows have to be probed.
* Heuristic: a false positive offers unlock on a file that did not need it, a
* false negative leaves it unopenable. */
-async function looksEncryptedFromTrailer(file: File): Promise<boolean> {
+export async function looksEncryptedFromTrailer(file: File): Promise<boolean> {
const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
const tail = await file.slice(tailStart).arrayBuffer();
if (containsEncryptMarker(new Uint8Array(tail))) return true;
@@ -133,11 +134,12 @@ async function renderPdfThumbnailPdfium(
scale: number,
applyRotation: boolean,
collectAllPagesMetadata: boolean,
+ password?: string,
): Promise<PdfiumRenderResult> {
const m = await getPdfiumModule();
let docPtr: number;
try {
- docPtr = await openRawDocumentSafe(data);
+ docPtr = await openRawDocumentSafe(data, password);
} catch (error) {
if (error instanceof PdfiumOpenError && error.code === FPDF_ERR_PASSWORD) {
return {
@@ -192,11 +194,12 @@ async function renderPdfThumbnailPairPdfium(
data: ArrayBuffer,
scale: number,
collectAllPagesMetadata: boolean,
+ password?: string,
): Promise<{ unrotated: PdfiumRenderResult; rotated: PdfiumRenderResult }> {
const m = await getPdfiumModule();
let docPtr: number;
try {
- docPtr = await openRawDocumentSafe(data);
+ docPtr = await openRawDocumentSafe(data, password);
} catch (error) {
if (error instanceof PdfiumOpenError && error.code === FPDF_ERR_PASSWORD) {
const encrypted: PdfiumRenderResult = {
@@ -250,12 +253,14 @@ async function renderPdfThumbnailPairPdfium(
async function generatePDFThumbnail(
arrayBuffer: ArrayBuffer,
scale: number,
+ password?: string,
): Promise<string> {
const result = await renderPdfThumbnailPdfium(
arrayBuffer,
scale,
true,
false,
+ password,
);
if (result.isEncrypted) {
return "";
@@ -540,14 +545,22 @@ export async function generateThumbnailForFile(file: File): Promise<string> {
const arrayBuffer = await chunk.arrayBuffer();
try {
- return await generatePDFThumbnail(arrayBuffer, scale);
+ return await generatePDFThumbnail(
+ arrayBuffer,
+ scale,
+ getPdfAccess(file)?.password,
+ );
} catch {
// PDFium needs the xref table at the end of the file, so the 2MB
// chunk can fail to open for PDFs larger than that. Retry with the
// full buffer before falling back to an empty thumbnail.
try {
const fullArrayBuffer = await getDocumentBytes(file);
- return await generatePDFThumbnail(fullArrayBuffer, scale);
+ return await generatePDFThumbnail(
+ fullArrayBuffer,
+ scale,
+ getPdfAccess(file)?.password,
+ );
} catch (error) {
reportThumbnailFailure(file, error);
return "";
@@ -582,7 +595,7 @@ export async function generateThumbnailWithMetadata(
// Probe inside the try: an unreadable file must still resolve, or the
// caller leaves the card with no metadata and a spinner that never stops.
try {
- if (await looksEncryptedFromTrailer(file)) {
+ if (!getPdfAccess(file) && (await looksEncryptedFromTrailer(file))) {
return { thumbnail: "", pageCount: 1, isEncrypted: true };
}
const chunk = await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer();
@@ -591,6 +604,7 @@ export async function generateThumbnailWithMetadata(
scale,
applyRotation,
false,
+ getPdfAccess(file)?.password,
);
if (result.isEncrypted) {
return { thumbnail: "", pageCount: 1, isEncrypted: true };
@@ -616,6 +630,7 @@ export async function generateThumbnailWithMetadata(
scale,
applyRotation,
true,
+ getPdfAccess(file)?.password,
);
if (result.isEncrypted) {
@@ -652,7 +667,11 @@ export async function generateThumbnailPairWithMetadata(file: File): Promise<{
try {
// Probe inside the try: an unreadable file must still resolve, or the
// caller leaves the card with no metadata and a spinner that never stops.
- if (isLarge && (await looksEncryptedFromTrailer(file))) {
+ if (
+ isLarge &&
+ !getPdfAccess(file) &&
+ (await looksEncryptedFromTrailer(file))
+ ) {
const encrypted: ThumbnailWithMetadata = {
thumbnail: "",
pageCount: 1,
@@ -663,7 +682,12 @@ export async function generateThumbnailPairWithMetadata(file: File): Promise<{
const buffer = isLarge
? await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer()
: await getDocumentBytes(file);
- const pair = await renderPdfThumbnailPairPdfium(buffer, scale, !isLarge);
+ const pair = await renderPdfThumbnailPairPdfium(
+ buffer,
+ scale,
+ !isLarge,
+ getPdfAccess(file)?.password,
+ );
const toPublic = (r: PdfiumRenderResult): ThumbnailWithMetadata =>
r.isEncrypted
diff --git a/frontend/editor/src/core/utils/toolIOCompat.ts b/frontend/editor/src/core/utils/toolIOCompat.ts
index 4753bf958a..e5c747ade1 100644
--- a/frontend/editor/src/core/utils/toolIOCompat.ts
+++ b/frontend/editor/src/core/utils/toolIOCompat.ts
@@ -16,6 +16,8 @@ import {
} from "@app/types/toolIO";
import { detectFileExtension, getFileFormats } from "@app/utils/fileUtils";
import type { StirlingFileStub } from "@app/types/fileContext";
+import { getPdfAccess } from "@app/services/pdfPasswordStore";
+import { supportsSessionUnlock } from "@app/services/pdfSessionUnlock";
export type ToolDiagnosticSeverity = "ERROR" | "WARN" | "INFO";
@@ -267,10 +269,22 @@ export function toolAcceptsFormat(
*/
export function toolAcceptsFile(
operation: string | undefined,
- file: Pick<StirlingFileStub, "name" | "type" | "processedFile">,
+ file: Pick<StirlingFileStub, "name" | "type" | "processedFile"> & {
+ id?: string;
+ },
): boolean {
const spec = operation ? toolIOFor(operation) : undefined;
- const formats = getFileFormats(file);
+ const formats =
+ getPdfAccess(file.id) && supportsSessionUnlock(operation)
+ ? getFileFormats({
+ ...file,
+ processedFile: {
+ ...file.processedFile,
+ pages: file.processedFile?.pages ?? [],
+ isEncrypted: false,
+ },
+ })
+ : getFileFormats(file);
if (
formats.includes("PDF_ENCRYPTED") &&
(!spec || !acceptsFormat(spec, "PDF_ENCRYPTED"))