#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Let administrators block changes to digitally signed PDFs (#8815)
Anthony Stirlingdcd6499a6633
diff --git a/.gitattributes b/.gitattributesindex 849675bc6e..528ed33f55 100644--- a/.gitattributes+++ b/.gitattributes@@ -6,3 +6,5 @@ app/core/src/main/resources/static/pdfjs/** linguist-vendoredapp/core/src/main/resources/static/css/bootstrap-icons.css linguist-vendoredapp/core/src/main/resources/static/css/bootstrap.min.css linguist-vendoredapp/core/src/main/resources/static/css/fonts/* linguist-vendored++frontend/src/editor/core/tests/test-fixtures/signature-*.pdf binarydiff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex 2be7eeb342..d800f668bf 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -973,6 +973,7 @@ public class ApplicationProperties {public static class Security {private boolean enableLogin;private boolean honorOwnerPasswords = true;+ private boolean blockSignedPdfEdits = false;private boolean ssoAutoLogin;private InitialLogin initialLogin = new InitialLogin();private OAUTH2 oauth2 = new OAUTH2();diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.javaindex 4de84ea7a8..161aab737c 100644--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java@@ -268,6 +268,9 @@ public class ConfigController {configData.put("honorOwnerPasswords",applicationProperties.getSecurity().isHonorOwnerPasswords());+ configData.put(+ "blockSignedPdfEdits",+ applicationProperties.getSecurity().isBlockSignedPdfEdits());configData.put("showSettingsWhenNoLogin",applicationProperties.getSystem().isShowSettingsWhenNoLogin());diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 4579c464ea..9dd3825ddd 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -12,6 +12,7 @@security:honorOwnerPasswords: true # Require the permissions password for restricted PDF actions; opening passwords are always required.+ blockSignedPdfEdits: false # Lock digitally signed PDFs against changes in the web and desktop apps; viewing, converting and signing again stay allowed. API calls and server pipelines are not affected.enableLogin: true # set to 'true' to enable loginssoAutoLogin: falseloginAttemptCount: 5 # lock user account after 5 tries; when using e.g. Fail2Ban you can deactivate the function with -1diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 1c5e06e481..5a8e11eadd 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -1661,6 +1661,10 @@ verbose = "STANDARD events plus: continuous polling calls, all GET requests, detdescription = "Number of days to retain audit logs (0 = infinite retention)"label = "Audit Retention (days)"+[admin.settings.security.blockSignedPdfEdits]+description = "Signed PDFs can still be viewed, printed, converted or signed again, but not changed in the app. API calls and server pipelines are not affected."+label = "Block changes to signed PDFs"+[admin.settings.security.csrfDisabled]description = "Disable Cross-Site Request Forgery protection (not recommended)"label = "Disable CSRF Protection"@@ -13535,6 +13539,11 @@ bullet3 = "Invisible signatures still provide cryptographic validation"description = "Controls whether the signature is visible on the document or embedded invisibly."title = "Signature Visibility"+[signedPdf]+editsBlocked = "This PDF is digitally signed, and changes to signed PDFs are turned off. You can still view or print it, convert it to another format, or sign it again."+editsBlockedStatus = "Signed: edits blocked"+editsBlockedTitle = "Signed PDF can't be changed"+[signingDetail]allSigned = "Everyone has signed. Review the document, then finalize."awaitingOwner = "The owner will finalize the document once they are ready."diff --git a/frontend/src-tauri/provisioner/src/main.rs b/frontend/src-tauri/provisioner/src/main.rsindex 9f85551677..f35e093946 100644--- a/frontend/src-tauri/provisioner/src/main.rs+++ b/frontend/src-tauri/provisioner/src/main.rs@@ -18,6 +18,8 @@ struct ProvisioningConfig<'a> {local_processing_only: Option<bool>,#[serde(skip_serializing_if = "Option::is_none")]login_agreement_enabled: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ block_signed_pdf_edits: Option<bool>,/// Optional headless-install update policy./// One of `"prompt"` (default), `"auto"`, or `"disabled"`.#[serde(skip_serializing_if = "Option::is_none")]@@ -68,6 +70,7 @@ fn main() -> Result<(), String> {let mut cloud_only_arg: Option<String> = None;let mut local_processing_only_arg: Option<String> = None;let mut login_agreement_value: Option<String> = None;+ let mut block_signed_pdf_edits_arg: Option<String> = None;let mut update_mode_arg: Option<String> = None;let mut args = env::args().skip(1);@@ -110,6 +113,12 @@ fn main() -> Result<(), String> {.ok_or_else(|| "--login-agreement requires a value".to_string())?;login_agreement_value = Some(value);}+ "--block-signed-pdf-edits" => {+ block_signed_pdf_edits_arg = Some(+ args.next()+ .ok_or("--block-signed-pdf-edits requires a value")?,+ );+ }"--update-mode" => {let value = args.next()@@ -146,6 +155,7 @@ fn main() -> Result<(), String> {let require_sign_in = parse_policy_bool(require_sign_in_arg.as_deref())?;let cloud_only = parse_policy_bool(cloud_only_arg.as_deref())?;let local_processing_only = parse_policy_bool(local_processing_only_arg.as_deref())?;+ let block_signed_pdf_edits = parse_policy_bool(block_signed_pdf_edits_arg.as_deref())?;// Nothing to write — avoid clobbering an existing provisioning file when the// MSI is invoked without any provisioning directives@@ -156,6 +166,7 @@ fn main() -> Result<(), String> {&& require_sign_in.is_none()&& cloud_only.is_none()&& local_processing_only.is_none()+ && block_signed_pdf_edits.is_none(){return Ok(());}@@ -178,6 +189,7 @@ fn main() -> Result<(), String> {cloud_only,local_processing_only,login_agreement_enabled: login_agreement,+ block_signed_pdf_edits,update_mode,};@@ -252,6 +264,7 @@ mod tests {cloud_only: Some(true),local_processing_only: Some(true),login_agreement_enabled: None,+ block_signed_pdf_edits: None,update_mode: None,};assert_eq!(@@ -259,4 +272,22 @@ mod tests {serde_json::json!({"requireSignIn": true, "cloudOnly": true, "localProcessingOnly": true}));}++ #[test]+ fn signed_pdf_edit_policy_is_written_only_when_supplied() {+ let config = ProvisioningConfig {+ server_url: None,+ lock_connection_mode: None,+ require_sign_in: None,+ cloud_only: None,+ local_processing_only: None,+ login_agreement_enabled: None,+ block_signed_pdf_edits: parse_policy_bool(Some("true")).unwrap(),+ update_mode: None,+ };+ assert_eq!(+ serde_json::to_value(config).unwrap(),+ serde_json::json!({"blockSignedPdfEdits": true})+ );+ }}diff --git a/frontend/src-tauri/src/commands/backend.rs b/frontend/src-tauri/src/commands/backend.rsindex be563e755f..6cc00370e6 100644--- a/frontend/src-tauri/src/commands/backend.rs+++ b/frontend/src-tauri/src/commands/backend.rs@@ -355,6 +355,10 @@ fn run_stirling_pdf_jar(java_options.push("-Dlegal.loginAgreement.enabled=true");}+ if crate::commands::connection::block_signed_pdf_edits(app) {+ java_options.push("-Dsecurity.blockSignedPdfEdits=true");+ }+java_options.push("-jar");java_options.push(jar_path.to_str().unwrap());diff --git a/frontend/src-tauri/src/commands/connection.rs b/frontend/src-tauri/src/commands/connection.rsindex 560f33b173..7c069988e2 100644--- a/frontend/src-tauri/src/commands/connection.rs+++ b/frontend/src-tauri/src/commands/connection.rs@@ -16,6 +16,7 @@ const REQUIRE_SIGN_IN_KEY: &str = "require_sign_in";const CLOUD_ONLY_KEY: &str = "cloud_only";const LOCAL_PROCESSING_ONLY_KEY: &str = "local_processing_only";const LOGIN_AGREEMENT_KEY: &str = "login_agreement_enabled";+const BLOCK_SIGNED_PDF_EDITS_KEY: &str = "block_signed_pdf_edits";pub(crate) const UPDATE_MODE_KEY: &str = "update_mode";/// When `true` the update mode was written by a provisioning file and cannot/// be changed from the UI. Only another provisioning file (from MDM) can@@ -214,6 +215,7 @@ struct ProvisioningConfig {cloud_only: Option<bool>,local_processing_only: Option<bool>,login_agreement_enabled: Option<bool>,+ block_signed_pdf_edits: Option<bool>,/// Optional headless-install update policy (`"prompt"`, `"auto"`, `"disabled"`)./// When omitted the existing stored mode is left unchanged.update_mode: Option<UpdateMode>,@@ -369,6 +371,20 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strin));}+ if let Some(block_signed_pdf_edits) = parsed.block_signed_pdf_edits {+ if let Ok(store) = app_handle.store(STORE_FILE) {+ store.set(+ BLOCK_SIGNED_PDF_EDITS_KEY,+ serde_json::json!(block_signed_pdf_edits),+ );+ let _ = store.save();+ }+ add_log(format!(+ "🧩 Provisioned signed PDF edit blocking = {}",+ block_signed_pdf_edits+ ));+ }+let server_url = parsed.server_url.map(|value| value.trim().to_string())@@ -383,6 +399,7 @@ pub fn apply_provisioning_if_present(app_handle: &AppHandle) -> Result<(), Strin&& parsed.require_sign_in.is_none()&& parsed.cloud_only.is_none()&& parsed.local_processing_only.is_none()+ && parsed.block_signed_pdf_edits.is_none(){add_log("⚠️ Provisioning file has no actionable fields (serverUrl/updateMode/loginAgreement); skipping apply"@@ -530,6 +547,15 @@ pub fn login_agreement_enabled(app_handle: &AppHandle) -> bool {.unwrap_or(false)}+pub fn block_signed_pdf_edits(app_handle: &AppHandle) -> bool {+ app_handle+ .store(STORE_FILE)+ .ok()+ .and_then(|store| store.get(BLOCK_SIGNED_PDF_EDITS_KEY))+ .and_then(|value| value.as_bool())+ .unwrap_or(false)+}+#[tauri::command]pub async fn is_first_launch(app_handle: AppHandle) -> Result<bool, String> {let store = app_handlediff --git a/frontend/src-tauri/windows/wix/provisioning.wxs b/frontend/src-tauri/windows/wix/provisioning.wxsindex ac67b5e56e..fcfa51e61d 100644--- a/frontend/src-tauri/windows/wix/provisioning.wxs+++ b/frontend/src-tauri/windows/wix/provisioning.wxs@@ -8,6 +8,7 @@<Property Id="STIRLING_LOCAL_PROCESSING_ONLY" Secure="yes" /><!-- STIRLING_LOGIN_AGREEMENT — "1"/"true" enables the login agreement popup on this install. --><Property Id="STIRLING_LOGIN_AGREEMENT" Secure="yes" />+ <Property Id="STIRLING_BLOCK_SIGNED_PDF_EDITS" Secure="yes" /><!--STIRLING_UPDATE_MODE — headless auto-update policy for MDM/Intune deploys.Accepts "prompt" (default, user-interactive), "auto" (silent download+install on@@ -76,20 +77,20 @@<CustomActionId="SetWriteProvisioningFilePerUser"Property="WriteProvisioningFilePerUser"- Value="--output "[AppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""+ Value="--output "[AppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --block-signed-pdf-edits "[STIRLING_BLOCK_SIGNED_PDF_EDITS]" --update-mode "[STIRLING_UPDATE_MODE]""/><CustomActionId="SetWriteProvisioningFileAllUsers"Property="WriteProvisioningFileAllUsers"- Value="--output "[CommonAppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --update-mode "[STIRLING_UPDATE_MODE]""+ Value="--output "[CommonAppDataFolder]Stirling-PDF\stirling-provisioning.json" --url "[STIRLING_SERVER_URL]" --lock "[STIRLING_LOCK_CONNECTION]" --require-sign-in "[STIRLING_REQUIRE_SIGN_IN]" --cloud-only "[STIRLING_CLOUD_ONLY]" --local-processing-only "[STIRLING_LOCAL_PROCESSING_ONLY]" --login-agreement "[STIRLING_LOGIN_AGREEMENT]" --block-signed-pdf-edits "[STIRLING_BLOCK_SIGNED_PDF_EDITS]" --update-mode "[STIRLING_UPDATE_MODE]""/><InstallExecuteSequence>- <Custom Action="SetWriteProvisioningFilePerUser" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>- <Custom Action="WriteProvisioningFilePerUser" After="SetWriteProvisioningFilePerUser">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>- <Custom Action="SetWriteProvisioningFileAllUsers" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>- <Custom Action="WriteProvisioningFileAllUsers" After="SetWriteProvisioningFileAllUsers">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>+ <Custom Action="SetWriteProvisioningFilePerUser" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "" OR STIRLING_BLOCK_SIGNED_PDF_EDITS <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>+ <Custom Action="WriteProvisioningFilePerUser" After="SetWriteProvisioningFilePerUser">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "" OR STIRLING_BLOCK_SIGNED_PDF_EDITS <> "") AND (NOT ALLUSERS OR ALLUSERS=0)</Custom>+ <Custom Action="SetWriteProvisioningFileAllUsers" After="InstallFiles">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "" OR STIRLING_BLOCK_SIGNED_PDF_EDITS <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom>+ <Custom Action="WriteProvisioningFileAllUsers" After="SetWriteProvisioningFileAllUsers">(STIRLING_SERVER_URL <> "" OR STIRLING_LOGIN_AGREEMENT <> "" OR STIRLING_UPDATE_MODE <> "" OR STIRLING_REQUIRE_SIGN_IN <> "" OR STIRLING_CLOUD_ONLY <> "" OR STIRLING_LOCAL_PROCESSING_ONLY <> "" OR STIRLING_BLOCK_SIGNED_PDF_EDITS <> "") AND (ALLUSERS=1 OR ALLUSERS=2)</Custom></InstallExecuteSequence></Fragment></Wix>diff --git a/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts b/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.tsindex acfaf4885d..4f2d4af953 100644--- a/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts+++ b/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts@@ -21,6 +21,7 @@ import {buildTrackFile,policyIdsForTracks,} from "@editor/components/pageTracks/buildTrackFile";+import { SignedPdfEditsBlockedError } from "@editor/services/pdfSessionUnlock";/*** The page editor is a page-level rework of the open documents, which is what@@ -243,6 +244,16 @@ export function useTrackSave(title: t("policy.recoveryTitle"),body: t("policy.recoveryBody"),});+ } else if (error instanceof SignedPdfEditsBlockedError) {+ alert({+ alertType: "warning",+ title: t(+ "signedPdf.editsBlockedTitle",+ "Signed PDF can't be changed",+ ),+ body: error.message,+ expandable: false,+ });} else {console.error("[PageTracks] save failed", error);alert({diff --git a/frontend/src/editor/core/components/tools/shared/FilesToolStep.tsx b/frontend/src/editor/core/components/tools/shared/FilesToolStep.tsxindex fbe91657b7..a8758919ef 100644--- a/frontend/src/editor/core/components/tools/shared/FilesToolStep.tsx+++ b/frontend/src/editor/core/components/tools/shared/FilesToolStep.tsx@@ -4,7 +4,10 @@ import { StirlingFile } from "@editor/types/fileContext";import i18n from "@editor/i18n";import { useViewScopedFileStubs } from "@editor/hooks/tools/shared/useViewScopedFiles";import { usePdfAccess } from "@editor/hooks/usePdfAccess";-import { getPdfAccess } from "@editor/services/pdfAccessService";+import {+ getPdfAccess,+ signedPdfEditsBlocked,+} from "@editor/services/pdfAccessService";export interface FilesToolStepProps {selectedFiles: StirlingFile[];@@ -22,12 +25,14 @@ function FilesStepContent({usePdfAccess(undefined);const files = useViewScopedFileStubs();const unavailableFiles = showUnavailableFiles- ? files.filter(- (file) =>- file.processedFile?.isEncrypted &&- getPdfAccess(file.id) &&- !selectedFiles.some((selected) => selected.fileId === file.id),- )+ ? files.filter((file) => {+ const access = getPdfAccess(file.id);+ return (+ ((file.processedFile?.isEncrypted && access) ||+ signedPdfEditsBlocked(access)) &&+ !selectedFiles.some((selected) => selected.fileId === file.id)+ );+ }): [];return (<FileStatusIndicatordiff --git a/frontend/src/editor/core/components/tools/shared/ProtectedPdfToolNotice.tsx b/frontend/src/editor/core/components/tools/shared/ProtectedPdfToolNotice.tsxindex ab88131e01..d35af42a9c 100644--- a/frontend/src/editor/core/components/tools/shared/ProtectedPdfToolNotice.tsx+++ b/frontend/src/editor/core/components/tools/shared/ProtectedPdfToolNotice.tsx@@ -1,3 +1,4 @@+import { signedPdfEditsBlockedMessage } from "@editor/services/pdfSessionUnlock";import { Group, Stack, Text } from "@mantine/core";import { Tooltip } from "@editor/components/shared/Tooltip";import { ActionIcon } from "@editor/ui/ActionIcon";@@ -6,6 +7,7 @@ import { useTranslation } from "react-i18next";import { PrivateContent } from "@editor/components/shared/PrivateContent";import type { StirlingFileStub } from "@editor/types/fileContext";import { useToolWorkflowActions } from "@editor/contexts/ToolWorkflowContext";+import { getPdfAccess } from "@editor/services/pdfAccessService";function RemovePasswordAction() {const { t } = useTranslation();@@ -47,10 +49,14 @@ export function ProtectedPdfToolNotice({{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.",- )}+ content={+ getPdfAccess(file.id)?.encrypted+ ? t(+ "encryptedPdfUnlock.toolUnavailable",+ "This tool doesn't support encrypted PDFs. Remove the password first.",+ )+ : signedPdfEditsBlockedMessage()+ }position="top"maxWidth={260}arrow@@ -80,7 +86,7 @@ export function ProtectedPdfToolNotice({><PrivateContent>{file.name}</PrivateContent></Text>- <RemovePasswordAction />+ {getPdfAccess(file.id)?.encrypted && <RemovePasswordAction />}</Group>))}</Stack>diff --git a/frontend/src/editor/core/components/viewer/BookmarkSidebar.tsx b/frontend/src/editor/core/components/viewer/BookmarkSidebar.tsxindex 28659549be..5baf2668ff 100644--- a/frontend/src/editor/core/components/viewer/BookmarkSidebar.tsx+++ b/frontend/src/editor/core/components/viewer/BookmarkSidebar.tsx@@ -16,6 +16,7 @@ import { useFileContext } from "@editor/contexts/FileContext";import { isStirlingFile } from "@editor/types/fileContext";import { createStirlingFilesAndStubs } from "@editor/services/fileStubHelpers";import apiClient from "@editor/services/apiClient";+import { assertSignedPdfsEditable } from "@editor/services/pdfSessionUnlock";import { openExternalTab } from "@editor/platform/openExternalTab";import { getExternalHref } from "@editor/utils/externalUrl";import { PdfBookmarkObject, PdfActionType } from "@embedpdf/models";@@ -394,6 +395,11 @@ export const BookmarkSidebar = ({setIsSavingBookmark(true);setAddBookmarkError(null);try {+ await assertSignedPdfsEditable(+ [file],+ "/api/v1/general/edit-table-of-contents",+ false,+ );// Convert existing PDF bookmarks (from embedpdf) to the backend's// payload shape, then append the new one.const toPayload = (b: PdfBookmarkObject): BookmarkPayload => ({diff --git a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsxindex 7a3cbb4d52..6c857fb8a6 100644--- a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx@@ -28,7 +28,7 @@ import { useViewer } from "@editor/contexts/ViewerContext";import { LocalEmbedPDF } from "@editor/components/viewer/LocalEmbedPDF";import { PdfProtectionStatus } from "@editor/components/viewer/PdfProtectionStatus";import { usePdfAccess } from "@editor/hooks/usePdfAccess";-import { canPrintPdf } from "@editor/services/pdfPermissions";+import { canPrintPdf, pdfEditingLocked } from "@editor/services/pdfPermissions";import { PdfPreviewUnlockGate } from "@editor/components/viewer/PdfPreviewUnlockGate";import { PdfViewerToolbar } from "@editor/components/viewer/PdfViewerToolbar";import { ThumbnailSidebar } from "@editor/components/viewer/ThumbnailSidebar";@@ -48,6 +48,7 @@ import type {} from "@editor/components/viewer/viewerTypes";import { createStirlingFilesAndStubs } from "@editor/services/fileStubHelpers";import { rememberPlainPdfExport } from "@editor/services/pdfAccessService";+import { assertSignedPdfsEditable } from "@editor/services/pdfSessionUnlock";import { hasUnsavedWork } from "@editor/services/unsavedWork";import {isStirlingFile,@@ -1307,6 +1308,7 @@ const EmbedPdfViewerContent = ({layerApplyInProgressRef.current = true;try {+ await assertSignedPdfsEditable([currentFile], undefined, true);const filename = currentFile.name || "document.pdf";const file = new File([modifiedBlob], filename, {type: "application/pdf",@@ -1964,15 +1966,15 @@ const EmbedPdfViewerContent = ({: undefined}enableAnnotations={- shouldEnableAnnotations && !!pdfAccess && !pdfAccess.encrypted+ shouldEnableAnnotations && !pdfEditingLocked(pdfAccess)}isSignMode={selectedTool === "sign"}showBakedAnnotations={isAnnotationsVisible}enableRedaction={- shouldEnableRedaction && !!pdfAccess && !pdfAccess.encrypted+ shouldEnableRedaction && !pdfEditingLocked(pdfAccess)}enableFormFill={- shouldEnableFormFill && !!pdfAccess && !pdfAccess.encrypted+ shouldEnableFormFill && !pdfEditingLocked(pdfAccess)}formEditingActive={isFormFillToolActive}isManualRedactionMode={isManualRedactMode}@@ -2090,6 +2092,7 @@ const EmbedPdfViewerContent = ({documentCacheKey={bookmarkCacheKey}onApplyLayers={handleLayerApply}onLayersDetected={setHasLayers}+ readOnly={pdfEditingLocked(pdfAccess)}/></Box>);diff --git a/frontend/src/editor/core/components/viewer/ExportAPIBridge.tsx b/frontend/src/editor/core/components/viewer/ExportAPIBridge.tsxindex 8d3e844799..c0e3a83873 100644--- a/frontend/src/editor/core/components/viewer/ExportAPIBridge.tsx+++ b/frontend/src/editor/core/components/viewer/ExportAPIBridge.tsx@@ -3,7 +3,7 @@ import { useExportCapability } from "@embedpdf/plugin-export/react";import { useViewer } from "@editor/contexts/ViewerContext";import { useDocumentReady } from "@editor/components/viewer/hooks/useDocumentReady";-/** Supply originalFile for protected, read-only documents: native export can remove their encryption. */+/** Supply originalFile for read-only documents whose bytes must survive export: native export can remove encryption and invalidates signatures. */export function ExportAPIBridge({disabled = false,originalFile,diff --git a/frontend/src/editor/core/components/viewer/LayerSidebar.tsx b/frontend/src/editor/core/components/viewer/LayerSidebar.tsxindex 047d4574cf..90d815f395 100644--- a/frontend/src/editor/core/components/viewer/LayerSidebar.tsx+++ b/frontend/src/editor/core/components/viewer/LayerSidebar.tsx@@ -29,6 +29,7 @@ interface LayerSidebarProps {onApplyLayers: (modifiedBlob: Blob) => Promise<void>;/** Called when layer detection completes, reporting whether the PDF has layers. */onLayersDetected?: (hasLayers: boolean) => void;+ readOnly?: boolean;}type LoadStatus = "idle" | "loading" | "ready" | "no-layers" | "error";@@ -39,6 +40,7 @@ export function LayerSidebar({file,documentCacheKey,onApplyLayers,+ readOnly = false,onLayersDetected,}: LayerSidebarProps) {const { t } = useTranslation();@@ -168,12 +170,17 @@ export function LayerSidebar({return () => clearTimeout(timer);}, [visibility, file, layers, isApplying, onApplyLayers]);- const toggleLayerVisibility = useCallback((id: string) => {- userChangedRef.current = true;- setVisibility((prev) => ({ ...prev, [id]: !prev[id] }));- }, []);+ const toggleLayerVisibility = useCallback(+ (id: string) => {+ if (readOnly) return;+ userChangedRef.current = true;+ setVisibility((prev) => ({ ...prev, [id]: !prev[id] }));+ },+ [readOnly],+ );const showAll = useCallback(() => {+ if (readOnly) return;userChangedRef.current = true;setVisibility((prev) => {const updated: Record<string, boolean> = {};@@ -182,9 +189,10 @@ export function LayerSidebar({}return updated;});- }, []);+ }, [readOnly]);const hideAll = useCallback(() => {+ if (readOnly) return;userChangedRef.current = true;setVisibility((prev) => {const updated: Record<string, boolean> = {};@@ -193,7 +201,7 @@ export function LayerSidebar({}return updated;});- }, []);+ }, [readOnly]);const toggleExpanded = useCallback((id: string) => {setExpanded((prev) => ({ ...prev, [id]: !(prev[id] ?? true) }));@@ -262,6 +270,7 @@ export function LayerSidebar({<Checkboxsize="xs"checked={visibility[layer.id] ?? layer.visible}+ disabled={readOnly}onChange={() => toggleLayerVisibility(layer.id)}onClick={(e) => e.stopPropagation()}style={{ flexShrink: 0 }}@@ -306,7 +315,7 @@ export function LayerSidebar({variant="tertiary"size="sm"onClick={showAll}- disabled={allVisible || isApplying}+ disabled={readOnly || allVisible || isApplying}aria-label={t("viewer.layers.showAll", "Show all layers")}title={t("viewer.layers.showAll", "Show all layers")}>@@ -316,7 +325,7 @@ export function LayerSidebar({variant="tertiary"size="sm"onClick={hideAll}- disabled={allHidden || isApplying}+ disabled={readOnly || allHidden || isApplying}aria-label={t("viewer.layers.hideAll", "Hide all layers")}title={t("viewer.layers.hideAll", "Hide all layers")}>diff --git a/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx b/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsxindex 90ffd96823..664d63886f 100644--- a/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx@@ -71,6 +71,7 @@ import {RedactionLayer,} from "@embedpdf/plugin-redaction/react";import { CustomSearchLayer } from "@editor/components/viewer/CustomSearchLayer";+import { useActiveUrlSource } from "@editor/components/viewer/useActiveUrlSource";import { ZoomAPIBridge } from "@editor/components/viewer/ZoomAPIBridge";import { Center, Loader, Stack, Text } from "@mantine/core";import { ScrollAPIBridge } from "@editor/components/viewer/ScrollAPIBridge";@@ -110,7 +111,12 @@ import { DocumentSwapBridge } from "@editor/components/viewer/DocumentSwapBridgeimport { PdfPasswordBridge } from "@editor/components/viewer/PdfPasswordBridge";import { isStirlingFile } from "@editor/types/fileContext";import type { FileId } from "@editor/types/file";-import { pdfAllows, canPrintPdf } from "@editor/services/pdfPermissions";+import {+ pdfAllows,+ canPrintPdf,+ pdfEditingLocked,+} from "@editor/services/pdfPermissions";+import { signedPdfEditsBlocked } from "@editor/services/pdfAccessService";import { PdfPermissionFlag } from "@embedpdf/models";import { usePdfAccess } from "@editor/hooks/usePdfAccess";@@ -935,13 +941,16 @@ export function LocalEmbedPDF({}: LocalEmbedPDFProps) {const { t } = useTranslation();const { config } = useAppConfig();- const [urlSource, setUrlSource] = useState<File | null>(null);+ const {+ source: urlSource,+ stage: stageUrlSource,+ settle: settleUrlSource,+ } = useActiveUrlSource();const pdfAccess = usePdfAccess(file ?? urlSource ?? fileId);const permissionOverride =pdfAccess?.ownerAuthenticated === true ||(pdfAccess?.honorOwnerPasswords ?? config?.honorOwnerPasswords) === false;- const annotationsReadOnly =- !pdfAccess || pdfAccess.encrypted || !enableAnnotations;+ const annotationsReadOnly = pdfEditingLocked(pdfAccess) || !enableAnnotations;const [pdfUrl, setPdfUrl] = useState<string | null>(() => url ?? null);const [, setAnnotations] = useState<Array<{ id: string; pageIndex: number; rect: Rect }>@@ -1216,7 +1225,7 @@ export function LocalEmbedPDF({const buf = await source.arrayBuffer();if (!cancelled) {bindPdfViewerSource(buf, source);- setUrlSource(source);+ stageUrlSource(url, source, !initialDocumentOpenedRef.current);openDocument(buf, exportFileName, url);}})@@ -1278,6 +1287,7 @@ export function LocalEmbedPDF({const handleDocumentSwapped = useCallback((documentId: string, fileKey: string) => {+ settleUrlSource(fileKey, true);onDocumentReady?.(fileKey);onDocumentSwapped?.(documentId);setPendingDocument((pending) =>@@ -1286,7 +1296,7 @@ export function LocalEmbedPDF({setSwapAnnouncement(t("viewer.documentUpdated", "Document updated"));setTimeout(() => setSwapAnnouncement(null), 3000);},- [onDocumentReady, onDocumentSwapped, t],+ [onDocumentReady, onDocumentSwapped, settleUrlSource, t],);const handleDocumentSwapFailed = useCallback((fileKey: string, error: unknown) => {@@ -1295,13 +1305,19 @@ export function LocalEmbedPDF({"[LocalEmbedPDF] Replacement document failed to open:",error,);+ settleUrlSource(fileKey, false);onDocumentLoadFailed?.(fileKey, error);if (fileKey === fileStableKey) onDocumentSwapFailed?.(error);setPendingDocument((pending) =>pending?.fileKey === fileKey ? null : pending,);},- [onDocumentLoadFailed, onDocumentSwapFailed, fileStableKey],+ [+ onDocumentLoadFailed,+ onDocumentSwapFailed,+ fileStableKey,+ settleUrlSource,+ ],);useEffect(() => {@@ -1716,8 +1732,18 @@ export function LocalEmbedPDF({onPasswordRequired={onPasswordRequired}/><ExportAPIBridge- originalFile={pdfAccess?.encrypted ? file : undefined}- disabled={pdfAccess?.encrypted && !file}+ originalFile={+ pdfAccess?.encrypted+ ? file+ : signedPdfEditsBlocked(pdfAccess)+ ? (file ?? urlSource ?? undefined)+ : undefined+ }+ disabled={+ pendingDocument !== null ||+ (pdfAccess?.encrypted && !file) ||+ (signedPdfEditsBlocked(pdfAccess) && !file && !urlSource)+ }/><BookmarkAPIBridge /><AttachmentAPIBridge />diff --git a/frontend/src/editor/core/components/viewer/PdfProtectionStatus.tsx b/frontend/src/editor/core/components/viewer/PdfProtectionStatus.tsxindex 54e35748fb..e4ec464b12 100644--- a/frontend/src/editor/core/components/viewer/PdfProtectionStatus.tsx+++ b/frontend/src/editor/core/components/viewer/PdfProtectionStatus.tsx@@ -1,3 +1,7 @@+import {+ SignedPdfEditsBlockedError,+ signedPdfEditsBlockedMessage,+} from "@editor/services/pdfSessionUnlock";import { useState } from "react";import { Group, Modal, Stack, Text } from "@mantine/core";import { Tooltip } from "@editor/components/shared/Tooltip";@@ -13,6 +17,28 @@ import { usePdfAccess } from "@editor/hooks/usePdfAccess";import type { StirlingFile } from "@editor/types/fileContext";import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@editor/styles/zIndex";import { hasPdfPermissionOverride } from "@editor/services/pdfPermissions";+import { signedPdfEditsBlocked } from "@editor/services/pdfAccessService";++function SignedPdfLockedStatus() {+ const { t } = useTranslation();+ return (+ <Group gap="xs" px="sm" py={4}>+ <Tooltip+ content={signedPdfEditsBlockedMessage()}+ position="bottom"+ maxWidth={280}+ arrow+ >+ <Group gap={6} role="status" tabIndex={0}>+ <Icon name="signature" size={14} />+ <Text size="xs">+ {t("signedPdf.editsBlockedStatus", "Signed: edits blocked")}+ </Text>+ </Group>+ </Tooltip>+ </Group>+ );+}/** Persistent document settings; authentication is requested only when an action needs it. */export function PdfProtectionStatus({ file }: { file: StirlingFile }) {@@ -24,7 +50,8 @@ export function PdfProtectionStatus({ file }: { file: StirlingFile }) {const [confirmCopy, setConfirmCopy] = useState(false);const [error, setError] = useState<string | null>(null);const [busy, setBusy] = useState(false);- if (!access?.encrypted) return null;+ if (!access?.encrypted)+ return signedPdfEditsBlocked(access) ? <SignedPdfLockedStatus /> : null;const close = () => {setOpened(false);setConfirmCopy(false);@@ -60,12 +87,14 @@ export function PdfProtectionStatus({ file }: { file: StirlingFile }) {try {await fileActions.createUnprotectedCopy(file.fileId);close();- } catch {+ } catch (error) {setError(- t(- "encryptedPdfUnlock.copyFailed",- "Unable to create the copy. Your PDF is unchanged.",- ),+ error instanceof SignedPdfEditsBlockedError+ ? error.message+ : t(+ "encryptedPdfUnlock.copyFailed",+ "Unable to create the copy. Your PDF is unchanged.",+ ),);setOpened(true);} finally {@@ -197,7 +226,9 @@ export function PdfProtectionStatus({ file }: { file: StirlingFile }) {: t("encryptedPdfUnlock.actionUnlocked","{{action}} unlocked for this session",- { action: label },+ {+ action: label,+ },)}>diff --git a/frontend/src/editor/core/components/viewer/pdfViewerAccess.test.ts b/frontend/src/editor/core/components/viewer/pdfViewerAccess.test.tsindex b9f878f0e1..ebadbb39e8 100644--- a/frontend/src/editor/core/components/viewer/pdfViewerAccess.test.ts+++ b/frontend/src/editor/core/components/viewer/pdfViewerAccess.test.ts@@ -44,7 +44,7 @@ const protectedAccess = {pageCount: 1,};-function viewer(file: File) {+function viewer(file: File, signatureCount = 0) {const buffer = new ArrayBuffer(8);bindPdfViewerSource(buffer, file);const opened = PdfTaskHelper.create<PdfDocumentObject>();@@ -52,6 +52,11 @@ function viewer(file: File) {const raw = {openDocumentBuffer: vi.fn(() => opened),closeDocument: close,+ getSignatures: vi.fn(() =>+ PdfTaskHelper.resolve(+ new Array(signatureCount).fill({ contents: new ArrayBuffer(8) }),+ ),+ ),};const engine = withPdfViewerAccess(raw as unknown as PdfEngine<Blob>);return { engine, opened, close, raw, buffer };@@ -81,6 +86,69 @@ describe("viewer permission readiness", () => {expect(read).not.toHaveBeenCalled();});+ it("closes the document and records nothing when cancelled while signatures are read", async () => {+ const file = new File(["PDF"], "signed.pdf");+ const { engine, opened, close, raw, buffer } = viewer(file);+ const signatures = PdfTaskHelper.create<{ contents: ArrayBuffer }[]>();+ raw.getSignatures.mockReturnValue(signatures as never);+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });+ task.wait(+ () => {},+ () => {},+ );+ opened.resolve(document);+ task.abort({ code: PdfErrorCode.Cancelled, message: "switched" });+ signatures.resolve([{ contents: new ArrayBuffer(8) }]);+ expect(close).toHaveBeenCalledOnce();+ expect(getPdfAccess(file)).toBeUndefined();+ });++ it("records whether an unencrypted PDF is signed from the document it opened", async () => {+ const file = new File(["PDF"], "signed.pdf");+ const read = vi.fn();+ Object.defineProperty(file, "arrayBuffer", { value: read });+ const { engine, opened, raw, buffer } = viewer(file, 1);+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });+ opened.resolve(document);+ await task.toPromise();+ expect(getPdfAccess(file)).toMatchObject({+ encrypted: false,+ signed: true,+ });+ expect(raw.getSignatures).toHaveBeenCalledExactlyOnceWith(document);+ expect(read).not.toHaveBeenCalled();+ });++ it("does not treat an empty signature field as a signature", async () => {+ const file = new File(["PDF"], "blank-signature-field.pdf");+ const { engine, opened, raw, buffer } = viewer(file);+ raw.getSignatures.mockReturnValue(+ PdfTaskHelper.resolve([{ contents: new ArrayBuffer(0) }]),+ );+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });+ opened.resolve(document);+ await task.toPromise();+ expect(getPdfAccess(file)).toMatchObject({ signed: false });+ });++ it("treats a PDF whose signatures cannot be read as signed", async () => {+ const file = new File(["PDF"], "unreadable-signatures.pdf");+ const { engine, opened, raw, buffer } = viewer(file);+ raw.getSignatures.mockReturnValue(+ PdfTaskHelper.reject({+ code: PdfErrorCode.Unknown,+ message: "signature read failed",+ }),+ );+ const task = engine.openDocumentBuffer({ id: "opened", content: buffer });+ opened.resolve(document);+ await task.toPromise();+ expect(getPdfAccess(file)).toMatchObject({+ encrypted: false,+ signed: true,+ });+ });+it("does not publish unrestricted access while encrypted authentication is pending", async () => {const file = new File(["protected"], "large.pdf");Object.defineProperty(file, "size", { value: 125 * 1024 ** 2 });diff --git a/frontend/src/editor/core/components/viewer/pdfViewerAccess.ts b/frontend/src/editor/core/components/viewer/pdfViewerAccess.tsindex f4aef83b73..d402bbc530 100644--- a/frontend/src/editor/core/components/viewer/pdfViewerAccess.ts+++ b/frontend/src/editor/core/components/viewer/pdfViewerAccess.ts@@ -71,8 +71,36 @@ export function withPdfViewerAccess(engine: PdfEngine<Blob>): PdfEngine<Blob> {return;}if (!document.isEncrypted) {- rememberUnencryptedPdf(source, document.pageCount);- task.resolve(document);+ // Second read of `signed`; belongs to the probe in workers/pdfAccessWorker.ts.+ const publish = (signed: boolean) => {+ if (!isCurrent()) {+ close();+ task.abort({+ code: PdfErrorCode.Cancelled,+ message: "PDF opening cancelled.",+ });+ return;+ }+ rememberUnencryptedPdf(source, document.pageCount, signed);+ task.resolve(document);+ };+ const signatures = engine.getSignatures(document);+ cancellation.signal.addEventListener(+ "abort",+ () =>+ signatures.abort({+ code: PdfErrorCode.Cancelled,+ message: "PDF opening cancelled.",+ }),+ { once: true },+ );+ signatures.wait(+ (found) =>+ publish(+ found.some((signature) => signature.contents.byteLength > 0),+ ),+ () => publish(true),+ );return;}void ensureLocalPdfAccess(diff --git a/frontend/src/editor/core/components/viewer/useActiveUrlSource.test.ts b/frontend/src/editor/core/components/viewer/useActiveUrlSource.test.tsnew file mode 100644index 0000000000..2a50ab083e--- /dev/null+++ b/frontend/src/editor/core/components/viewer/useActiveUrlSource.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { useActiveUrlSource } from "@editor/components/viewer/useActiveUrlSource";++const pdf = (name: string) =>+ new File([name], name, { type: "application/pdf" });++describe("the source of the document the viewer shows", () => {+ it("uses the first document's bytes as soon as they are fetched", () => {+ const { result } = renderHook(() => useActiveUrlSource());+ const first = pdf("first.pdf");+ act(() => result.current.stage("a", first, true));+ expect(result.current.source).toBe(first);+ });++ it("keeps the outgoing bytes until a replacement lands", () => {+ const { result } = renderHook(() => useActiveUrlSource());+ const first = pdf("first.pdf");+ const second = pdf("second.pdf");+ act(() => result.current.stage("a", first, true));+ act(() => result.current.stage("b", second, false));+ expect(result.current.source).toBe(first);+ act(() => result.current.settle("b", true));+ expect(result.current.source).toBe(second);+ });++ it("keeps the outgoing bytes when the replacement fails to open", () => {+ const { result } = renderHook(() => useActiveUrlSource());+ const first = pdf("first.pdf");+ act(() => result.current.stage("a", first, true));+ act(() => result.current.stage("b", pdf("second.pdf"), false));+ act(() => result.current.settle("b", false));+ expect(result.current.source).toBe(first);+ act(() => result.current.settle("b", true));+ expect(result.current.source).toBe(first);+ });++ it("ignores the outcome of a replacement that was superseded", () => {+ const { result } = renderHook(() => useActiveUrlSource());+ const first = pdf("first.pdf");+ const third = pdf("third.pdf");+ act(() => result.current.stage("a", first, true));+ act(() => result.current.stage("b", pdf("second.pdf"), false));+ act(() => result.current.stage("c", third, false));+ act(() => result.current.settle("b", true));+ expect(result.current.source).toBe(first);+ act(() => result.current.settle("c", true));+ expect(result.current.source).toBe(third);+ });+});diff --git a/frontend/src/editor/core/components/viewer/useActiveUrlSource.ts b/frontend/src/editor/core/components/viewer/useActiveUrlSource.tsnew file mode 100644index 0000000000..f0b8af5fd5--- /dev/null+++ b/frontend/src/editor/core/components/viewer/useActiveUrlSource.ts@@ -0,0 +1,27 @@+import { useCallback, useRef, useState } from "react";++/**+ * The fetched bytes of the document the viewer shows. A replacement is held aside until its swap+ * lands, so export and access never describe a document that is not on screen; a failed swap+ * drops it and the outgoing source stays.+ */+export function useActiveUrlSource() {+ const [source, setSource] = useState<File | null>(null);+ const pending = useRef<{ key: string; source: File } | null>(null);++ const stage = useCallback((key: string, next: File, initial: boolean) => {+ if (initial) {+ pending.current = null;+ setSource(next);+ } else pending.current = { key, source: next };+ }, []);++ const settle = useCallback((key: string, landed: boolean) => {+ const staged = pending.current;+ if (staged?.key !== key) return;+ pending.current = null;+ if (landed) setSource(staged.source);+ }, []);++ return { source, stage, settle };+}diff --git a/frontend/src/editor/core/contexts/AppConfigContext.tsx b/frontend/src/editor/core/contexts/AppConfigContext.tsxindex 1ed1888da7..2d047581b4 100644--- a/frontend/src/editor/core/contexts/AppConfigContext.tsx+++ b/frontend/src/editor/core/contexts/AppConfigContext.tsx@@ -18,7 +18,10 @@ import type {AppConfigBootstrapMode,} from "@editor/types/appConfig";import { useJwtConfigSync } from "@editor/hooks/useJwtConfigSync";-import { setPdfAccessPolicy } from "@editor/services/pdfAccessService";+import {+ setPdfAccessPolicy,+ setSignedPdfEditPolicy,+} from "@editor/services/pdfAccessService";export interface AppConfigRetryOptions {maxRetries?: number;@@ -172,6 +175,10 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({setPdfAccessPolicy(value.config?.honorOwnerPasswords !== false);}, [value.config?.honorOwnerPasswords]);+ useLayoutEffect(() => {+ setSignedPdfEditPolicy(value.config?.blockSignedPdfEdits === true);+ }, [value.config?.blockSignedPdfEdits]);+useLayoutEffect(() => () => setPdfAccessPolicy(true), []);return (diff --git a/frontend/src/editor/core/contexts/FileContext.tsx b/frontend/src/editor/core/contexts/FileContext.tsxindex 72e5067d2b..29934d9b2e 100644--- a/frontend/src/editor/core/contexts/FileContext.tsx+++ b/frontend/src/editor/core/contexts/FileContext.tsx@@ -21,6 +21,7 @@ import {useRef,useMemo,useState,+ useSyncExternalStore,} from "react";import {FileContextProviderProps,@@ -70,6 +71,7 @@ import EncryptedPdfUnlockModal from "@editor/components/shared/EncryptedPdfUnlocimport { useTranslation } from "react-i18next";import {inspectLocalPdfAccess,+ ensureLocalPdfAccess,bindPdfAccess,clearPdfAccess,forgetPdfAccess,@@ -77,6 +79,9 @@ import {getPdfAccess,pdfAccessLifetime,rememberPdfAccess,+ signedPdfEditPolicyOn,+ signedPdfEditsBlocked,+ subscribePdfAccess,type PdfAccess,} from "@editor/services/pdfAccessService";import { alert } from "@editor/components/toast";@@ -88,6 +93,7 @@ import {setPendingUnlocks,} from "@editor/services/pendingUnlocks";import { handlePasswordError } from "@editor/utils/toolErrorHandler";+import { SignedPdfEditsBlockedError } from "@editor/services/pdfSessionUnlock";import apiClient from "@editor/services/apiClient";import { buildRemovePasswordFormData } from "@editor/hooks/tools/removePassword/buildRemovePasswordFormData";import { combineAbortSignals } from "@editor/utils/combineAbortSignals";@@ -470,6 +476,54 @@ function FileContextInner({[], // Empty deps - selectors are stable);+ // While signed PDFs are locked, selected files are read before a tool needs them, so a signed+ // file shows as locked rather than being refused at Run. Known-encrypted files wait for the+ // unlock prompt instead.+ const selectionProbes = useRef(new Map<FileId, AbortController>());+ const readSelectedFiles = useSyncExternalStore(+ subscribePdfAccess,+ signedPdfEditPolicyOn,+ );+ useEffect(() => {+ const probes = selectionProbes.current;+ const selected = new Set(readSelectedFiles ? state.ui.selectedFileIds : []);+ for (const [fileId, probe] of probes)+ if (!selected.has(fileId)) {+ probe.abort();+ probes.delete(fileId);+ }+ for (const fileId of selected) {+ const file = selectors.getFile(fileId);+ if (+ probes.has(fileId) ||+ !file ||+ getPdfAccess(file) ||+ state.files.byId[fileId]?.processedFile?.isEncrypted ||+ (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name))+ )+ continue;+ const probe = new AbortController();+ probes.set(fileId, probe);+ void ensureLocalPdfAccess(file, probe.signal)+ .catch(() => {})+ .finally(() => {+ if (probes.get(fileId) === probe) probes.delete(fileId);+ });+ }+ }, [+ readSelectedFiles,+ state.ui.selectedFileIds,+ state.files.byId,+ selectors,+ ]);+ useEffect(() => {+ const probes = selectionProbes.current;+ return () => {+ for (const probe of probes.values()) probe.abort();+ probes.clear();+ };+ }, []);+// Navigation management removed - moved to NavigationContext// Navigation guard system functions@@ -844,6 +898,7 @@ function FileContextInner({"Enter the permissions password to continue.",),);+ if (signedPdfEditsBlocked(access)) throw new SignedPdfEditsBlockedError();const file = filesRef.current.get(fileId);if (!file)throw new Error(@@ -860,13 +915,18 @@ function FileContextInner({const response = await apiClient.post<Blob>("/api/v1/security/remove-password",form,- { responseType: "blob", suppressErrorToast: true },+ {+ responseType: "blob",+ suppressErrorToast: true,+ },);if (filesRef.current.get(fileId) !== file) return;const copy = new File([response.data],`${file.name.replace(/\.pdf$/i, "")}_unprotected.pdf`,- { type: "application/pdf" },+ {+ type: "application/pdf",+ },);const copyAccess = await inspectLocalPdfAccess(copy,@@ -904,6 +964,7 @@ function FileContextInner({try {const access = await inspectLocalPdfAccess(file, unlockPassword, signal);if (filesRef.current.get(fileId) !== file) return;+ if (signedPdfEditsBlocked(access)) throw new SignedPdfEditsBlockedError();if (openingPasswordToRemove === null) {if (!access.ownerAuthenticated) {setOpeningPasswordToRemove(unlockPassword);@@ -927,13 +988,19 @@ function FileContextInner({const response = await apiClient.post<Blob>("/api/v1/security/remove-password",form,- { responseType: "blob", suppressErrorToast: true, signal },+ {+ responseType: "blob",+ suppressErrorToast: true,+ signal,+ },);if (filesRef.current.get(fileId) !== file) return;const copy = new File([response.data],`${file.name.replace(/\.pdf$/i, "")}_password_removed.pdf`,- { type: "application/pdf" },+ {+ type: "application/pdf",+ },);const copyAccess = await inspectLocalPdfAccess(copy, "", signal);await admitProtectionCopy(fileId, file, copy, copyAccess);@@ -941,14 +1008,16 @@ function FileContextInner({} catch (error) {if (signal.aborted) return;setUnlockError(- await handlePasswordError(- error,- t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),- t(- "removePassword.error.failed",- "An error occurred while removing the password from the PDF.",- ),- ),+ error instanceof SignedPdfEditsBlockedError+ ? error.message+ : await handlePasswordError(+ error,+ t("encryptedPdfUnlock.incorrectPassword", "Incorrect password"),+ t(+ "removePassword.error.failed",+ "An error occurred while removing the password from the PDF.",+ ),+ ),);} finally {dispose();diff --git a/frontend/src/editor/core/data/settingsSearchIndex.ts b/frontend/src/editor/core/data/settingsSearchIndex.tsindex 4e3cf792d7..16a8973ed5 100644--- a/frontend/src/editor/core/data/settingsSearchIndex.ts+++ b/frontend/src/editor/core/data/settingsSearchIndex.ts@@ -279,6 +279,13 @@ export const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = ["honorOwnerPasswords",],},+ {+ section: "adminSecurity",+ anchor: "pdfPermissions",+ labelKey: "admin.settings.security.blockSignedPdfEdits.label",+ labelFallback: "Block changes to signed PDFs",+ keywords: ["pdf", "signed", "signature", "edit", "blockSignedPdfEdits"],+ },{section: "adminDatabase",anchor: "adminDatabase",diff --git a/frontend/src/editor/core/hooks/tools/shared/useBaseTool.ts b/frontend/src/editor/core/hooks/tools/shared/useBaseTool.tsindex 29afb86ab4..f84756f4f4 100644--- a/frontend/src/editor/core/hooks/tools/shared/useBaseTool.ts+++ b/frontend/src/editor/core/hooks/tools/shared/useBaseTool.ts@@ -5,6 +5,7 @@ import { BaseToolProps } from "@editor/types/tool";import { ToolOperationHook } from "@editor/hooks/tools/shared/useToolOperation";import { BaseParametersHook } from "@editor/hooks/tools/shared/useBaseParameters";import { StirlingFile } from "@editor/types/fileContext";+import { usePdfAccess } from "@editor/hooks/usePdfAccess";interface BaseToolReturn<TParams,@@ -84,6 +85,7 @@ export function useBaseTool<const { enabled: endpointEnabled, loading: endpointLoading } =useEndpointEnabled(params.getEndpointName());+ usePdfAccess(undefined);// Standard computed state - defined early so it's available in useEffectsconst selectedFiles =operation.getEligibleFiles?.(params.parameters, effectiveFiles) ??diff --git a/frontend/src/editor/core/hooks/tools/shared/useToolOperation.ts b/frontend/src/editor/core/hooks/tools/shared/useToolOperation.tsindex a38c4d97be..902b5aa283 100644--- a/frontend/src/editor/core/hooks/tools/shared/useToolOperation.ts+++ b/frontend/src/editor/core/hooks/tools/shared/useToolOperation.ts@@ -9,10 +9,12 @@ import { useFileContext } from "@editor/contexts/FileContext";import { useNavigationActions } from "@editor/contexts/NavigationContext";import { ViewerContext } from "@editor/contexts/ViewerContext";import { toolAcceptsFile } from "@editor/utils/toolIOCompat";+import { getPdfAccess } from "@editor/services/pdfAccessService";import {prepareUnlockedFile,protectUnlockedResults,preflightPdfOperation,+ signedPdfEditRefused,} from "@editor/services/pdfSessionUnlock";import { useToolState } from "@editor/hooks/tools/shared/useToolState";import {@@ -201,20 +203,35 @@ export const useToolOperation = <TParams>([config, notificationsAvailable],);+ const editsInBrowser = useCallback(+ (endpoint: string | undefined) =>+ !endpoint &&+ config.endpoint === undefined &&+ !!config.customProcessor &&+ config.operationType !== "automate",+ [config.customProcessor, config.endpoint, config.operationType],+ );+const getCompatibleFiles = useCallback((params: TParams, selectedFiles: StirlingFile[]) => {const endpoint =typeof config.endpoint === "function"? config.endpoint(params): config.endpoint;- return selectedFiles.filter((file) =>- toolAcceptsFile(- endpoint ?? undefined,- selectors.getStirlingFileStub(file.fileId) ?? file,- ),+ return selectedFiles.filter(+ (file) =>+ toolAcceptsFile(+ endpoint ?? undefined,+ selectors.getStirlingFileStub(file.fileId) ?? file,+ ) &&+ !signedPdfEditRefused(+ getPdfAccess(file),+ endpoint ?? undefined,+ editsInBrowser(endpoint ?? undefined),+ ),);},- [config.endpoint, selectors],+ [config.endpoint, editsInBrowser, selectors],);const eligibleFilesRef = useRef<StirlingFile[]>([]);@@ -344,6 +361,7 @@ export const useToolOperation = <TParams>((file) =>selectors.getStirlingFileStub(file.fileId)?.processedFile?.isEncrypted === true,+ editsInBrowser(runtimeEndpoint),);if (!permitted) return;let processedFiles: File[];diff --git a/frontend/src/editor/core/services/indexedDBManager.ts b/frontend/src/editor/core/services/indexedDBManager.tsindex 9be3fa4f59..b00bd17284 100644--- a/frontend/src/editor/core/services/indexedDBManager.ts+++ b/frontend/src/editor/core/services/indexedDBManager.ts@@ -539,6 +539,12 @@ export const DATABASE_CONFIGS = {},],} as DatabaseConfig,++ PDF_PROBE: {+ name: "stirling-pdf-probe",+ version: 1,+ stores: [{ name: "facts", keyPath: "fileId" }],+ } as DatabaseConfig,} as const;export const indexedDBManager = IndexedDBManager.getInstance();diff --git a/frontend/src/editor/core/services/pdfAccessService.test.ts b/frontend/src/editor/core/services/pdfAccessService.test.tsindex 7f72e595d0..3479723119 100644--- a/frontend/src/editor/core/services/pdfAccessService.test.ts+++ b/frontend/src/editor/core/services/pdfAccessService.test.ts@@ -7,9 +7,11 @@ import {rememberPdfAccess,type PdfAccess,ensureLocalPdfAccess,+ getPdfDetails,inspectLocalPdfAccess,setPdfAccessPolicy,subscribePdfAccess,+ setSignedPdfEditPolicy,} from "@editor/services/pdfAccessService";import { preflightPdfOperation } from "@editor/services/pdfSessionUnlock";@@ -22,7 +24,11 @@ const workers = vi.hoisted(() =>[] as {onmessage?: (event: {- data: { access: PdfAccess } | { error: string; code: number };+ data:+ | { access: PdfAccess; background?: boolean }+ | { details: { signatures?: unknown[] } }+ | { done: true }+ | { error: string; code: number };}) => void;onerror?: () => void;postMessage: ReturnType<typeof vi.fn>;@@ -102,6 +108,7 @@ describe("local inspection lifetime", () => {expect(workers[0].postMessage).toHaveBeenCalledWith({file,password: "",+ runBackgroundChecks: false,wasmUrl: "/pdfium.wasm",wasmModule: "precompiled-module",}),@@ -110,6 +117,22 @@ describe("local inspection lifetime", () => {await result;});+ it("asks for background checks only while signed PDF edits are blocked", async () => {+ setSignedPdfEditPolicy(true);+ try {+ const result = inspectLocalPdfAccess(new File(["PDF"], "signed.pdf"));+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledWith(+ expect.objectContaining({ runBackgroundChecks: true }),+ ),+ );+ workers[0].onmessage?.({ data: { access } });+ await result;+ } finally {+ setSignedPdfEditPolicy(false);+ }+ });+it("bounds concurrent inspections and drops a cancelled queued file", async () => {const files = Array.from({ length: 4 },@@ -277,8 +300,9 @@ describe("local inspection lifetime", () => {data: { access: { ...access, permissions: -4 } },});await expect(pending).resolves.toBe(true);+ const created = workers.length;await expect(preflight()).resolves.toBe(true);- expect(workers).toHaveLength(1);+ expect(workers).toHaveLength(created);expect(ownerPrompt).not.toHaveBeenCalled();expect(apiClient.post).not.toHaveBeenCalled();});@@ -296,3 +320,157 @@ describe("local inspection lifetime", () => {expect(getPdfAccess(file)).toBeUndefined();});});++describe("warm workers and background signature details", () => {+ const plain: PdfAccess = {+ ...access,+ password: "",+ encrypted: false,+ permissions: -4,+ };+ const details = [{ signerName: "Test Signer", digestMatches: true }];++ it("keeps a worker warm after a small unencrypted file and reuses it", async () => {+ const first = inspectLocalPdfAccess(new File(["PDF"], "a.pdf"));+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledOnce(),+ );+ workers[0].onmessage?.({ data: { access: plain } });+ await first;+ expect(workers[0].terminate).not.toHaveBeenCalled();+ const second = inspectLocalPdfAccess(new File(["PDF"], "b.pdf"));+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledTimes(2),+ );+ expect(workers).toHaveLength(1);+ workers[0].onmessage?.({ data: { access: plain } });+ await second;+ });++ it("does not keep a worker that held a large file", async () => {+ const file = new File(["PDF"], "large.pdf");+ Object.defineProperty(file, "size", { value: 64 * 1024 * 1024 });+ const result = inspectLocalPdfAccess(file);+ workers[0].onmessage?.({ data: { access: plain } });+ await result;+ expect(workers[0].terminate).toHaveBeenCalledOnce();+ });++ it("answers before signature details and publishes them when they arrive", async () => {+ const file = new File(["PDF"], "signed.pdf");+ const result = ensureLocalPdfAccess(file);+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledOnce(),+ );+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await expect(result).resolves.toMatchObject({ signed: true });+ expect(getPdfDetails(file)?.signatures).toBeUndefined();+ workers[0].onmessage?.({ data: { details: { signatures: details } } });+ expect(getPdfDetails(file)?.signatures).toEqual(details);+ expect(workers[0].postMessage).toHaveBeenCalledOnce();+ workers[0].onmessage?.({ data: { done: true } });+ expect(workers[0].terminate).not.toHaveBeenCalled();+ const next = inspectLocalPdfAccess(new File(["PDF"], "next.pdf"));+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledTimes(2),+ );+ expect(workers).toHaveLength(1);+ workers[0].onmessage?.({ data: { access: plain } });+ await next;+ });++ it("discards signature details for a file closed before they arrive", async () => {+ const file = createStirlingFile(new File(["PDF"], "signed.pdf"));+ bindPdfAccess(file, file.fileId);+ const result = ensureLocalPdfAccess(file);+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await result;+ forgetPdfAccess([file.fileId]);+ expect(workers[0].terminate).toHaveBeenCalledOnce();+ workers[0].onmessage?.({ data: { details: { signatures: details } } });+ workers[0].onmessage?.({ data: { done: true } });+ expect(getPdfDetails(file)?.signatures).toBeUndefined();+ });++ it("retires idle workers and clears details on logout", async () => {+ vi.useFakeTimers();+ const file = new File(["PDF"], "signed.pdf");+ const result = ensureLocalPdfAccess(file);+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await result;+ workers[0].onmessage?.({ data: { details: { signatures: details } } });+ workers[0].onmessage?.({ data: { done: true } });+ clearPdfAccess();+ expect(workers[0].terminate).toHaveBeenCalledOnce();+ expect(getPdfDetails(file)?.signatures).toBeUndefined();+ const again = inspectLocalPdfAccess(new File(["PDF"], "c.pdf"));+ workers[1].onmessage?.({ data: { access: plain } });+ await again;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(workers[1].terminate).toHaveBeenCalledOnce();+ });++ it("gives the background checks their own timeout after the blocking answer", async () => {+ vi.useFakeTimers();+ const result = inspectLocalPdfAccess(new File(["PDF"], "signed.pdf"));+ await vi.waitFor(() =>+ expect(workers[0].postMessage).toHaveBeenCalledOnce(),+ );+ await vi.advanceTimersByTimeAsync(20_000);+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await result;+ await vi.advanceTimersByTimeAsync(20_000);+ expect(workers[0].terminate).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(workers[0].terminate).toHaveBeenCalledOnce();+ });++ it("keeps a large file's bytes in the memory budget while its background checks run", async () => {+ const sized = (name: string) => {+ const file = new File(["PDF"], name);+ Object.defineProperty(file, "size", { value: 80 * 1024 * 1024 });+ return file;+ };+ const first = inspectLocalPdfAccess(sized("a.pdf"));+ const second = inspectLocalPdfAccess(sized("b.pdf"));+ expect(workers).toHaveLength(1);+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await first;+ expect(workers).toHaveLength(1);+ workers[0].onmessage?.({ data: { done: true } });+ await vi.waitFor(() => expect(workers).toHaveLength(2));+ workers[1].onmessage?.({ data: { access: plain } });+ await second;+ });++ it("frees the queue slot once a large signed file's blocking answer arrives", async () => {+ const large = new File(["PDF"], "signed.pdf");+ Object.defineProperty(large, "size", { value: 40 * 1024 * 1024 });+ const signed = inspectLocalPdfAccess(large);+ const second = inspectLocalPdfAccess(new File(["PDF"], "b.pdf"));+ const third = inspectLocalPdfAccess(new File(["PDF"], "c.pdf"));+ expect(workers).toHaveLength(2);+ workers[0].onmessage?.({+ data: { access: { ...plain, signed: true }, background: true },+ });+ await signed;+ expect(workers).toHaveLength(3);+ expect(workers[0].terminate).not.toHaveBeenCalled();+ workers[1].onmessage?.({ data: { access: plain } });+ workers[2].onmessage?.({ data: { access: plain } });+ await Promise.all([second, third]);+ workers[0].onmessage?.({ data: { details: { signatures: details } } });+ workers[0].onmessage?.({ data: { done: true } });+ expect(getPdfDetails(new File(["PDF"], "x.pdf"))).toBeUndefined();+ });+});diff --git a/frontend/src/editor/core/services/pdfAccessService.ts b/frontend/src/editor/core/services/pdfAccessService.tsindex 7ab48d034a..f3272b44b3 100644--- a/frontend/src/editor/core/services/pdfAccessService.ts+++ b/frontend/src/editor/core/services/pdfAccessService.ts@@ -5,7 +5,13 @@ import PdfAccessWorker from "@editor/workers/pdfAccessWorker?worker";import type {PdfAccessRequest,PdfAccessResponse,+ PdfAccessWarmup,} from "@editor/workers/pdfAccessWorker";+import type { PdfProbeDetails } from "@editor/utils/pdfProbeChecks";+import {+ cachePdfAccess,+ readCachedPdfAccess,+} from "@editor/services/pdfProbeCache";import {pdfiumWasmUrl,pdfiumWasmModulePromise,@@ -47,6 +53,23 @@ export function setPdfAccessPolicy(publish();}+let blockSignedPdfEdits = false;+export function setSignedPdfEditPolicy(block: boolean): void {+ if (blockSignedPdfEdits === block) return;+ blockSignedPdfEdits = block;+ publish();+}++export function signedPdfEditPolicyOn(): boolean {+ return blockSignedPdfEdits;+}++export function signedPdfEditsBlocked(+ access: Pick<PdfAccess, "signed"> | undefined,+): boolean {+ return blockSignedPdfEdits && access?.signed === true;+}+/** Aborted by logout or FileContext teardown, independently of individual document closures. */export function pdfAccessSessionLifetime(): AbortSignal {return sessionLifetime.signal;@@ -70,11 +93,12 @@ export function pdfAccessLifetime(file: Blob): AbortSignal {export function rememberUnencryptedPdf(file: Blob,pageCount: number,+ signed = false,): PdfAccess {return rememberPdfAccess(file, {password: "",encrypted: false,- signed: false,+ signed,ownerAuthenticated: false,permissions: -4,pageCount,@@ -85,7 +109,7 @@ export function rememberUnencryptedPdf(export function rememberPlainPdfExport(source: Blob, output: Blob): void {const access = getPdfAccess(source);if (access?.encrypted === false)- rememberUnencryptedPdf(output, access.pageCount);+ rememberUnencryptedPdf(output, access.pageCount, access.signed);}function publish(): void {@@ -185,6 +209,8 @@ export function forgetPreviewPdfAccess(file: Blob, access: PdfAccess): void {/** Clear all credentials on logout or FileContext teardown. */export function clearPdfAccess(): void {+ terminateIdleWorkers();+ detailsByFile = new WeakMap();sessionLifetime.abort();sessionLifetime = new AbortController();accessLifetimes = new WeakMap();@@ -217,23 +243,73 @@ const INSPECTION_TIMEOUT_MS = 30_000;const MAX_INSPECTION_WORKERS = 2;// Each worker holds the input buffer and a WASM copy. Larger files run alone.const INSPECTION_BYTE_BUDGET = 100 * 1024 * 1024;+const WORKER_REUSE_MAX_BYTES = 32 * 1024 * 1024;+const IDLE_WORKER_TTL_MS = 30_000;const inspectionQueue: { size: number; start: () => void }[] = [];+const idleWorkers: Worker[] = [];+let idleWorkerTimer: ReturnType<typeof setTimeout> | undefined;let activeInspections = 0;let inspectingBytes = 0;+let detailsByFile = new WeakMap<Blob, Partial<PdfProbeDetails>>();function drainInspections(): void {while (inspectionQueue.length && activeInspections < MAX_INSPECTION_WORKERS) {const next = inspectionQueue[0];- if (- activeInspections &&- inspectingBytes + next.size > INSPECTION_BYTE_BUDGET- )+ if (inspectingBytes && inspectingBytes + next.size > INSPECTION_BYTE_BUDGET)return;inspectionQueue.shift();next.start();}}+function terminateIdleWorkers(): void {+ clearTimeout(idleWorkerTimer);+ for (const worker of idleWorkers.splice(0)) worker.terminate();+}++function parkWorker(worker: Worker): void {+ idleWorkers.push(worker);+ clearTimeout(idleWorkerTimer);+ idleWorkerTimer = setTimeout(terminateIdleWorkers, IDLE_WORKER_TTL_MS);+}++function startSpareWorker(): void {+ const worker = new PdfAccessWorker();+ parkWorker(worker);+ void pdfiumWasmModulePromise.then((wasmModule) => {+ if (!idleWorkers.includes(worker)) return;+ const warmup: PdfAccessWarmup = {+ warmup: true,+ wasmUrl: pdfiumWasmUrl,+ wasmModule,+ };+ try {+ worker.postMessage(warmup);+ } catch {+ worker.postMessage({ ...warmup, wasmModule: null });+ }+ });+}++function releaseWorker(worker: Worker, reusable: boolean): void {+ worker.onmessage = null;+ worker.onerror = null;+ if (reusable && idleWorkers.length < MAX_INSPECTION_WORKERS) {+ parkWorker(worker);+ return;+ }+ worker.terminate();+ if (idleWorkers.length === 0) startSpareWorker();+}++/** Background probe results for these exact bytes; each key appears once its check has finished. */+export function getPdfDetails(+ file: Blob | string | null | undefined,+): Partial<PdfProbeDetails> | undefined {+ const blob = typeof file === "string" ? filesById.get(file)?.deref() : file;+ return blob ? detailsByFile.get(blob) : undefined;+}+function runInspection(file: Blob,password: string,@@ -243,15 +319,19 @@ function runInspection(let worker: Worker | undefined;let timer: ReturnType<typeof setTimeout> | undefined;let started = false;+ let holdsSlot = false;let finished = false;- const finish = () => {+ let delivered: PdfAccess | undefined;+ const lifetime = pdfAccessLifetime(file);+ const finish = (reusable = false) => {if (finished) return false;finished = true;- worker?.terminate();+ if (worker) releaseWorker(worker, reusable);clearTimeout(timer);signal.removeEventListener("abort", abort);+ lifetime.removeEventListener("abort", abort);if (started) {- activeInspections--;+ if (holdsSlot) activeInspections--;inspectingBytes -= file.size;} else {const index = inspectionQueue.indexOf(queued);@@ -260,9 +340,53 @@ function runInspection(drainInspections();return true;};- const abort = () => {- if (finish())- reject(new DOMException("Operation cancelled", "AbortError"));+ const fail = (error: unknown) => {+ if (finish() && !delivered) reject(error);+ };+ const abort = () =>+ fail(new DOMException("Operation cancelled", "AbortError"));+ const startTimer = () => {+ clearTimeout(timer);+ timer = setTimeout(+ () =>+ fail(+ new DOMException(+ "PDF permission inspection timed out. Try opening the file again.",+ "TimeoutError",+ ),+ ),+ INSPECTION_TIMEOUT_MS,+ );+ };+ const reusable = () =>+ !!delivered &&+ !delivered.encrypted &&+ password === "" &&+ file.size <= WORKER_REUSE_MAX_BYTES;+ const onMessage = ({ data }: MessageEvent<PdfAccessResponse>) => {+ if (finished) return;+ if ("access" in data) {+ delivered = data.access;+ signal.removeEventListener("abort", abort);+ resolve(data.access);+ if (!data.background) finish(reusable());+ else startTimer();+ if (data.background && file.size > WORKER_REUSE_MAX_BYTES) {+ holdsSlot = false;+ activeInspections--;+ drainInspections();+ }+ } else if ("details" in data) {+ if (!lifetime.aborted) {+ detailsByFile.set(file, {+ ...detailsByFile.get(file),+ ...data.details,+ });+ publish();+ }+ } else if ("done" in data) {+ finish(reusable());+ } else fail(Object.assign(new Error(data.error), { code: data.code }));};const queued = {size: file.size,@@ -272,29 +396,15 @@ function runInspection(return;}started = true;+ holdsSlot = true;activeInspections++;inspectingBytes += file.size;- timer = setTimeout(() => {- if (finish())- reject(- new DOMException(- "PDF permission inspection timed out. Try opening the file again.",- "TimeoutError",- ),- );- }, INSPECTION_TIMEOUT_MS);+ startTimer();try {- worker = new PdfAccessWorker();- worker.onmessage = ({ data }: MessageEvent<PdfAccessResponse>) => {- if (!finish()) return;- if ("access" in data) resolve(data.access);- else- reject(Object.assign(new Error(data.error), { code: data.code }));- };- worker.onerror = () => {- if (finish())- reject(new Error("Unable to inspect PDF security locally"));- };+ worker = idleWorkers.pop() ?? new PdfAccessWorker();+ worker.onmessage = onMessage;+ worker.onerror = () =>+ fail(new Error("Unable to inspect PDF security locally"));startEagerWasmCompilation();void pdfiumWasmModulePromise.then((wasmModule) => {@@ -302,6 +412,7 @@ function runInspection(const request: PdfAccessRequest = {file,password,+ runBackgroundChecks: blockSignedPdfEdits,wasmUrl: pdfiumWasmUrl,wasmModule,};@@ -317,16 +428,15 @@ function runInspection(worker!.postMessage({ ...request, wasmModule: null });}})- .catch((error: unknown) => {- if (finish()) reject(error);- });+ .catch(fail);} catch (error) {- if (finish()) reject(error);+ fail(error);}},};signal.addEventListener("abort", abort, { once: true });- if (signal.aborted) abort();+ lifetime.addEventListener("abort", abort, { once: true });+ if (signal.aborted || lifetime.aborted) abort();else {inspectionQueue.push(queued);drainInspections();@@ -411,9 +521,17 @@ export async function ensureLocalPdfAccess(if (existing && (password === undefined || password === existing.password))return existing;const lifetime = pdfAccessLifetime(file);- const access = await inspectLocalPdfAccess(file, password ?? "", signal);- if (signal?.aborted || lifetime.aborted)- throw new DOMException("Session closed", "AbortError");+ const lookup = password ? undefined : readCachedPdfAccess(file);+ const cached = lookup && (await lookup);+ const closed = () => {+ if (signal?.aborted || lifetime.aborted)+ throw new DOMException("Session closed", "AbortError");+ };+ closed();+ const access =+ cached ?? (await inspectLocalPdfAccess(file, password ?? "", signal));+ closed();+ if (!cached) cachePdfAccess(file, access);const current = getPdfAccess(file);return current && current !== existing? currentdiff --git a/frontend/src/editor/core/services/pdfPermissions.ts b/frontend/src/editor/core/services/pdfPermissions.tsindex 3ac28db38c..a4988a902b 100644--- a/frontend/src/editor/core/services/pdfPermissions.ts+++ b/frontend/src/editor/core/services/pdfPermissions.ts@@ -1,4 +1,7 @@-import type { PdfAccess } from "@editor/services/pdfAccessService";+import {+ signedPdfEditsBlocked,+ type PdfAccess,+} from "@editor/services/pdfAccessService";import { PdfPermissionFlag } from "@embedpdf/models";type PermissionAccess = Pick<@@ -46,3 +49,7 @@ export function canPrintPdf(access: PermissionAccess | undefined): boolean {pdfAllows(access, PdfPermissionFlag.PrintHighQuality));}++export function pdfEditingLocked(access: PdfAccess | undefined): boolean {+ return !access || access.encrypted || signedPdfEditsBlocked(access);+}diff --git a/frontend/src/editor/core/services/pdfProbeCache.test.ts b/frontend/src/editor/core/services/pdfProbeCache.test.tsnew file mode 100644index 0000000000..dc0607d3eb--- /dev/null+++ b/frontend/src/editor/core/services/pdfProbeCache.test.ts@@ -0,0 +1,56 @@+import "fake-indexeddb/auto";+import { describe, expect, it } from "vitest";+import { createStirlingFile } from "@editor/types/fileContext";+import {+ cachePdfAccess,+ readCachedPdfAccess,+} from "@editor/services/pdfProbeCache";+import type { PdfAccess } from "@editor/services/pdfAccessService";++const facts: PdfAccess = {+ password: "",+ encrypted: false,+ signed: true,+ ownerAuthenticated: false,+ permissions: -1,+ encryptionRevision: -1,+ pageCount: 3,+};+const pdf = (lastModified: number, body = "%PDF-1.7") =>+ new File([body], "contract.pdf", { type: "application/pdf", lastModified });++async function stored(file: File) {+ await expect.poll(() => readCachedPdfAccess(file)).toBeDefined();+ return readCachedPdfAccess(file);+}++describe("probe facts cache", () => {+ it("returns the facts of the same stored file after a reload", async () => {+ const file = createStirlingFile(pdf(1));+ cachePdfAccess(file, facts);+ await expect(stored(file)).resolves.toMatchObject({+ signed: true,+ pageCount: 3,+ encrypted: false,+ password: "",+ });+ });++ it("ignores the entry once the bytes under that id have changed", async () => {+ const original = createStirlingFile(pdf(2));+ cachePdfAccess(original, facts);+ await stored(original);+ const reloaded = createStirlingFile(+ pdf(3, "%PDF-1.7 edited"),+ original.fileId,+ );+ await expect(readCachedPdfAccess(reloaded)).resolves.toBeUndefined();+ });++ it("never stores encrypted files or files without an id", async () => {+ const encrypted = createStirlingFile(pdf(4));+ cachePdfAccess(encrypted, { ...facts, encrypted: true });+ await expect(readCachedPdfAccess(encrypted)).resolves.toBeUndefined();+ expect(readCachedPdfAccess(pdf(5))).toBeUndefined();+ });+});diff --git a/frontend/src/editor/core/services/pdfProbeCache.ts b/frontend/src/editor/core/services/pdfProbeCache.tsnew file mode 100644index 0000000000..4f7a629955--- /dev/null+++ b/frontend/src/editor/core/services/pdfProbeCache.ts@@ -0,0 +1,95 @@+/**+ * Remembers the blocking probe facts of unencrypted files across reloads, so a stored file is not+ * read again. An entry is trusted only for the same file id, size and lastModified: a new version+ * gets a new id and a file reloaded from disk gets a new lastModified, so changed bytes are always+ * probed afresh. Encrypted files are never stored, because their facts depend on the password.+ * A slow or missing database never delays a check: the lookup gives up and the file is probed.+ */+import {+ DATABASE_CONFIGS,+ indexedDBManager,+} from "@editor/services/indexedDBManager";+import type { PdfAccess } from "@editor/services/pdfAccessService";++type CachedFacts = Pick<+ PdfAccess,+ "signed" | "permissions" | "encryptionRevision" | "pageCount"+>;++interface CacheEntry {+ fileId: string;+ size: number;+ lastModified: number;+ facts: CachedFacts;+}++const STORE = "facts";+const LOOKUP_TIMEOUT_MS = 200;++function identity(file: Blob) {+ const fileId = (file as { fileId?: unknown }).fileId;+ return typeof indexedDB !== "undefined" &&+ typeof fileId === "string" &&+ file instanceof File+ ? { fileId, size: file.size, lastModified: file.lastModified }+ : undefined;+}++async function request<T>(+ mode: IDBTransactionMode,+ run: (store: IDBObjectStore) => IDBRequest<T>,+): Promise<T> {+ const db = await indexedDBManager.openDatabase(DATABASE_CONFIGS.PDF_PROBE);+ return new Promise((resolve, reject) => {+ const pending = run(db.transaction(STORE, mode).objectStore(STORE));+ pending.onsuccess = () => resolve(pending.result);+ pending.onerror = () => reject(pending.error);+ });+}++export function readCachedPdfAccess(+ file: Blob,+): Promise<PdfAccess | undefined> | undefined {+ const key = identity(file);+ return key && lookup(key);+}++async function lookup(+ key: NonNullable<ReturnType<typeof identity>>,+): Promise<PdfAccess | undefined> {+ const entry = await Promise.race([+ request<CacheEntry | undefined>("readonly", (store) =>+ store.get(key.fileId),+ ),+ new Promise<undefined>((resolve) => setTimeout(resolve, LOOKUP_TIMEOUT_MS)),+ ]).catch(() => undefined);+ if (!entry) return undefined;+ if (entry.size !== key.size || entry.lastModified !== key.lastModified) {+ void request("readwrite", (store) => store.delete(key.fileId)).catch(+ () => {},+ );+ return undefined;+ }+ return {+ ...entry.facts,+ password: "",+ encrypted: false,+ ownerAuthenticated: false,+ requiresOpeningPassword: false,+ };+}++export function cachePdfAccess(file: Blob, access: PdfAccess): void {+ const key = identity(file);+ if (!key || access.encrypted || access.password !== "") return;+ const entry: CacheEntry = {+ ...key,+ facts: {+ signed: access.signed,+ permissions: access.permissions,+ encryptionRevision: access.encryptionRevision,+ pageCount: access.pageCount,+ },+ };+ void request("readwrite", (store) => store.put(entry)).catch(() => {});+}diff --git a/frontend/src/editor/core/services/pdfSessionUnlock.signedUnread.test.ts b/frontend/src/editor/core/services/pdfSessionUnlock.signedUnread.test.tsnew file mode 100644index 0000000000..91766b2385--- /dev/null+++ b/frontend/src/editor/core/services/pdfSessionUnlock.signedUnread.test.ts@@ -0,0 +1,193 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { PdfErrorCode } from "@embedpdf/models";+import apiClient from "@editor/services/apiClient";+import { createStirlingFile } from "@editor/types/fileContext";+import { ToolType } from "@editor/hooks/tools/shared/useToolOperation";+import type { ToolRegistry } from "@editor/data/toolsTaxonomy";+import { executeToolOperation } from "@editor/utils/automationExecutor";+import {+ clearPdfAccess,+ ensureLocalPdfAccess,+ inspectLocalPdfAccess,+ rememberPdfAccess,+ setSignedPdfEditPolicy,+ type PdfAccess,+} from "@editor/services/pdfAccessService";+import {+ assertSignedPdfsEditable,+ changePdfSecurity,+ preflightPdfOperation,+ signedPdfEditRefused,+} from "@editor/services/pdfSessionUnlock";++vi.mock("@editor/services/apiClient", () => ({ default: { post: vi.fn() } }));+vi.mock("@editor/services/pdfAccessService", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@editor/services/pdfAccessService")+ >()),+ ensureLocalPdfAccess: vi.fn(),+ inspectLocalPdfAccess: vi.fn(),+}));++const signed: PdfAccess = {+ password: "",+ encrypted: false,+ signed: true,+ ownerAuthenticated: false,+ permissions: -1,+ pageCount: 1,+};+const ensure = vi.mocked(ensureLocalPdfAccess);+const inspect = vi.mocked(inspectLocalPdfAccess);+const unread = () =>+ createStirlingFile(+ new File(["%PDF-1.7"], "signed.pdf", { type: "application/pdf" }),+ );++beforeEach(() => {+ vi.clearAllMocks();+ clearPdfAccess();+ setSignedPdfEditPolicy(true);+ ensure.mockResolvedValue(signed);+ inspect.mockResolvedValue(signed);+});+afterEach(() => setSignedPdfEditPolicy(false));++describe("signed PDFs nobody has opened yet", () => {+ it("refuses a browser-side editor once preflight has read the file", async () => {+ const file = unread();+ await expect(+ preflightPdfOperation(+ [file],+ undefined,+ false,+ vi.fn(),+ undefined,+ undefined,+ true,+ ),+ ).rejects.toThrow("digitally signed");+ expect(ensure).toHaveBeenCalledWith(file, undefined);+ });++ it("lets a tool with no endpoint that only reads the file through", async () => {+ await expect(+ preflightPdfOperation([unread()], undefined, false, vi.fn()),+ ).resolves.toBe(true);+ });++ it("reads the file for add-password without remembering it", async () => {+ await expect(+ preflightPdfOperation(+ [unread()],+ "/api/v1/security/add-password",+ false,+ vi.fn(),+ ),+ ).rejects.toThrow("digitally signed");+ expect(inspect).toHaveBeenCalledOnce();+ expect(ensure).not.toHaveBeenCalled();+ });++ it("does not read password-tool inputs while the setting is off", async () => {+ setSignedPdfEditPolicy(false);+ await expect(+ preflightPdfOperation(+ [unread()],+ "/api/v1/security/add-password",+ false,+ vi.fn(),+ ),+ ).resolves.toBe(true);+ expect(inspect).not.toHaveBeenCalled();+ });++ it("reads a file that needs its opening password before removing protection", async () => {+ const file = unread();+ const form = new FormData();+ form.set("password", "opening");+ await expect(+ changePdfSecurity(file, form, "/api/v1/security/remove-password"),+ ).rejects.toThrow("digitally signed");+ expect(inspect).toHaveBeenCalledWith(file, "opening", undefined);+ expect(apiClient.post).not.toHaveBeenCalled();+ });++ it("refuses a password change on a file whose signed access is already known", async () => {+ const file = unread();+ rememberPdfAccess(file, signed);+ const form = new FormData();+ form.set("password", "new");+ await expect(+ changePdfSecurity(file, form, "/api/v1/security/add-password"),+ ).rejects.toThrow("digitally signed");+ expect(inspect).not.toHaveBeenCalled();+ expect(apiClient.post).not.toHaveBeenCalled();+ });++ it("refuses add-password when the file cannot be checked", async () => {+ inspect.mockRejectedValue(+ new DOMException("PDF permission inspection timed out", "TimeoutError"),+ );+ await expect(+ preflightPdfOperation(+ [unread()],+ "/api/v1/security/add-password",+ false,+ vi.fn(),+ ),+ ).rejects.toThrow("timed out");+ });++ it("leaves a file that needs its opening password to the password the user enters", async () => {+ inspect.mockRejectedValue(+ Object.assign(new Error("password"), { code: PdfErrorCode.Password }),+ );+ await expect(+ preflightPdfOperation(+ [unread()],+ "/api/v1/security/add-password",+ false,+ vi.fn(),+ ),+ ).resolves.toBe(true);+ });++ it("treats an endpoint without declared output as a rewrite", () => {+ expect(signedPdfEditRefused(signed, "/api/v1/form/fill")).toBe(true);+ expect(+ signedPdfEditRefused(signed, "/api/v1/misc/extract-single-attachment"),+ ).toBe(false);+ });++ it("skips reading files when the tool cannot rewrite them", async () => {+ await assertSignedPdfsEditable(+ [unread()],+ "/api/v1/convert/pdf/img",+ false,+ );+ expect(ensure).not.toHaveBeenCalled();+ });++ it("reads every automation step's input, not just the first", async () => {+ const registry = {+ step: {+ operationConfig: {+ operationType: "step",+ toolType: ToolType.singleFile,+ endpoint: "/api/v1/general/rotate-pdf",+ defaultParameters: {},+ buildFormData: () => new FormData(),+ },+ },+ } as unknown as ToolRegistry;+ const intermediate = new File(["%PDF-1.7"], "step-1.pdf", {+ type: "application/pdf",+ });+ await expect(+ executeToolOperation("step", {}, [intermediate], registry),+ ).rejects.toThrow("digitally signed");+ expect(ensure).toHaveBeenCalledWith(intermediate, undefined);+ expect(apiClient.post).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/editor/core/services/pdfSessionUnlock.test.ts b/frontend/src/editor/core/services/pdfSessionUnlock.test.tsindex 0c289bd04c..e7fbd7b9ae 100644--- a/frontend/src/editor/core/services/pdfSessionUnlock.test.ts+++ b/frontend/src/editor/core/services/pdfSessionUnlock.test.ts@@ -9,11 +9,13 @@ import {forgetPdfAccess,getPdfAccess,rememberPdfAccess,+ setSignedPdfEditPolicy,type PdfAccess,} from "@editor/services/pdfAccessService";import {hasPdfPermissionOverride,pdfAllows,+ pdfEditingLocked,} from "@editor/services/pdfPermissions";import {prepareUnlockedFile,@@ -21,8 +23,10 @@ import {assertPdfSessionEditable,preflightPdfOperation,changePdfSecurity,+ signedPdfEditRefused,} from "@editor/services/pdfSessionUnlock";import { PdfPermissionFlag } from "@embedpdf/models";+import { toolAcceptsFile } from "@editor/utils/toolIOCompat";vi.mock("@editor/services/apiClient", () => ({ default: { post: vi.fn() } }));const post = vi.mocked(apiClient.post);@@ -602,3 +606,83 @@ describe("protected split archives", () => {expect(post).not.toHaveBeenCalled();});});++describe("signed PDF edit policy", () => {+ const signedAccess: PdfAccess = {+ ...access,+ password: "",+ encrypted: false,+ signed: true,+ };++ function signedPdf() {+ const file = createStirlingFile(new File(["%PDF-1.7"], "signed.pdf"));+ rememberPdfAccess(file, signedAccess);+ return file;+ }++ const stub = (file: File & { fileId: string }) => ({+ id: file.fileId,+ name: file.name,+ type: "application/pdf",+ });++ afterEach(() => setSignedPdfEditPolicy(false));++ it("leaves signed PDFs editable while the setting is off", async () => {+ const file = signedPdf();+ expect(await preflightPdfOperation([file], rotate, false, vi.fn())).toBe(+ true,+ );+ await expect(prepareUnlockedFile(file, rotate)).resolves.toBe(file);+ expect(pdfEditingLocked(signedAccess)).toBe(false);+ expect(signedPdfEditRefused(signedAccess, rotate)).toBe(false);+ });++ it("refuses every way of rewriting a signed PDF while it is on", async () => {+ setSignedPdfEditPolicy(true);+ const file = signedPdf();+ await expect(+ preflightPdfOperation([file], rotate, false, vi.fn()),+ ).rejects.toThrow("digitally signed");+ await expect(+ prepareUnlockedFile(file, "/api/v1/general/rearrange-pages"),+ ).rejects.toThrow("digitally signed");+ expect(() => assertPdfSessionEditable(signedAccess)).toThrow(+ "digitally signed",+ );+ expect(pdfEditingLocked(signedAccess)).toBe(true);+ expect(signedPdfEditRefused(signedAccess, rotate)).toBe(true);+ expect(post).not.toHaveBeenCalled();+ });++ it.each([+ "/api/v1/security/cert-sign",+ "/api/v1/security/remove-cert-sign",+ "/api/v1/convert/pdf/img",+ ])("still allows %s on a signed PDF", async (endpoint) => {+ setSignedPdfEditPolicy(true);+ const file = signedPdf();+ expect(await preflightPdfOperation([file], endpoint, false, vi.fn())).toBe(+ true,+ );+ await expect(prepareUnlockedFile(file, endpoint)).resolves.toBe(file);+ expect(signedPdfEditRefused(signedAccess, endpoint)).toBe(false);+ expect(toolAcceptsFile(endpoint, stub(file))).toBe(true);+ });++ it("leaves signed PDFs out of tools that rewrite them", () => {+ setSignedPdfEditPolicy(true);+ const file = signedPdf();+ expect(toolAcceptsFile(rotate, stub(file))).toBe(false);+ });++ it("does not block unsigned PDFs", async () => {+ setSignedPdfEditPolicy(true);+ const file = createStirlingFile(new File(["%PDF-1.7"], "plain.pdf"));+ rememberPdfAccess(file, { ...signedAccess, signed: false });+ expect(await preflightPdfOperation([file], rotate, false, vi.fn())).toBe(+ true,+ );+ });+});diff --git a/frontend/src/editor/core/services/pdfSessionUnlock.ts b/frontend/src/editor/core/services/pdfSessionUnlock.tsindex 8779b87797..8562664bc2 100644--- a/frontend/src/editor/core/services/pdfSessionUnlock.ts+++ b/frontend/src/editor/core/services/pdfSessionUnlock.ts@@ -1,16 +1,20 @@import {ensureLocalPdfAccess,getPdfAccess,+ inspectLocalPdfAccess,pdfAccessLifetime,rememberPdfAccess,+ signedPdfEditPolicyOn,+ signedPdfEditsBlocked,type PdfAccess,} from "@editor/services/pdfAccessService";+import { toolIOFor } from "@editor/types/toolIO";import apiClient from "@editor/services/apiClient";import axios, { type CancelToken } from "axios";import i18n from "i18next";import type { StirlingFile } from "@editor/types/fileContext";-import { PdfPermissionFlag } from "@embedpdf/models";+import { PdfErrorCode, PdfPermissionFlag } from "@embedpdf/models";import { zipFileService } from "@editor/services/zipFileService";import {@@ -60,6 +64,119 @@ async function requestWorkingPdf(}}+const SIGNATURE_ENDPOINTS = new Set([+ "/api/v1/security/cert-sign",+ "/api/v1/security/timestamp-pdf",+ "/api/v1/security/remove-cert-sign",+]);++const PASSWORD_ENDPOINTS = new Set([+ "/api/v1/security/add-password",+ "/api/v1/security/remove-password",+]);++/** An endpoint missing from TOOL_IO counts as a rewrite, so it is refused on signed PDFs until it declares its output. */+function rewritesPdf(+ endpoint: string | undefined,+ editsInBrowser: boolean,+): boolean {+ if (!endpoint) return editsInBrowser;+ if (SIGNATURE_ENDPOINTS.has(endpoint)) return false;+ const produces = toolIOFor(endpoint)?.produces;+ return (+ produces === undefined || produces === "PDF" || produces === "PDF_ENCRYPTED"+ );+}++export function signedPdfEditsBlockedMessage(): string {+ return i18n.t(+ "signedPdf.editsBlocked",+ "This PDF is digitally signed, and changes to signed PDFs are turned off. You can still view or print it, convert it to another format, or sign it again.",+ );+}++export class SignedPdfEditsBlockedError extends Error {+ constructor() {+ super(signedPdfEditsBlockedMessage());+ }+}++/** `editsInBrowser` marks a tool with no endpoint that rewrites the PDF itself. */+export function signedPdfEditRefused(+ access: PdfAccess | undefined,+ endpoint: string | undefined,+ editsInBrowser = false,+): boolean {+ return signedPdfEditsBlocked(access) && rewritesPdf(endpoint, editsInBrowser);+}++function assertSignedPdfEditable(+ access: PdfAccess | undefined,+ endpoint: string | undefined,+ editsInBrowser = false,+): void {+ if (signedPdfEditRefused(access, endpoint, editsInBrowser))+ throw new SignedPdfEditsBlockedError();+}++const signedCheckApplies = (+ endpoint: string | undefined,+ editsInBrowser: boolean,+) => signedPdfEditPolicyOn() && rewritesPdf(endpoint, editsInBrowser);++const isPdf = (file: File) =>+ file.type === "application/pdf" || /\.pdf$/i.test(file.name);++/**+ * Access for the signed-PDF check on a file not read yet. Password tools read it without remembering+ * the result, so their own encryption handling is unchanged; a file that needs an opening password+ * cannot be read here, and Remove Password checks it again with the password the user enters.+ */+async function accessForSignedCheck(+ file: File,+ endpoint: string | undefined,+ signal?: AbortSignal,+): Promise<PdfAccess | undefined> {+ const known = getPdfAccess(file);+ if (known) return known;+ if (endpoint && PASSWORD_ENDPOINTS.has(endpoint))+ return inspectForPasswordTool(file, "", signal);+ return ensureAccessUnlessDamaged(file, signal);+}++/** Only a wrong password or unparseable bytes leave the file unread; any other failure refuses the run. */+async function inspectForPasswordTool(+ file: File,+ password: string,+ signal?: AbortSignal,+): Promise<PdfAccess | undefined> {+ try {+ return await inspectLocalPdfAccess(file, password, signal);+ } catch (error) {+ if ((error as { code?: unknown } | null)?.code === PdfErrorCode.Password)+ return undefined;+ if (isDamagedPdfError(error)) return undefined;+ throw error;+ }+}++/** Reads every PDF not read yet, then refuses the run if any is signed and the tool would rewrite it. */+export async function assertSignedPdfsEditable(+ files: readonly File[],+ endpoint: string | undefined,+ editsInBrowser: boolean,+ signal?: AbortSignal,+): Promise<void> {+ if (!signedCheckApplies(endpoint, editsInBrowser)) return;+ for (const file of files)+ if (isPdf(file))+ assertSignedPdfEditable(+ await accessForSignedCheck(file, endpoint, signal),+ endpoint,+ editsInBrowser,+ );+}+/** 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);@@ -71,7 +188,7 @@ export function supportsSessionUnlock(endpoint: string | undefined): boolean {* recorded for them: nothing has proved them unencrypted.*/async function ensureAccessUnlessDamaged(- file: StirlingFile,+ file: File,signal?: AbortSignal,): Promise<PdfAccess | undefined> {try {@@ -91,18 +208,24 @@ export async function preflightPdfOperation(requestOwner: (file: StirlingFile) => Promise<boolean>,signal?: AbortSignal,isKnownEncrypted: (file: StirlingFile) => boolean = () => false,+ editsInBrowser = false,): Promise<boolean> {const protectedFiles: StirlingFile[] = [];const changesProtection =- endpoint === "/api/v1/security/add-password" ||- endpoint === "/api/v1/security/remove-password";+ endpoint !== undefined && PASSWORD_ENDPOINTS.has(endpoint);for (const file of files) {if (signal?.aborted) throw new axios.CanceledError("Operation cancelled");- if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name)) continue;+ if (!isPdf(file)) continue;// Password endpoints validate the requested change themselves; unknown roles need no preflight upload.const access = changesProtection? getPdfAccess(file): await ensureAccessUnlessDamaged(file, signal);+ if (signedCheckApplies(endpoint, editsInBrowser))+ assertSignedPdfEditable(+ access ?? (await accessForSignedCheck(file, endpoint, signal)),+ endpoint,+ editsInBrowser,+ );const encrypted =access?.encrypted ??(endpoint === "/api/v1/security/add-password" && isKnownEncrypted(file));@@ -153,6 +276,7 @@ function operationPermission(endpoint: string | undefined): PdfPermissionFlag {/** Signed protected PDFs remain view-only until their edits can preserve signatures. */export function assertPdfSessionEditable(access: PdfAccess | undefined): void {+ if (signedPdfEditsBlocked(access)) throw new SignedPdfEditsBlockedError();if (access?.encrypted && access.signed)throw new Error(i18n.t(@@ -179,16 +303,12 @@ export async function prepareUnlockedFile(inspectionSignal?: AbortSignal,cancelToken?: CancelToken,): Promise<File> {- if (- endpoint === "/api/v1/security/remove-password" ||- endpoint === "/api/v1/security/add-password"- )- return file;- if (file.type !== "application/pdf" && !/\.pdf$/i.test(file.name))+ if ((endpoint && PASSWORD_ENDPOINTS.has(endpoint)) || !isPdf(file))return file;const access =getPdfAccess(file) ??(await ensureAccessUnlessDamaged(file, inspectionSignal));+ assertSignedPdfEditable(access, endpoint);if (!access?.encrypted) return file;if (!supportsSessionUnlock(endpoint))throw new Error(@@ -258,7 +378,7 @@ async function protectPdfOutput(protectionRestoreError().message,);const file = new File([bytes], output.name, { type: "application/pdf" });- rememberPdfAccess(file, { ...access, signed: false });+ rememberPdfAccess(file, access);return file;}@@ -319,6 +439,15 @@ export async function changePdfSecurity(): Promise<Blob> {const settingProtection = endpoint === "/api/v1/security/add-password";const access = getPdfAccess(file);+ if (signedCheckApplies(endpoint, false))+ assertSignedPdfEditable(+ access ??+ (await inspectForPasswordTool(+ file,+ String(form.get("password") ?? ""),+ )),+ endpoint,+ );if (settingProtection) {if (access?.encrypted && !hasPdfPermissionOverride(access))throw new Error(diff --git a/frontend/src/editor/core/tests/stubbed/settings-pdf-permissions.spec.ts b/frontend/src/editor/core/tests/stubbed/settings-pdf-permissions.spec.tsindex 52d9cc01f3..eb1c2940db 100644--- a/frontend/src/editor/core/tests/stubbed/settings-pdf-permissions.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/settings-pdf-permissions.spec.ts@@ -1,7 +1,18 @@+import type { Page } from "@playwright/test";import { test, expect } from "@editor/tests/helpers/stub-test-base";test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });+function toggleRow(page: Page, label: string) {+ return page+ .locator(".settings-card")+ .filter({+ has: page.getByRole("button", { name: "PDF permissions", exact: true }),+ })+ .locator(".settings-toggle")+ .filter({ has: page.getByText(label, { exact: true }) });+}+for (const initial of [undefined, true, false]) {test(`an administrator can change owner enforcement from ${initial ?? "the default"} and reload the pending value`, async ({page,@@ -29,17 +40,15 @@ for (const initial of [undefined, true, false]) {return route.fulfill({ json: {} });});await page.goto("/settings/adminSecurity#pdfPermissions");- const card = page.locator(".settings-card").filter({- has: page.getByRole("button", { name: "PDF permissions", exact: true }),- });- await expect(card.getByRole("switch")).toBeChecked({+ const row = toggleRow(page, "Honor PDF permissions");+ await expect(row.getByRole("switch")).toBeChecked({checked: expectedInitial,});await page.screenshot({path: test.info().outputPath("owner-policy-setting-default.png"),});- await card.locator(".mantine-Switch-track").click();- await expect(card.getByRole("switch")).toBeChecked({ checked: target });+ await row.locator(".mantine-Switch-track").click();+ await expect(row.getByRole("switch")).toBeChecked({ checked: target });await page.getByRole("button", { name: "Save Changes", exact: true }).click();@@ -48,6 +57,28 @@ for (const initial of [undefined, true, false]) {.toContainEqual({ settings: { "security.honorOwnerPasswords": target } });await expect(page.getByRole("dialog")).toBeVisible();await page.reload();- await expect(card.getByRole("switch")).toBeChecked({ checked: target });+ await expect(row.getByRole("switch")).toBeChecked({ checked: target });});}++test("an administrator can block changes to signed PDFs", async ({ page }) => {+ await page.route("**/api/v1/admin/settings/section/security", (route) =>+ route.fulfill({ json: { enableLogin: true } }),+ );+ const saved: unknown[] = [];+ await page.route("**/api/v1/admin/settings", (route) => {+ if (route.request().method() === "PUT") {+ saved.push(route.request().postDataJSON());+ }+ return route.fulfill({ json: {} });+ });+ await page.goto("/settings/adminSecurity#pdfPermissions");+ const row = toggleRow(page, "Block changes to signed PDFs");+ await expect(row.getByRole("switch")).toBeChecked({ checked: false });+ await row.locator(".mantine-Switch-track").click();+ await expect(row.getByRole("switch")).toBeChecked({ checked: true });+ await page.getByRole("button", { name: "Save Changes", exact: true }).click();+ await expect+ .poll(() => saved)+ .toContainEqual({ settings: { "security.blockSignedPdfEdits": true } });+});diff --git a/frontend/src/editor/core/tests/stubbed/signed-pdf-edit-policy.spec.ts b/frontend/src/editor/core/tests/stubbed/signed-pdf-edit-policy.spec.tsnew file mode 100644index 0000000000..b284a26010--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/signed-pdf-edit-policy.spec.ts@@ -0,0 +1,152 @@+import type { Page } from "@playwright/test";+import path from "node:path";+import { test, expect } from "@editor/tests/helpers/stub-test-base";+import { uploadFiles } from "@editor/tests/helpers/ui-helpers";++const SIGNED = path.join(+ import.meta.dirname,+ "../test-fixtures/signed-sample.pdf",+);++async function openSigned(page: Page, route: string, block: boolean) {+ await page.route("**/api/v1/config/app-config", (r) =>+ r.fulfill({+ json: {+ enableLogin: false,+ isAdmin: false,+ languages: ["en-US"],+ defaultLocale: "en-US",+ blockSignedPdfEdits: block,+ },+ }),+ );+ await page.route("**/api/v1/form/fields-with-coordinates", (r) =>+ r.fulfill({ json: [] }),+ );+ await page.goto(route, { waitUntil: "domcontentloaded" });+ await uploadFiles(page, SIGNED);+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({+ timeout: 30_000,+ });+}++const unavailable = (page: Page) =>+ page.getByRole("button", {+ name: "Why signed-sample.pdf is unavailable",+ exact: true,+ });++test("Annotate explains why a signed PDF is left out while changes are blocked", async ({+ page,+}) => {+ await openSigned(page, "/annotate", true);+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ await expect(+ page.getByRole("button", { name: "Highlight", exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Remove Password", exact: true }),+ ).toHaveCount(0);+ await unavailable(page).hover();+ await expect(page.getByRole("tooltip")).toContainText("digitally signed");+});++test("Annotate edits a signed PDF while changes are allowed", async ({+ page,+}) => {+ await openSigned(page, "/annotate", false);+ await expect(+ page.getByRole("button", { name: "Highlight", exact: true }),+ ).toBeVisible({ timeout: 30_000 });+ await expect(unavailable(page)).toHaveCount(0);+});++test("the form editor locks a signed PDF while changes are blocked", async ({+ page,+}) => {+ await openSigned(page, "/form-fill", true);+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ await expect(+ page+ .locator(".mantine-SegmentedControl-label")+ .filter({ hasText: "Create" }),+ ).toHaveCount(0);+});++test("the form editor edits a signed PDF while changes are allowed", async ({+ page,+}) => {+ await openSigned(page, "/form-fill", false);+ await expect(+ page+ .locator(".mantine-SegmentedControl-label")+ .filter({ hasText: "Create" }),+ ).toBeVisible({ timeout: 30_000 });+ await expect(unavailable(page)).toHaveCount(0);+});++for (const block of [true, false]) {+ test(`the viewer ${block ? "shows" : "hides"} the signed lock chip while changes are ${block ? "blocked" : "allowed"}`, async ({+ page,+ }) => {+ await openSigned(page, "/editor", block);+ await expect(page.getByTestId("annotations-toggle")).toBeVisible({+ timeout: 30_000,+ });+ await expect(page.getByText("Signed: edits blocked")).toHaveCount(+ block ? 1 : 0,+ );+ });++ test(`Compress ${block ? "leaves out" : "accepts"} a signed PDF while changes are ${block ? "blocked" : "allowed"}`, async ({+ page,+ }) => {+ await openSigned(page, "/compress", block);+ if (block) {+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ await unavailable(page).hover();+ await expect(page.getByRole("tooltip")).toContainText("digitally signed");+ return;+ }+ await expect(page.locator('[data-tour="run-button"]')).toBeEnabled({+ timeout: 30_000,+ });+ await expect(unavailable(page)).toHaveCount(0);+ });++ test(`Add Text ${block ? "leaves out" : "accepts"} a signed PDF while changes are ${block ? "blocked" : "allowed"}`, async ({+ page,+ }) => {+ await openSigned(page, "/add-text", block);+ const textInput = page.getByPlaceholder("Enter the text you want to add");+ if (block) {+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ await expect(textInput).toHaveCount(0);+ return;+ }+ await expect(textInput).toBeVisible({ timeout: 30_000 });+ await expect(unavailable(page)).toHaveCount(0);+ });++ test(`Adjust Contrast ${block ? "leaves out" : "accepts"} a signed PDF nobody opened in the viewer while changes are ${block ? "blocked" : "allowed"}`, async ({+ page,+ }) => {+ await openSigned(page, "/adjust-contrast", block);+ if (block) {+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ return;+ }+ await expect(unavailable(page)).toHaveCount(0);+ });++ test(`Add Password ${block ? "leaves out" : "accepts"} a signed PDF while changes are ${block ? "blocked" : "allowed"}`, async ({+ page,+ }) => {+ await openSigned(page, "/add-password", block);+ if (block) {+ await expect(unavailable(page)).toBeVisible({ timeout: 30_000 });+ return;+ }+ await expect(unavailable(page)).toHaveCount(0);+ });+}diff --git a/frontend/src/editor/core/tests/test-fixtures/README.md b/frontend/src/editor/core/tests/test-fixtures/README.mdindex 634a02f45e..010901f5a7 100644--- a/frontend/src/editor/core/tests/test-fixtures/README.md+++ b/frontend/src/editor/core/tests/test-fixtures/README.md@@ -11,6 +11,17 @@ qpdf --encrypt annotation-test annotation-test 256 -- annotations_out_of_order.pqpdf --encrypt annotation-test annotation-test 256 -- link-annotations-sample.pdf encrypted-links.pdf```+## Signature probe fixtures++`signature-*.pdf` exercise the local signature probe (`utils/pdfiumSignatures.ts`). They were signed by Stirling-PDF's `cert-sign` endpoint with `certs/valid-test.p12` (password `testpass`, signer `Test Signer`):++- `signature-one.pdf`: one signature covering the whole file.+- `signature-two.pdf`: `signature-one.pdf` countersigned, so the first signature no longer reaches the end of the file.+- `signature-changed-after.pdf`: `signature-one.pdf` with an incremental metadata update appended after signing.+- `signature-rewritten.pdf`: `signature-one.pdf` rewritten by `update-metadata`, so its byte range no longer fits the file.+- `signature-timestamp.pdf`: an RFC 3161 document timestamp from `timestamp-pdf` (DigiCert TSA).+- `signature-empty-field.pdf`: an empty signature field with no signature value.+## Required Test FilesTo run the full test suite, please add the following test files to this directory:diff --git a/frontend/src/editor/core/tests/test-fixtures/signature-changed-after.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-changed-after.pdfnew file mode 100644index 0000000000..988c59b16d--- /dev/null+++ b/frontend/src/editor/core/tests/test-fixtures/signature-changed-after.pdf@@ -0,0 +1,204 @@+%PDF-1.3+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+4 0 obj+<<+/PageMode /UseNone /Pages 6 0 R /Type /Catalog+>>+endobj+5 0 obj+<<+/Author (anonymous) /CreationDate (D:20261110111401+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20261110111401+00'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Signature probe fixture) /Trapped /False+>>+endobj+6 0 obj+<<+/Count 1 /Kids [ 3 0 R ] /Type /Pages+>>+endobj+7 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 115+>>+stream+GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<;D:$c:^G0Ccj7ojcV#f</P9"k.*>=X<Ck<7!:_l\6F%:lZp=I%\,\>5(]X~>endstream+endobj+xref+0 8+0000000000 65535 f+0000000061 00000 n+0000000092 00000 n+0000000199 00000 n+0000000402 00000 n+0000000470 00000 n+0000000746 00000 n+0000000805 00000 n+trailer+<<+/ID+[<ba05d6207b76e2bd3fcb557b71e8b76f><ba05d6207b76e2bd3fcb557b71e8b76f>]+% ReportLab generated PDF document -- digest (opensource)++/Info 5 0 R+/Root 4 0 R+/Size 8+>>+startxref+1010+%%EOF++5 0 obj+<<+/Author (anonymous)+/CreationDate (D:20261110111401+00'00')+/Creator (anonymous)+/Keywords ()+/ModDate (D:20261110111401+00'00')+/Producer (Stirling-PDF v3.3.0)+/Subject (unspecified)+/Title (Signature probe fixture)+/Trapped /False+>>+endobj+8 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature1)+/V 9 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 10 0 R+>>+endobj+9 0 obj+<<+/Type /Sig+/Filter /Adobe.PPKLite+/SubFilter /adbe.pkcs7.detached+/Reason (Approved)+/M (D:20261110111401+00'00')+/Contents <308006092A864886F70D010702A0803080020101310D300B0609608648016503040201300B06092A864886F70D010701A0803082035930820241A00302010202145D6EC4A703506FC37A82ED3838CD6C40247302A7300D06092A864886F70D01010C0500303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E65723020170D3235303130313030303030305A180F32313235303130313030303030305A303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657230820122300D06092A864886F70D01010105000382010F003082010A0282010100BBFB2719030B25ED07591CDB88A67C664D13A00C11BF9E9F297B5F7889321904C4F962BBBB12A169049A6130E75F6DB695621BA60D09A567082A4C09626E47408E254A25590A6E8DC7747C988CDA77EAD0BAA111FA7B1DFD61BF893E8C5E8A21B30FB6FD46604FF40AB9CE4F5B13E7903EE457277837D9B0820368C2EBBC25CBCB87F4DD6715D84BA63FC68016433C50F3388BC1965A94FF3242372A09363593CA3051334D764C9BE043E18F4A54F6F310DD5F7470E197BE42F3AB17E057A126EFCA51178BF5B76D964C25CFA4EF778CFB43F5F6D4A91F6E957C5C2CF452C0A57F7CC74C56B7ACB4A5C6584AD19C547D5178BEF0DCE0039FAC7F59AA1A2AC1C10203010001A3533051301F0603551D230418301680142271595BA068E88537F2FAD13C0A3072BA9DBF35300F0603551D130101FF040530030101FF301D0603551D0E041604142271595BA068E88537F2FAD13C0A3072BA9DBF35300D06092A864886F70D01010C05000382010100AE465AE45BAB23922FEFE2C91A5418473C1A9DBD198DD7F0C08170F596FC7462CD9A62534D6A8B78506010E3CAB4335CB16E7E7D93B3B6FFFED24FF6F66026C0B9FB64BC42F5A4AB8730C902B677EAA16B0FFD36F13B67DDB488292BA45F1AF04E915A5EE0E50084AF7F33BE063FBE54F556D98B8DEE2E222208BA571809BF1DB07A409D2D394BABE8BB72E94FA5279701C3298BCC607C9DF3C0910788FFFD2F1F66F2C10C43541C13D9D6574E238049CB3C7B2BF53C9D80FD302B8B0D540BC0E5E12F5C52E013D5BE97D71F6954739F763FC29D175CFFA3B978FBEFD2B73E69298F669CAA2E43295CC5D883E1A74E93EA0FBB40745B5549529B50F4C8BEDC58000031820215308202110201013053303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657202145D6EC4A703506FC37A82ED3838CD6C40247302A7300B0609608648016503040201A08196301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3236313131303131313430315A302B06092A864886F70D010934311E301C300B0609608648016503040201A10D06092A864886F70D01010B0500302F06092A864886F70D0109043122042087C62DD1FA7B03E76E3730B45B44A368BB153CECEA4B777ADABDA558D0AE61BA300D06092A864886F70D01010B0500048201007DEE06968A7DDA6AD933A8EB319F59200B335E30CDA30F58916B40E806FAC0FCE59793466E769DED0C78770197C7441205950B82407BBE20D789B07B3F006E0F327CA6AAE03B1ED2DD55F3C49C671AF2B7F3B6060B1857E754782FDC741C279515FCA89E368A568B9439011AEC7CE3747B6BE3E620AB88A770087D815D17CAA60F8445116FE13BB14401687D5AA5A9D858603CF959ADD6CCDEB49C7DB586AD0C3915D772AD5920447AE371C1B8C132EDEA6A5F0D040E623E321CE51DEE0101CA0E5A678BA9AA1DE0C28F67C3F601E95855E24FD37B2C225B7ECFB46B5EA746F99EC80C33A39BF5C144CAF38A6B750693A5D5E91E93D94ECDA71E8457402C00D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000>+/ByteRange [0 1908 20854 885]+>>+endobj+3 0 obj+<<+/Contents 7 0 R+/MediaBox [0 0 595.2756 841.8898]+/Parent 6 0 R+/Resources <<+/Font 1 0 R+/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]+>>+/Rotate 0+/Trans <<+>>+/Type /Page+/Annots [8 0 R]+>>+endobj+10 0 obj+<<+/N 11 0 R+>>+endobj+11 0 obj+<<+/Length 0+/Type /XObject+/Subtype /Form+/BBox [0.0 0.0 0.0 0.0]+>>+stream++endstream+endobj+4 0 obj+<<+/PageMode /UseNone+/Pages 6 0 R+/Type /Catalog+/AcroForm <<+/Fields [8 0 R]+/SigFlags 3+>>+>>+endobj+xref+0 1+0000000000 65535 f+3 3+0000020913 00000 n+0000021262 00000 n+0000001383 00000 n+8 4+0000001637 00000 n+0000001773 00000 n+0000021124 00000 n+0000021156 00000 n+trailer+<<+/ID [<BA05D6207B76E2BD3FCB557B71E8B76F> <DDBCF3CD22977ED0CD63354BDF94B173D1C5A047083DE553A31F16F03D04BAE9>]+/Info 5 0 R+/Root 4 0 R+/Size 12+/Prev 1010+>>+startxref+21374+%%EOF+5 0 obj+<<+/Author (anonymous)+/CreationDate (D\07220261110111401\05300\04700\047)+/Creator (anonymous)+/Keywords ()+/ModDate (D\07220261110111401\05300\04700\047)+/Producer (Stirling\055PDF v3\0563\0560)+/Subject (unspecified)+/Title (Edited after signing)+/Trapped /False+>>+endobj+12 0 obj<<+/Type /XRef+/Size 13+/Root 4 0 R+/Filter /FlateDecode+/Index [ 5 1 ]+/W [ 1 4 1 ]+/Info 5 0 R+/Prev 21374+/ID [ <ba05d6207b76e2bd3fcb557b71e8b76f> <ddbcf3cd22977ed0cd63354bdf94b173d1c5a047083de553a31f16f03d04bae9> ]+/Length 14+>>+stream+x�cd`y� �A+endstream+endobj+startxref+22023+%%EOFdiff --git a/frontend/src/editor/core/tests/test-fixtures/signature-empty-field.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-empty-field.pdfnew file mode 100644index 0000000000..22b0e99d9eBinary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/signature-empty-field.pdf differdiff --git a/frontend/src/editor/core/tests/test-fixtures/signature-one.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-one.pdfnew file mode 100644index 0000000000..df62bcd25e--- /dev/null+++ b/frontend/src/editor/core/tests/test-fixtures/signature-one.pdf@@ -0,0 +1,172 @@+%PDF-1.3+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+4 0 obj+<<+/PageMode /UseNone /Pages 6 0 R /Type /Catalog+>>+endobj+5 0 obj+<<+/Author (anonymous) /CreationDate (D:20261110111401+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20261110111401+00'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Signature probe fixture) /Trapped /False+>>+endobj+6 0 obj+<<+/Count 1 /Kids [ 3 0 R ] /Type /Pages+>>+endobj+7 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 115+>>+stream+GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<;D:$c:^G0Ccj7ojcV#f</P9"k.*>=X<Ck<7!:_l\6F%:lZp=I%\,\>5(]X~>endstream+endobj+xref+0 8+0000000000 65535 f+0000000061 00000 n+0000000092 00000 n+0000000199 00000 n+0000000402 00000 n+0000000470 00000 n+0000000746 00000 n+0000000805 00000 n+trailer+<<+/ID+[<ba05d6207b76e2bd3fcb557b71e8b76f><ba05d6207b76e2bd3fcb557b71e8b76f>]+% ReportLab generated PDF document -- digest (opensource)++/Info 5 0 R+/Root 4 0 R+/Size 8+>>+startxref+1010+%%EOF++5 0 obj+<<+/Author (anonymous)+/CreationDate (D:20261110111401+00'00')+/Creator (anonymous)+/Keywords ()+/ModDate (D:20261110111401+00'00')+/Producer (Stirling-PDF v3.3.0)+/Subject (unspecified)+/Title (Signature probe fixture)+/Trapped /False+>>+endobj+8 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature1)+/V 9 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 10 0 R+>>+endobj+9 0 obj+<<+/Type /Sig+/Filter /Adobe.PPKLite+/SubFilter /adbe.pkcs7.detached+/Reason (Approved)+/M (D:20261110111401+00'00')+/Contents <308006092A864886F70D010702A0803080020101310D300B0609608648016503040201300B06092A864886F70D010701A0803082035930820241A00302010202145D6EC4A703506FC37A82ED3838CD6C40247302A7300D06092A864886F70D01010C0500303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E65723020170D3235303130313030303030305A180F32313235303130313030303030305A303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657230820122300D06092A864886F70D01010105000382010F003082010A0282010100BBFB2719030B25ED07591CDB88A67C664D13A00C11BF9E9F297B5F7889321904C4F962BBBB12A169049A6130E75F6DB695621BA60D09A567082A4C09626E47408E254A25590A6E8DC7747C988CDA77EAD0BAA111FA7B1DFD61BF893E8C5E8A21B30FB6FD46604FF40AB9CE4F5B13E7903EE457277837D9B0820368C2EBBC25CBCB87F4DD6715D84BA63FC68016433C50F3388BC1965A94FF3242372A09363593CA3051334D764C9BE043E18F4A54F6F310DD5F7470E197BE42F3AB17E057A126EFCA51178BF5B76D964C25CFA4EF778CFB43F5F6D4A91F6E957C5C2CF452C0A57F7CC74C56B7ACB4A5C6584AD19C547D5178BEF0DCE0039FAC7F59AA1A2AC1C10203010001A3533051301F0603551D230418301680142271595BA068E88537F2FAD13C0A3072BA9DBF35300F0603551D130101FF040530030101FF301D0603551D0E041604142271595BA068E88537F2FAD13C0A3072BA9DBF35300D06092A864886F70D01010C05000382010100AE465AE45BAB23922FEFE2C91A5418473C1A9DBD198DD7F0C08170F596FC7462CD9A62534D6A8B78506010E3CAB4335CB16E7E7D93B3B6FFFED24FF6F66026C0B9FB64BC42F5A4AB8730C902B677EAA16B0FFD36F13B67DDB488292BA45F1AF04E915A5EE0E50084AF7F33BE063FBE54F556D98B8DEE2E222208BA571809BF1DB07A409D2D394BABE8BB72E94FA5279701C3298BCC607C9DF3C0910788FFFD2F1F66F2C10C43541C13D9D6574E238049CB3C7B2BF53C9D80FD302B8B0D540BC0E5E12F5C52E013D5BE97D71F6954739F763FC29D175CFFA3B978FBEFD2B73E69298F669CAA2E43295CC5D883E1A74E93EA0FBB40745B5549529B50F4C8BEDC58000031820215308202110201013053303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657202145D6EC4A703506FC37A82ED3838CD6C40247302A7300B0609608648016503040201A08196301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3236313131303131313430315A302B06092A864886F70D010934311E301C300B0609608648016503040201A10D06092A864886F70D01010B0500302F06092A864886F70D0109043122042087C62DD1FA7B03E76E3730B45B44A368BB153CECEA4B777ADABDA558D0AE61BA300D06092A864886F70D01010B0500048201007DEE06968A7DDA6AD933A8EB319F59200B335E30CDA30F58916B40E806FAC0FCE59793466E769DED0C78770197C7441205950B82407BBE20D789B07B3F006E0F327CA6AAE03B1ED2DD55F3C49C671AF2B7F3B6060B1857E754782FDC741C279515FCA89E368A568B9439011AEC7CE3747B6BE3E620AB88A770087D815D17CAA60F8445116FE13BB14401687D5AA5A9D858603CF959ADD6CCDEB49C7DB586AD0C3915D772AD5920447AE371C1B8C132EDEA6A5F0D040E623E321CE51DEE0101CA0E5A678BA9AA1DE0C28F67C3F601E95855E24FD37B2C225B7ECFB46B5EA746F99EC80C33A39BF5C144CAF38A6B750693A5D5E91E93D94ECDA71E8457402C00D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000>+/ByteRange [0 1908 20854 885]+>>+endobj+3 0 obj+<<+/Contents 7 0 R+/MediaBox [0 0 595.2756 841.8898]+/Parent 6 0 R+/Resources <<+/Font 1 0 R+/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]+>>+/Rotate 0+/Trans <<+>>+/Type /Page+/Annots [8 0 R]+>>+endobj+10 0 obj+<<+/N 11 0 R+>>+endobj+11 0 obj+<<+/Length 0+/Type /XObject+/Subtype /Form+/BBox [0.0 0.0 0.0 0.0]+>>+stream++endstream+endobj+4 0 obj+<<+/PageMode /UseNone+/Pages 6 0 R+/Type /Catalog+/AcroForm <<+/Fields [8 0 R]+/SigFlags 3+>>+>>+endobj+xref+0 1+0000000000 65535 f+3 3+0000020913 00000 n+0000021262 00000 n+0000001383 00000 n+8 4+0000001637 00000 n+0000001773 00000 n+0000021124 00000 n+0000021156 00000 n+trailer+<<+/ID [<BA05D6207B76E2BD3FCB557B71E8B76F> <DDBCF3CD22977ED0CD63354BDF94B173D1C5A047083DE553A31F16F03D04BAE9>]+/Info 5 0 R+/Root 4 0 R+/Size 12+/Prev 1010+>>+startxref+21374+%%EOFdiff --git a/frontend/src/editor/core/tests/test-fixtures/signature-rewritten.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-rewritten.pdfnew file mode 100644index 0000000000..2517a98261Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/signature-rewritten.pdf differdiff --git a/frontend/src/editor/core/tests/test-fixtures/signature-timestamp.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-timestamp.pdfnew file mode 100644index 0000000000..9e5ef6fede--- /dev/null+++ b/frontend/src/editor/core/tests/test-fixtures/signature-timestamp.pdf@@ -0,0 +1,171 @@+%PDF-1.3+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+4 0 obj+<<+/PageMode /UseNone /Pages 6 0 R /Type /Catalog+>>+endobj+5 0 obj+<<+/Author (anonymous) /CreationDate (D:20261110111401+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20261110111401+00'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Signature probe fixture) /Trapped /False+>>+endobj+6 0 obj+<<+/Count 1 /Kids [ 3 0 R ] /Type /Pages+>>+endobj+7 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 115+>>+stream+GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<;D:$c:^G0Ccj7ojcV#f</P9"k.*>=X<Ck<7!:_l\6F%:lZp=I%\,\>5(]X~>endstream+endobj+xref+0 8+0000000000 65535 f+0000000061 00000 n+0000000092 00000 n+0000000199 00000 n+0000000402 00000 n+0000000470 00000 n+0000000746 00000 n+0000000805 00000 n+trailer+<<+/ID+[<ba05d6207b76e2bd3fcb557b71e8b76f><ba05d6207b76e2bd3fcb557b71e8b76f>]+% ReportLab generated PDF document -- digest (opensource)++/Info 5 0 R+/Root 4 0 R+/Size 8+>>+startxref+1010+%%EOF++5 0 obj+<<+/Author (anonymous)+/CreationDate (D:20261110111401+00'00')+/Creator (anonymous)+/Keywords ()+/ModDate (D:20261110111401+00'00')+/Producer (Stirling-PDF v3.3.0)+/Subject (unspecified)+/Title (Signature probe fixture)+/Trapped /False+>>+endobj+8 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature1)+/V 9 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 10 0 R+>>+endobj+9 0 obj+<<+/Type /DocTimeStamp+/Filter /Adobe.PPKLite+/SubFilter /ETSI.RFC3161+/M (D:20261110111401+00'00')+/Contents <3082176A06092A864886F70D010702A082175B30821757020103310F300D06096086480165030402010500308182060B2A864886F70D0109100104A0730471306F02010106096086480186FD6C07013031300D060960864801650304020105000420206E353241D5DC3FE4EE4CA0247A1C77AEA29743C58793530800C87B7E6FBABD021100A45F5278CC07A435B040BF10DE42495C180F32303236313131303131313430315A02084B4EC94763BF362BA082133A308206ED308204D5A0030201020210084FDC334F7E454EDBC30F8FF9921835300D06092A864886F70D01010B05003069310B300906035504061302555331173015060355040A130E44696769436572742C20496E632E3141303F06035504031338446967694365727420547275737465642047342054696D655374616D70696E67205253413430393620534841323536203230323520434131301E170D3236303830353030303030305A170D3337313130343233353935395A3063310B300906035504061302555331173015060355040A130E44696769436572742C20496E632E313B30390603550403133244696769436572742053484132353620525341343039362054696D657374616D7020526573706F6E6465722032303236203130820222300D06092A864886F70D01010105000382020F003082020A0282020100B67BA6F2C9FECD4AF8D49B4C65B3FD38C630F87C090E91B9C6422EFE5A9C7CD626317F35626B148872DB87DCA4A5E58118A4CB85806B00DF53760FD01331B7D9770E6E68086E59EBD02A10DD648078367A9C7E97E95905C98909C37401251130BE6E1484BCD2C66C0F03B7052914C438CB261048FAA8993F76A2C400BFA8418B8EC04D94BA25F5567BA5F1845E23259DE2480B9FD82AE8B35733452996447A8CBFD01F199BE9F3281812586E769423B5C3E9C283A5E90AD9254C95DE220DBCDE1C3B4E69AC65747E48C6E36EB10EBD9DDF3F6571220791DBC63DD194AD77717D56E039455CA76FFC212133C0A3D6FBE59AF84DAE8C8F75119B6E90658327FC59DBB937A072845C14467D14EA8CE53E8C4DDB6BFE7EF89484FFBA0D1E78ECE667A413160DF7A2D5FE6C546C22896FCA41358E2BDEE0FB8449A4FCCF355E1560C0303B68CCD80B72D9060F5663904C99B49ACB979C9AD26E5DA07FD2729699099565EA9354382C9B31CFE4C42E84026489636E0BD3260A0F536475DB276FF22D54A8BFDA75E940D32ED4F4F9A6B5BCDEF57C77AED6A30B94B341DD6381FC00C2C6BDD2FF587123DD99EA32A01040FF6EDC08BDB7EE5E434D860F0CB43838DDCE2D31969EF45BEA30EB7FF4FBE603117D4CD22C20507C1BAC9BDFA64964650BF0DFE92FDEF50F22D770AE873393D89C7E57F9E56D73384280709540217A5C30253D0203010001A382019530820191300C0603551D130101FF04023000301D0603551D0E0416041414C9638A302ED44AFB6E94F3E6E3407EF5ECCDE2301F0603551D23041830168014EF6F534AE9E4067C7ACAE29056F62FD449ECCB4E300E0603551D0F0101FF04040302078030160603551D250101FF040C300A06082B0601050507030830819506082B06010505070101048188308185302406082B060105050730018618687474703A2F2F6F6373702E64696769636572742E636F6D305D06082B060105050730028651687474703A2F2F636163657274732E64696769636572742E636F6D2F446967694365727454727573746564473454696D655374616D70696E6752534134303936534841323536323032354341312E637274305F0603551D1F045830563054A052A050864E687474703A2F2F63726C332E64696769636572742E636F6D2F446967694365727454727573746564473454696D655374616D70696E6752534134303936534841323536323032354341312E63726C30200603551D20041930173008060667810C010402300B06096086480186FD6C0701300D06092A864886F70D01010B050003820201008DC53A611E9D520ADF99AC09807E7D2840B16BD262F2C122DA0D740810DA322AAC6B15B25B9730953FFA645E6C1739DACEA56CA02F3953D76A2CE62A430B2DF94410A0D9431E02912DADF1A1CF8E45E16B7858674D7486D15ADDD84D8266A51F9BEE5AF877B5309FE1FAD34BB80FB4673867FC5A3E1436001D6647C7847BF59B1F44561EF54897A570437FA0E4528D7CDD8DFC358991FD77C361FED867EA11F6DDDF95B0F02BE86018CB3480D369D70F59D82C8EC88E68AFFB12C28980B8D4348560BDC68538B2D0FC696B03ED191C9A0551B3ABE5224DF33CA43ECA572179690C963F82A15465144E79A6FD19582685B74E25C0FFEB7461C4F6A115419B72444E36A31EE83600BFAFE6386D2959DDDC3D2B6C75C4BB6EE8F90F29E2C1163CCA8A0C1FAA6DC79BE93FFA59CC13C17990F653822CB61CB107925A6BCAAB3A4079CF5EB44D788CE400CCB296744DF0FD309A2AD2D16914FB2C29116159E10360FBDC52E37B53B96F71D1E5E1ECD0DCD4FFEC57ECD6C475CA1FCB45B759DC1DD573AAB65A60FC9830B4A7D933976A3BDE256D4BDE3A224123EC5911B191B0C35B5E63111144E0BBE39C6BB63BDCC3D672C948C765619122925E30DB0FAAE0837F47E4C87B41F89E0088D66A090936DEBC61F8A6E9C8C4CD54A22D27997DD92BE5DB453D35BA8C04E558975879E0D1182C9AB5FF11D614A3CD2BDD37CC9640F4FD83308206B43082049CA00302010202100DC7AC5705FF21992E4043220C3A4986300D06092A864886F70D01010B05003062310B300906035504061302555331153013060355040A130C446967694365727420496E6331193017060355040B13107777772E64696769636572742E636F6D3121301F060355040313184469676943657274205472757374656420526F6F74204734301E170D3235303530373030303030305A170D3338303131343233353935395A3069310B300906035504061302555331173015060355040A130E44696769436572742C20496E632E3141303F06035504031338446967694365727420547275737465642047342054696D655374616D70696E6720525341343039362053484132353620323032352043413130820222300D06092A864886F70D01010105000382020F003082020A0282020100B47831D30A984172BE3C46C01CAC75DBA3466874B451179D4DAD8D0D94B59996832C54ED436A118F3517326C42AAF91BB03A73E1A1FEA9BC5E2E1A3C23A8D8DF12F522EB0BA29B96DAA7ED25825A0CDB35F891FB67E41D48A58CD3AA9C8543FE01B74980C401DE1D8367431A979918A7BEE360C5505D2647FBED2DAE3E80A3EC61FC04BBB1046E40BDFB4176C384092D5493106F32011D8241620CD622393C783AD88570C4A4A93B45DA17D0CF7CD04A4BB65ACDC87C345E6FA7B79A676095371A6ABA6CD308D48EC66F920164AE22BDB542899BFB3CD058A87129355582D9943C05B7E715141511260EB33148D96BFCDB09C945F376D15452DE1A4B808478863CCBD21A6860693CD5CA1627E29D3EF32F681D16904FF6A87C49D2E712EB7F19C6A535E250E7922EC2728282CFA7AE9B9035F566501E4A9425F7640E31E471CA4BEAEA06F296C5D0B240410671B2DED5BF00C38C0992153526B3EC15FC56D606A8BB7D32678EADE18F45DB41C77C8638FFABC77ACA583109948A8B5EF2569D8D2FE7274FA4E8CBEACDFA733C33B2E72EA0AB3B624FDE85BFFF5B1FB990CA88311BD4043C7ACF57AFFBBA6C34E76024CA22C0EAD41B665D4A841B536ACC9292E243A6C64629D96C8E0E2EEF41308166D54525F559DE3ECE8169A7845AF8C94A3366DAA03EB1D154784634A958CF28E5AE83F1BA5F9B808B29CCEC1BB66B2063530203010001A382015D3082015930120603551D130101FF040830060101FF020100301D0603551D0E04160414EF6F534AE9E4067C7ACAE29056F62FD449ECCB4E301F0603551D23041830168014ECD7E382D2715D644CDF2E673FE7BA98AE1C0F4F300E0603551D0F0101FF04040302018630130603551D25040C300A06082B06010505070308307706082B06010505070101046B3069302406082B060105050730018618687474703A2F2F6F6373702E64696769636572742E636F6D304106082B060105050730028635687474703A2F2F636163657274732E64696769636572742E636F6D2F446967694365727454727573746564526F6F7447342E63727430430603551D1F043C303A3038A036A0348632687474703A2F2F63726C332E64696769636572742E636F6D2F446967694365727454727573746564526F6F7447342E63726C30200603551D20041930173008060667810C010402300B06096086480186FD6C0701300D06092A864886F70D01010B0500038202010017CEFB16801CFE073D11767130BDBE0BC8B534A67FCDD087C5881A307F4FC39B5C0673F0E8EE854C6369A15D95E30CD2506BC8F4D0336A8424F7B7EB3C1B488FE64BCDDA7EC9776138FE21085013B8D4FE45E38F2B498279F486FAD5EA1A9619DDEB2C052DEAF272F653033E34CBC4B8177FDAF99D6310C2BF0CC9BF6B115282847C9FA7379EE641F417C1C004182BD1476A8AB67B6E8C1EF558F6008303F258B2AEE919DA203FC1D1B6B61F72D48B00D1017C7535EABDC9D39A97DE421DF9939CCE08F99236AD541F8D7400D564A38DFE09D9AEE32F358636A357F83174490CC7534A538B8741C29F67102F0402AA315BAAB5EEBD33D27A038ECEBE045A3ECFB6CA481C195D344D8AF62EBDEDCBDA888A36A7AD44776A7CC4C25BF36628B27D33E32DB9C546C8EC620DFD3A557C722A43A2AEFEA8D363A85CDE1B1732B4BE534CB2F865AA0176A6E13A16776510D4A613EF49198C4E18B4BF0F6F3834735BA0319C9965DFC17472E246EEE101613A6D3126E17611900E9397829214B164E377AC6947AA1A41FFC325B837B3A2822CF02567AE91CC883DB02F8D269B9DFEFE3EED15AC58288A8BD10E2CB1DF311D99C89FFEC610B1F721DBC6D9794CF6AED63FF53080E930FC742DC9137AD892B84B50BCBB0DCF741BA7BC065AA6C888E5829DBE56AB12F7FC100FBC85CA5233D2C7266CABC5A16DA336B6CCD690F64FB9B75C3082058D30820475A00302010202100E9B188EF9D02DE7EFDB50E20840185A300D06092A864886F70D01010C05003065310B300906035504061302555331153013060355040A130C446967694365727420496E6331193017060355040B13107777772E64696769636572742E636F6D312430220603550403131B4469676943657274204173737572656420494420526F6F74204341301E170D3232303830313030303030305A170D3331313130393233353935395A3062310B300906035504061302555331153013060355040A130C446967694365727420496E6331193017060355040B13107777772E64696769636572742E636F6D3121301F060355040313184469676943657274205472757374656420526F6F7420473430820222300D06092A864886F70D01010105000382020F003082020A0282020100BFE6907368DEBBE45D4A3C3022306933ECC2A7252EC9213DF28AD859C2E129A73D58AB769ACDAE7B1B840DC4301FF31BA43816EB56C6976D1DABB279F2CA11D2E45FD6053C520F521FC69E15A57EBE9FA95716595572AF689370C2B2BA75996A733294D11044102EDF82F30784E6743B6D71E22D0C1BEE20D5C9201D63292DCEEC5E4EC893F821619B34EB05C65EEC5B1ABCEBC9CFCDAC34405FB17A66EE77C848A86657579F54588E0C2BB74FA730D956EECA7B5DE3ADC94F5EE535E731CBDA935EDC8E8F80DAB69198409079C378C7B6B1C4B56A183803108DD8D437A42E057D88F5823E109170AB55824132D7DB04732A6E91017C214CD4BCAE1B03755D7866D93A31449A3340BF08D75A49A4C2E6A9A067DDA427BCA14F39B5115817F7245C468F64F7C169887698763D595D4276878997697A48F0E0A2121B669A74CADE4B1EE70E63AEE6D4EF92923A9E3DDC00E4452589B69A44192B7EC094B4D2616DEB33D9C5DF4B0400CC7D1C95C38FF721B2B211B7BB7FF2D58C702C4160AAB1631844951A76627EF680B0FBE864A633D18907E1BDB7E643A418B8A67701E10F940C211DB2542925896CE50E52514774BE26ACB64175DE7AAC5F8D3FC9BCD34111125BE51050EB31C5CA72162209DF7C4C753F63EC215FC420516B6FB1AB868B4FC2D6455F9D20FCA11EC5C08FA2B17E0A2699F5E4692F981D2DF5D9A9B21DE51B0203010001A382013A30820136300F0603551D130101FF040530030101FF301D0603551D0E04160414ECD7E382D2715D644CDF2E673FE7BA98AE1C0F4F301F0603551D2304183016801445EBA2AFF492CB82312D518BA7A7219DF36DC80F300E0603551D0F0101FF040403020186307906082B06010505070101046D306B302406082B060105050730018618687474703A2F2F6F6373702E64696769636572742E636F6D304306082B060105050730028637687474703A2F2F636163657274732E64696769636572742E636F6D2F4469676943657274417373757265644944526F6F7443412E63727430450603551D1F043E303C303AA038A0368634687474703A2F2F63726C332E64696769636572742E636F6D2F4469676943657274417373757265644944526F6F7443412E63726C30110603551D20040A300830060604551D2000300D06092A864886F70D01010C0500038201010070A0BF435C55E7385FA0A3741B3DB616D7F7BF5707BD9AACA1872CEC855EA91ABB22F8871A695422EDA488776DBD1A14F4134A7A2F2DB738EFF4FF80B9F8A1F7F272DE24BC5203C84ED02ADEFA2D56CFF9F4F7AC307A9A8BB25ED4CFD143449B4321EB9672A148B499CB9D4FA7060313772744D4E77FE859A8F0BF2F0BA6E9F2343CECF703C787A8D24C401935466A6954B0B8A1568EECA4D53DE8B1DCFD1CD8F4775A5C548C6FEFA1503DFC760968849F6FCADB208D35601C0203CB20B0AC58A00E4063C59822C1B259F5556BCF27AB6C76CE6F232DF47E716A236B22FF12B8542D277ED83AD9F0B68796FD5BD15CAC18C34D9F73B701A99F57AA5E28E2B9943182037C30820378020101307D3069310B300906035504061302555331173015060355040A130E44696769436572742C20496E632E3141303F06035504031338446967694365727420547275737465642047342054696D655374616D70696E672052534134303936205348413235362032303235204341310210084FDC334F7E454EDBC30F8FF9921835300D06096086480165030402010500A081D1301A06092A864886F70D010903310D060B2A864886F70D0109100104301C06092A864886F70D010905310F170D3236313131303131313430315A302B060B2A864886F70D010910020C311C301A30183016041451D9ABDA034973D84F4266ACA48248E6B369C439302F06092A864886F70D01090431220420FF9C7F82CE0A2658A9D22D290DB00FD6C4A9B0352FC53AE2451823CA2E7EFC273037060B2A864886F70D010910022F312830263024302204202DA09DA7F4131F9FE72DB6C5E6E9C9656755AF043F1EA742CC0D2120E141EBFC300D06092A864886F70D01010105000482020081E74AF1D41CA6FB87123E1D8AD2B1C9F5A00DFD0BE93AE4990F1B6C592D481887C15AFDFEDDAC05C38828BCD38240623F1FBDBF578C9635F3F43C8E5E03129A4923806E6DCBA03D2F5BA59F4B2C7D9AC2DDE778787110B9AB352313BD7212AE2A8D2717142FA71B65D3BBABA63E5779884FED09706E7DF41F0FB4A1C1EDD346B163E56E7E05A9F1160D8B0A41926E8B4B643572B6B2E842BCE9390D943AF36ECF7EBD60A99D5441D98037F7FD0D30A1D738E25488E059E9BF93F54AA4B456DF34855E463A181149FD1BEA4096262240C9ACBDF914B50FB55FF7571D598D6DDF8561470BE0947E4049419082B4675FF68ADF58A473C45BB91DFA9663403D4E46BC679110BE196A2422E74ECDE70D27C8C19B9C0752A8DA68A27B1AA8628CEE26052CDB128736CCA6D25D38FEEBF24F9002120BE7CD6C8532F37DE59AF0510F81F0636CC808E6C087F68518FDDDD42A15508A2FBF8F2FAE1BBC11FBA9CB327928BE0BE21A6EBC4F3BBEBB8F17B4C56A13D3301C781FE7385EC60CFFAECA7E6534D7E4E845BD1404E28D3D0BB18495DB231B6FBCAF02D6CB547BB81CBEB11C7E9FECE622F079DBE751D81C109174AFCAECC2B58B6487ABDA5C3E13339D507E98D07021177F4B28044BD3314D644BAEE8819351C4F63EA829AEE27E26334D98528B01537317DAC6C1F60A2DC021D3FF0F7DE11815AAF6FA41268BB544843D3521E1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000>+/ByteRange [0 1891 20837 885]+>>+endobj+3 0 obj+<<+/Contents 7 0 R+/MediaBox [0 0 595.2756 841.8898]+/Parent 6 0 R+/Resources <<+/Font 1 0 R+/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]+>>+/Rotate 0+/Trans <<+>>+/Type /Page+/Annots [8 0 R]+>>+endobj+10 0 obj+<<+/N 11 0 R+>>+endobj+11 0 obj+<<+/Length 0+/Type /XObject+/Subtype /Form+/BBox [0.0 0.0 0.0 0.0]+>>+stream++endstream+endobj+4 0 obj+<<+/PageMode /UseNone+/Pages 6 0 R+/Type /Catalog+/AcroForm <<+/Fields [8 0 R]+/SigFlags 3+>>+>>+endobj+xref+0 1+0000000000 65535 f+3 3+0000020896 00000 n+0000021245 00000 n+0000001383 00000 n+8 4+0000001637 00000 n+0000001773 00000 n+0000021107 00000 n+0000021139 00000 n+trailer+<<+/ID [<BA05D6207B76E2BD3FCB557B71E8B76F> <97290DD9128BAB7FE3863D13F84028FA7609DAD8B9F8576D020FB1F01E9D740C>]+/Info 5 0 R+/Root 4 0 R+/Size 12+/Prev 1010+>>+startxref+21357+%%EOFdiff --git a/frontend/src/editor/core/tests/test-fixtures/signature-two.pdf b/frontend/src/editor/core/tests/test-fixtures/signature-two.pdfnew file mode 100644index 0000000000..e719162b24--- /dev/null+++ b/frontend/src/editor/core/tests/test-fixtures/signature-two.pdf@@ -0,0 +1,291 @@+%PDF-1.3+%���� ReportLab Generated PDF document (opensource)+1 0 obj+<<+/F1 2 0 R+>>+endobj+2 0 obj+<<+/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font+>>+endobj+3 0 obj+<<+/Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources <<+/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]+>> /Rotate 0 /Trans <<++>>+ /Type /Page+>>+endobj+4 0 obj+<<+/PageMode /UseNone /Pages 6 0 R /Type /Catalog+>>+endobj+5 0 obj+<<+/Author (anonymous) /CreationDate (D:20261110111401+00'00') /Creator (anonymous) /Keywords () /ModDate (D:20261110111401+00'00') /Producer (ReportLab PDF Library - \(opensource\))+ /Subject (unspecified) /Title (Signature probe fixture) /Trapped /False+>>+endobj+6 0 obj+<<+/Count 1 /Kids [ 3 0 R ] /Type /Pages+>>+endobj+7 0 obj+<<+/Filter [ /ASCII85Decode /FlateDecode ] /Length 115+>>+stream+GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<;D:$c:^G0Ccj7ojcV#f</P9"k.*>=X<Ck<7!:_l\6F%:lZp=I%\,\>5(]X~>endstream+endobj+xref+0 8+0000000000 65535 f+0000000061 00000 n+0000000092 00000 n+0000000199 00000 n+0000000402 00000 n+0000000470 00000 n+0000000746 00000 n+0000000805 00000 n+trailer+<<+/ID+[<ba05d6207b76e2bd3fcb557b71e8b76f><ba05d6207b76e2bd3fcb557b71e8b76f>]+% ReportLab generated PDF document -- digest (opensource)++/Info 5 0 R+/Root 4 0 R+/Size 8+>>+startxref+1010+%%EOF++5 0 obj+<<+/Author (anonymous)+/CreationDate (D:20261110111401+00'00')+/Creator (anonymous)+/Keywords ()+/ModDate (D:20261110111401+00'00')+/Producer (Stirling-PDF v3.3.0)+/Subject (unspecified)+/Title (Signature probe fixture)+/Trapped /False+>>+endobj+8 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature1)+/V 9 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 10 0 R+>>+endobj+9 0 obj+<<+/Type /Sig+/Filter /Adobe.PPKLite+/SubFilter /adbe.pkcs7.detached+/Reason (Approved)+/M (D:20261110111401+00'00')+/Contents <308006092A864886F70D010702A0803080020101310D300B0609608648016503040201300B06092A864886F70D010701A0803082035930820241A00302010202145D6EC4A703506FC37A82ED3838CD6C40247302A7300D06092A864886F70D01010C0500303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E65723020170D3235303130313030303030305A180F32313235303130313030303030305A303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657230820122300D06092A864886F70D01010105000382010F003082010A0282010100BBFB2719030B25ED07591CDB88A67C664D13A00C11BF9E9F297B5F7889321904C4F962BBBB12A169049A6130E75F6DB695621BA60D09A567082A4C09626E47408E254A25590A6E8DC7747C988CDA77EAD0BAA111FA7B1DFD61BF893E8C5E8A21B30FB6FD46604FF40AB9CE4F5B13E7903EE457277837D9B0820368C2EBBC25CBCB87F4DD6715D84BA63FC68016433C50F3388BC1965A94FF3242372A09363593CA3051334D764C9BE043E18F4A54F6F310DD5F7470E197BE42F3AB17E057A126EFCA51178BF5B76D964C25CFA4EF778CFB43F5F6D4A91F6E957C5C2CF452C0A57F7CC74C56B7ACB4A5C6584AD19C547D5178BEF0DCE0039FAC7F59AA1A2AC1C10203010001A3533051301F0603551D230418301680142271595BA068E88537F2FAD13C0A3072BA9DBF35300F0603551D130101FF040530030101FF301D0603551D0E041604142271595BA068E88537F2FAD13C0A3072BA9DBF35300D06092A864886F70D01010C05000382010100AE465AE45BAB23922FEFE2C91A5418473C1A9DBD198DD7F0C08170F596FC7462CD9A62534D6A8B78506010E3CAB4335CB16E7E7D93B3B6FFFED24FF6F66026C0B9FB64BC42F5A4AB8730C902B677EAA16B0FFD36F13B67DDB488292BA45F1AF04E915A5EE0E50084AF7F33BE063FBE54F556D98B8DEE2E222208BA571809BF1DB07A409D2D394BABE8BB72E94FA5279701C3298BCC607C9DF3C0910788FFFD2F1F66F2C10C43541C13D9D6574E238049CB3C7B2BF53C9D80FD302B8B0D540BC0E5E12F5C52E013D5BE97D71F6954739F763FC29D175CFFA3B978FBEFD2B73E69298F669CAA2E43295CC5D883E1A74E93EA0FBB40745B5549529B50F4C8BEDC58000031820215308202110201013053303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657202145D6EC4A703506FC37A82ED3838CD6C40247302A7300B0609608648016503040201A08196301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3236313131303131313430315A302B06092A864886F70D010934311E301C300B0609608648016503040201A10D06092A864886F70D01010B0500302F06092A864886F70D0109043122042087C62DD1FA7B03E76E3730B45B44A368BB153CECEA4B777ADABDA558D0AE61BA300D06092A864886F70D01010B0500048201007DEE06968A7DDA6AD933A8EB319F59200B335E30CDA30F58916B40E806FAC0FCE59793466E769DED0C78770197C7441205950B82407BBE20D789B07B3F006E0F327CA6AAE03B1ED2DD55F3C49C671AF2B7F3B6060B1857E754782FDC741C279515FCA89E368A568B9439011AEC7CE3747B6BE3E620AB88A770087D815D17CAA60F8445116FE13BB14401687D5AA5A9D858603CF959ADD6CCDEB49C7DB586AD0C3915D772AD5920447AE371C1B8C132EDEA6A5F0D040E623E321CE51DEE0101CA0E5A678BA9AA1DE0C28F67C3F601E95855E24FD37B2C225B7ECFB46B5EA746F99EC80C33A39BF5C144CAF38A6B750693A5D5E91E93D94ECDA71E8457402C00D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000>+/ByteRange [0 1908 20854 885]+>>+endobj+3 0 obj+<<+/Contents 7 0 R+/MediaBox [0 0 595.2756 841.8898]+/Parent 6 0 R+/Resources <<+/Font 1 0 R+/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]+>>+/Rotate 0+/Trans <<+>>+/Type /Page+/Annots [8 0 R]+>>+endobj+10 0 obj+<<+/N 11 0 R+>>+endobj+11 0 obj+<<+/Length 0+/Type /XObject+/Subtype /Form+/BBox [0.0 0.0 0.0 0.0]+>>+stream++endstream+endobj+4 0 obj+<<+/PageMode /UseNone+/Pages 6 0 R+/Type /Catalog+/AcroForm <<+/Fields [8 0 R]+/SigFlags 3+>>+>>+endobj+xref+0 1+0000000000 65535 f+3 3+0000020913 00000 n+0000021262 00000 n+0000001383 00000 n+8 4+0000001637 00000 n+0000001773 00000 n+0000021124 00000 n+0000021156 00000 n+trailer+<<+/ID [<BA05D6207B76E2BD3FCB557B71E8B76F> <DDBCF3CD22977ED0CD63354BDF94B173D1C5A047083DE553A31F16F03D04BAE9>]+/Info 5 0 R+/Root 4 0 R+/Size 12+/Prev 1010+>>+startxref+21374+%%EOF++5 0 obj+<<+/Author (anonymous)+/CreationDate (D:20261110111401+00'00')+/Creator (anonymous)+/Keywords ()+/ModDate (D:20261110111401+00'00')+/Producer (Stirling-PDF v3.3.0)+/Subject (unspecified)+/Title (Signature probe fixture)+/Trapped /False+>>+endobj+8 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature1)+/V 9 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 10 0 R+>>+endobj+12 0 obj+<<+/FT /Sig+/Type /Annot+/Subtype /Widget+/F 132+/T (Signature2)+/V 13 0 R+/P 3 0 R+/Rect [0.0 0.0 0.0 0.0]+/AP 14 0 R+>>+endobj+13 0 obj+<<+/Type /Sig+/Filter /Adobe.PPKLite+/SubFilter /adbe.pkcs7.detached+/Reason (Countersigned)+/M (D:20261110111401+00'00')+/Contents <308006092A864886F70D010702A0803080020101310D300B0609608648016503040201300B06092A864886F70D010701A0803082035930820241A00302010202145D6EC4A703506FC37A82ED3838CD6C40247302A7300D06092A864886F70D01010C0500303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E65723020170D3235303130313030303030305A180F32313235303130313030303030305A303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657230820122300D06092A864886F70D01010105000382010F003082010A0282010100BBFB2719030B25ED07591CDB88A67C664D13A00C11BF9E9F297B5F7889321904C4F962BBBB12A169049A6130E75F6DB695621BA60D09A567082A4C09626E47408E254A25590A6E8DC7747C988CDA77EAD0BAA111FA7B1DFD61BF893E8C5E8A21B30FB6FD46604FF40AB9CE4F5B13E7903EE457277837D9B0820368C2EBBC25CBCB87F4DD6715D84BA63FC68016433C50F3388BC1965A94FF3242372A09363593CA3051334D764C9BE043E18F4A54F6F310DD5F7470E197BE42F3AB17E057A126EFCA51178BF5B76D964C25CFA4EF778CFB43F5F6D4A91F6E957C5C2CF452C0A57F7CC74C56B7ACB4A5C6584AD19C547D5178BEF0DCE0039FAC7F59AA1A2AC1C10203010001A3533051301F0603551D230418301680142271595BA068E88537F2FAD13C0A3072BA9DBF35300F0603551D130101FF040530030101FF301D0603551D0E041604142271595BA068E88537F2FAD13C0A3072BA9DBF35300D06092A864886F70D01010C05000382010100AE465AE45BAB23922FEFE2C91A5418473C1A9DBD198DD7F0C08170F596FC7462CD9A62534D6A8B78506010E3CAB4335CB16E7E7D93B3B6FFFED24FF6F66026C0B9FB64BC42F5A4AB8730C902B677EAA16B0FFD36F13B67DDB488292BA45F1AF04E915A5EE0E50084AF7F33BE063FBE54F556D98B8DEE2E222208BA571809BF1DB07A409D2D394BABE8BB72E94FA5279701C3298BCC607C9DF3C0910788FFFD2F1F66F2C10C43541C13D9D6574E238049CB3C7B2BF53C9D80FD302B8B0D540BC0E5E12F5C52E013D5BE97D71F6954739F763FC29D175CFFA3B978FBEFD2B73E69298F669CAA2E43295CC5D883E1A74E93EA0FBB40745B5549529B50F4C8BEDC58000031820215308202110201013053303B310B300906035504061302474231163014060355040A0C0D537469726C696E6720546573743114301206035504030C0B54657374205369676E657202145D6EC4A703506FC37A82ED3838CD6C40247302A7300B0609608648016503040201A08196301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3236313131303131313430315A302B06092A864886F70D010934311E301C300B0609608648016503040201A10D06092A864886F70D01010B0500302F06092A864886F70D010904312204204227E2898E027B39D732606E1802B95378BD180463C826376E3A91F9E181EA0E300D06092A864886F70D01010B0500048201001883FAD57914236A2A2324CE31538A68FBB1DA4812D1FE293D1554110EA5A4D15B7714B070CCAD554FB1965E3D737C18382CE8B68C0FB6A0CE4BE5E59FF8A0BC611989F0C3E37380C8870A6C13A37C8560C9CF8240FDB04A52D91C26A4E9A8F0E3EB8B5976C778CBCF13A6F7D1099B6886E01266EF0BB0C9AD8C0D167244A37FE22E52008791BAD0CC756BE7111017BEF1799A878DD82198F7EA5AB3CDDC813520F015BA681EBD309C1DE5857EF28765836769A23EAEE063BE204C91A46C99CC9F8E89478A52ABECA9D353EBD55E37225760C2F35983EE192436641AEF4ADA1321F6E7EB9A21C63592897AC1AF85FF2F7C7FBB90CD3C0C6D63B0FA8ED9F651F9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000>+/ByteRange [0 22410 41356 925]+>>+endobj+3 0 obj+<<+/Contents 7 0 R+/MediaBox [0 0 595.2756 841.8898]+/Parent 6 0 R+/Resources <<+/Font 1 0 R+/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]+>>+/Rotate 0+/Trans <<+>>+/Type /Page+/Annots [8 0 R 12 0 R]+>>+endobj+14 0 obj+<<+/N 15 0 R+>>+endobj+15 0 obj+<<+/Length 0+/Type /XObject+/Subtype /Form+/BBox [0.0 0.0 0.0 0.0]+>>+stream++endstream+endobj+4 0 obj+<<+/PageMode /UseNone+/Pages 6 0 R+/Type /Catalog+/AcroForm <<+/Fields [8 0 R 12 0 R]+/SigFlags 3+>>+>>+endobj+xref+0 1+0000000000 65535 f+3 3+0000041415 00000 n+0000041771 00000 n+0000021741 00000 n+8 1+0000021995 00000 n+12 4+0000022131 00000 n+0000022269 00000 n+0000041633 00000 n+0000041665 00000 n+trailer+<<+/ID [<BA05D6207B76E2BD3FCB557B71E8B76F> <5EC33B2130238B9932DFEE2CE2E12FC97D9E5062377072F652E54AE5EABE1271>]+/Info 5 0 R+/Root 4 0 R+/Size 16+/Prev 21374+>>+startxref+41890+%%EOFdiff --git a/frontend/src/editor/core/tools/Annotate.tsx b/frontend/src/editor/core/tools/Annotate.tsxindex 5d45639839..90279f5f3e 100644--- a/frontend/src/editor/core/tools/Annotate.tsx+++ b/frontend/src/editor/core/tools/Annotate.tsx@@ -6,7 +6,10 @@ import { createToolFlow } from "@editor/components/tools/shared/createToolFlow";import { useNavigation } from "@editor/contexts/NavigationContext";import { useViewScopedFiles } from "@editor/hooks/tools/shared/useViewScopedFiles";import { usePdfAccess } from "@editor/hooks/usePdfAccess";-import { getPdfAccess } from "@editor/services/pdfAccessService";+import {+ getPdfAccess,+ signedPdfEditsBlocked,+} from "@editor/services/pdfAccessService";import { BaseToolProps } from "@editor/types/tool";import { useSignature } from "@editor/contexts/SignatureContext";import { useAnnotation as useAnnotationContext } from "@editor/contexts/AnnotationContext";@@ -81,9 +84,10 @@ const Annotate = (_props: BaseToolProps) => {useNavigation();const scopedFiles = useViewScopedFiles();usePdfAccess(undefined);- const editableFiles = scopedFiles.filter(- (file) => !getPdfAccess(file)?.encrypted,- );+ const editableFiles = scopedFiles.filter((file) => {+ const access = getPdfAccess(file);+ return !access?.encrypted && !signedPdfEditsBlocked(access);+ });const {signatureApiRef,annotationApiRef,diff --git a/frontend/src/editor/core/tools/Redact.tsx b/frontend/src/editor/core/tools/Redact.tsxindex 3758c819ce..5e115ed60f 100644--- a/frontend/src/editor/core/tools/Redact.tsx+++ b/frontend/src/editor/core/tools/Redact.tsx@@ -24,6 +24,11 @@ import {} from "@editor/contexts/NavigationContext";import { useRedaction } from "@editor/contexts/RedactionContext";import { useFileState } from "@editor/contexts/file/fileHooks";+import { useViewScopedFiles } from "@editor/hooks/tools/shared/useViewScopedFiles";+import {+ getPdfAccess,+ signedPdfEditsBlocked,+} from "@editor/services/pdfAccessService";const Redact = (props: BaseToolProps) => {const { t } = useTranslation();@@ -62,6 +67,9 @@ const Redact = (props: BaseToolProps) => {// Get total file count from context (any files in workbench, not just selected)const { state: fileState } = useFileState();const hasAnyFiles = fileState.files.ids.length > 0;+ const signedEditsBlocked = useViewScopedFiles().some((file) =>+ signedPdfEditsBlocked(getPdfAccess(file)),+ );// Tooltips for each stepconst modeTips = useRedactModeTips();@@ -232,7 +240,11 @@ const Redact = (props: BaseToolProps) => {isCollapsed: false,onCollapsedClick: () => {},tooltip: manualTips,- content: <ManualRedactionControls disabled={!hasAnyFiles} />,+ content: (+ <ManualRedactionControls+ disabled={!hasAnyFiles || signedEditsBlocked}+ />+ ),});}diff --git a/frontend/src/editor/core/tools/formFill/FormFill.tsx b/frontend/src/editor/core/tools/formFill/FormFill.tsxindex cc7eeda629..5769682c47 100644--- a/frontend/src/editor/core/tools/formFill/FormFill.tsx+++ b/frontend/src/editor/core/tools/formFill/FormFill.tsx@@ -34,6 +34,7 @@ import { useFieldShortcuts } from "@editor/tools/formFill/useFieldShortcuts";import { serverMessage } from "@editor/tools/formFill/useFormCommit";import { useViewer } from "@editor/contexts/ViewerContext";import { usePdfAccess } from "@editor/hooks/usePdfAccess";+import { pdfEditingLocked } from "@editor/services/pdfPermissions";import { useAllFiles, useFileState } from "@editor/contexts/FileContext";import { Skeleton } from "@mantine/core";import { isStirlingFile, getFormFillFileId } from "@editor/types/fileContext";@@ -216,7 +217,8 @@ const FormFill = (_props: BaseToolProps) => {return activeFiles[0];}, [activeFiles, selectedFileIds, activeFileId]);const pdfAccess = usePdfAccess(viewedFile);- const currentFile = pdfAccess?.encrypted === false ? viewedFile : null;+ const editingLocked = pdfEditingLocked(pdfAccess);+ const currentFile = editingLocked ? null : viewedFile;const handleExtractCsv = useCallback(async () => {if (!currentFile) return;@@ -501,7 +503,7 @@ const FormFill = (_props: BaseToolProps) => {}, [requiredFields, allValues]);if (!isActive) return null;- if (viewedFile && pdfAccess?.encrypted) {+ if (viewedFile && pdfAccess && editingLocked) {return (<Stack gap="sm" p="sm">{createToolSteps().createFilesStep({ selectedFiles: [] })}diff --git a/frontend/src/editor/core/tools/stamp/createStampTool.tsx b/frontend/src/editor/core/tools/stamp/createStampTool.tsxindex 0b1328d921..8cafb5bae3 100644--- a/frontend/src/editor/core/tools/stamp/createStampTool.tsx+++ b/frontend/src/editor/core/tools/stamp/createStampTool.tsx@@ -23,6 +23,14 @@ import SharedSigningLauncher from "@editor/components/shared/signing/SharedSigniimport { SuggestedToolsSection } from "@editor/components/tools/shared/SuggestedToolsSection";import { useGroupSigningEnabled } from "@editor/hooks/useGroupSigningEnabled";import { alert } from "@editor/components/toast";+import {+ getPdfAccess,+ signedPdfEditsBlocked,+} from "@editor/services/pdfAccessService";+import {+ assertSignedPdfsEditable,+ SignedPdfEditsBlockedError,+} from "@editor/services/pdfSessionUnlock";export type StampToolConfig = {toolId: ToolId;@@ -93,6 +101,10 @@ export const createStampTool = (config: StampToolConfig) => {props,);+ const selectedFiles = base.selectedFiles.filter(+ (file) => !signedPdfEditsBlocked(getPdfAccess(file)),+ );+const allowedSignatureTypes = allowedSignatureSources.filter((source): source is SignParameters["signatureType"] => source !== "saved",);@@ -143,11 +155,11 @@ export const createStampTool = (config: StampToolConfig) => {useEffect(() => handleDeactivateSignature, [handleDeactivateSignature]);useEffect(() => {- if (base.selectedFiles.length > 0 && !hasOpenedViewer.current) {+ if (selectedFiles.length > 0 && !hasOpenedViewer.current) {setWorkbench("viewer");hasOpenedViewer.current = true;}- }, [base.selectedFiles.length, setWorkbench]);+ }, [selectedFiles.length, setWorkbench]);useEffect(() => {setSignatureConfig(base.params.parameters);@@ -175,6 +187,7 @@ export const createStampTool = (config: StampToolConfig) => {if (!originalFile) {throw new Error("No file available to replace");}+ await assertSignedPdfsEditable([originalFile], undefined, true);const flattenResult = await flattenSignatures({signatureApiRef,@@ -205,17 +218,29 @@ export const createStampTool = (config: StampToolConfig) => {} catch (error) {console.error("Error saving signed document:", error);setHasUnsavedChanges(true);- alert({- alertType: "error",- title: t(- "sign.wallet.toast.applyFailed",- "Could not apply signatures",- ),- body: t(- "sign.wallet.toast.applyFailedBody",- "Your signatures are still on the document. Try again.",- ),- });+ alert(+ error instanceof SignedPdfEditsBlockedError+ ? {+ alertType: "warning",+ title: t(+ "signedPdf.editsBlockedTitle",+ "Signed PDF can't be changed",+ ),+ body: error.message,+ expandable: false,+ }+ : {+ alertType: "error",+ title: t(+ "sign.wallet.toast.applyFailed",+ "Could not apply signatures",+ ),+ body: t(+ "sign.wallet.toast.applyFailedBody",+ "Your signatures are still on the document. Try again.",+ ),+ },+ );return false;} finally {applyInFlightRef.current = false;@@ -292,7 +317,7 @@ export const createStampTool = (config: StampToolConfig) => {const getSteps = () => {const steps = [];- if (base.selectedFiles.length > 0) {+ if (selectedFiles.length > 0) {steps.push({title: translateTool("steps.configure", "Configure Stamp"),isCollapsed: false,@@ -316,7 +341,7 @@ export const createStampTool = (config: StampToolConfig) => {return createToolFlow({files: {- selectedFiles: base.selectedFiles,+ selectedFiles,isCollapsed: base.operation.files.length > 0,},steps: getSteps(),diff --git a/frontend/src/editor/core/types/appConfig.ts b/frontend/src/editor/core/types/appConfig.tsindex c7a2b28829..0d62423828 100644--- a/frontend/src/editor/core/types/appConfig.ts+++ b/frontend/src/editor/core/types/appConfig.ts@@ -8,6 +8,7 @@ export interface AppConfig {defaultLocale?: string;enableLogin?: boolean;honorOwnerPasswords?: boolean;+ blockSignedPdfEdits?: boolean;showSettingsWhenNoLogin?: boolean;enableEmailInvites?: boolean;enableOAuth?: boolean;diff --git a/frontend/src/editor/core/utils/automationExecutor.test.ts b/frontend/src/editor/core/utils/automationExecutor.test.tsindex fb3cc9fd78..b5b0231f00 100644--- a/frontend/src/editor/core/utils/automationExecutor.test.ts+++ b/frontend/src/editor/core/utils/automationExecutor.test.ts@@ -7,6 +7,10 @@ import {executeToolOperation,processMultiFileResponse,} from "@editor/utils/automationExecutor";+import {+ rememberPdfAccess,+ setSignedPdfEditPolicy,+} from "@editor/services/pdfAccessService";vi.mock("@editor/services/apiClient", () => ({default: {@@ -124,3 +128,70 @@ describe("executeToolOperation (automation execution)", () => {);});});++describe("automation steps on a signed PDF while edits are blocked", () => {+ const registry = (endpoint: string) =>+ ({+ step: {+ operationConfig: {+ operationType: "step",+ toolType: ToolType.singleFile,+ endpoint,+ defaultParameters: {},+ buildFormData: (_parameters: unknown, file: File) => {+ const formData = new FormData();+ formData.append("fileInput", file);+ return formData;+ },+ },+ },+ }) as unknown as ToolRegistry;++ function signedFile() {+ const file = new File(["%PDF-1.7"], "signed.pdf", {+ type: "application/pdf",+ });+ rememberPdfAccess(file, {+ password: "",+ encrypted: false,+ signed: true,+ ownerAuthenticated: false,+ permissions: -4,+ pageCount: 1,+ });+ return file;+ }++ beforeEach(() => {+ vi.clearAllMocks();+ setSignedPdfEditPolicy(true);+ (mockedApiClient.post as Mock).mockResolvedValue({+ data: new Blob([PDF_BYTES], { type: "application/pdf" }),+ headers: { "content-type": "application/pdf" },+ });+ });++ test("refuses a step that rewrites the PDF", async () => {+ await expect(+ executeToolOperation(+ "step",+ {},+ [signedFile()],+ registry("/api/v1/general/rotate-pdf"),+ ),+ ).rejects.toThrow("digitally signed");+ expect(mockedApiClient.post).not.toHaveBeenCalled();+ setSignedPdfEditPolicy(false);+ });++ test("runs a step that only converts it", async () => {+ await executeToolOperation(+ "step",+ {},+ [signedFile()],+ registry("/api/v1/convert/pdf/img"),+ );+ expect(mockedApiClient.post).toHaveBeenCalled();+ setSignedPdfEditPolicy(false);+ });+});diff --git a/frontend/src/editor/core/utils/automationExecutor.ts b/frontend/src/editor/core/utils/automationExecutor.tsindex 0e8feb5e59..343b864f64 100644--- a/frontend/src/editor/core/utils/automationExecutor.ts+++ b/frontend/src/editor/core/utils/automationExecutor.ts@@ -13,6 +13,7 @@ import { zipFileService } from "@editor/services/zipFileService";import { processResponse } from "@editor/utils/toolResponseProcessor";import { extractErrorMessage } from "@editor/utils/toolErrorHandler";import { type AutomationConfig } from "@editor/types/automation";+import { assertSignedPdfsEditable } from "@editor/services/pdfSessionUnlock";export const processMultiFileResponse = async (responseData: Blob,@@ -178,6 +179,15 @@ export const executeToolOperationWithPrefix = async (// Merge with default parameters to ensure all required fields are presentconst mergedParameters = { ...config.defaultParameters, ...parameters };+ const stepEndpoint =+ (typeof config.endpoint === "function"+ ? config.endpoint(mergedParameters)+ : config.endpoint) ?? undefined;+ await assertSignedPdfsEditable(+ files,+ stepEndpoint,+ !stepEndpoint && !!config.customProcessor,+ );try {// Check if tool uses custom processor (like Convert tool)diff --git a/frontend/src/editor/core/utils/pdfProbeChecks.test.ts b/frontend/src/editor/core/utils/pdfProbeChecks.test.tsnew file mode 100644index 0000000000..b17d58a03d--- /dev/null+++ b/frontend/src/editor/core/utils/pdfProbeChecks.test.ts@@ -0,0 +1,95 @@+// @vitest-environment node+import fs from "node:fs";+import path from "node:path";+import { beforeAll, describe, expect, it } from "vitest";+import { init, type WrappedPdfiumModule } from "@embedpdf/pdfium";+import { readPdfiumAccess } from "@editor/utils/pdfiumAccess";+import { backgroundChecksAfter } from "@editor/utils/pdfProbeChecks";+import type { PdfAccess } from "@editor/services/pdfAccessService";++const BLOCKING_BUDGET_MS = 250;+let pdfium: WrappedPdfiumModule;++beforeAll(async () => {+ const wasm = fs.readFileSync(+ path.join(process.cwd(), "node_modules/@embedpdf/pdfium/dist/pdfium.wasm"),+ );+ pdfium = await init({+ wasmBinary: wasm.buffer.slice(+ wasm.byteOffset,+ wasm.byteOffset + wasm.byteLength,+ ),+ });+ pdfium.PDFiumExt_Init();+});++function largePdf(streamBytes: number): Uint8Array {+ const encoder = new TextEncoder();+ const parts: Uint8Array[] = [];+ const offsets: number[] = [];+ let length = 0;+ const push = (part: string | Uint8Array) => {+ const bytes = typeof part === "string" ? encoder.encode(part) : part;+ parts.push(bytes);+ length += bytes.length;+ };+ push("%PDF-1.7\n");+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>",+ ];+ objects.forEach((body, i) => {+ offsets.push(length);+ push(`${i + 1} 0 obj\n${body}\nendobj\n`);+ });+ offsets.push(length);+ push(`4 0 obj\n<< /Length ${streamBytes} >>\nstream\n`);+ push(new Uint8Array(streamBytes).fill(0x20));+ push("\nendstream\nendobj\n");+ const xref = length;+ push(+ `xref\n0 5\n0000000000 65535 f \n${offsets+ .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)+ .join(+ "",+ )}trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`,+ );+ const pdf = new Uint8Array(length);+ let at = 0;+ for (const part of parts) {+ pdf.set(part, at);+ at += part.length;+ }+ return pdf;+}++describe("local PDF probe checks", () => {+ it("answers the blocking checks without reading the whole of a large file", () => {+ const bytes = largePdf(64 * 1024 * 1024);+ const pointer = pdfium.pdfium.wasmExports.malloc(bytes.length);+ (pdfium.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8.set(+ bytes,+ pointer,+ );+ try {+ const started = performance.now();+ const document = pdfium.FPDF_LoadMemDocument(pointer, bytes.length, "");+ const access = readPdfiumAccess(pdfium, document, "");+ const elapsed = performance.now() - started;+ pdfium.FPDF_CloseDocument(document);+ expect(access).toMatchObject({ encrypted: false, signed: false });+ expect(elapsed).toBeLessThan(BLOCKING_BUDGET_MS);+ } finally {+ pdfium.pdfium.wasmExports.free(pointer);+ }+ });++ it("schedules background work only for the blocking facts that need it", () => {+ const plain = { signed: false } as PdfAccess;+ expect(backgroundChecksAfter(plain)).toEqual([]);+ expect(backgroundChecksAfter({ ...plain, signed: true })).toEqual([+ "signatures",+ ]);+ });+});diff --git a/frontend/src/editor/core/utils/pdfProbeChecks.ts b/frontend/src/editor/core/utils/pdfProbeChecks.tsnew file mode 100644index 0000000000..166fdbc88b--- /dev/null+++ b/frontend/src/editor/core/utils/pdfProbeChecks.ts@@ -0,0 +1,63 @@+/**+ * Every check the local PDF probe runs on an opened document, in two phases:+ * - Blocking (synchronous): facts that decide what an action may do, such as encryption, permissions,+ * or `signed` for the signed-PDF edit block. They are fields on `PdfAccess`, read by+ * `readPdfiumAccess`, and answered first; callers await only these. Each must be a fact PDFium+ * has once the document is open, so the answer stays in milliseconds whatever the file size.+ * - Background (asynchronous): information never awaited by an action. One entry in+ * `backgroundChecks` per key of `PdfProbeDetails`, run after the blocking answer is sent and only+ * when `after` holds for it. Cost may grow with file size.+ * A check with both halves pairs a blocking field with a background entry gated on it: `signed`+ * blocks edits at once, and `signatures` validates them afterwards.+ *+ * Background checks run one at a time on the same document and file bytes in WASM memory, and may+ * rearrange those bytes while running as long as they restore them before resolving.+ */+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import type { PdfAccess } from "@editor/services/pdfAccessService";+import {+ readPdfiumSignatures,+ type PdfSignatureInfo,+} from "@editor/utils/pdfiumSignatures";++export interface PdfProbeDetails {+ signatures: PdfSignatureInfo[];+}++export type PdfProbeDetailKey = keyof PdfProbeDetails;++export interface OpenedPdf {+ module: WrappedPdfiumModule;+ document: number;+ file: { pointer: number; length: number };+}++type BackgroundChecks = {+ [K in PdfProbeDetailKey]: {+ after: (access: PdfAccess) => boolean;+ run: (pdf: OpenedPdf) => Promise<PdfProbeDetails[K]>;+ };+};++export const backgroundChecks: BackgroundChecks = {+ signatures: {+ after: (access) => access.signed,+ run: ({ module, document, file }) =>+ readPdfiumSignatures(module, document, file),+ },+};++const detailKeys = Object.keys(backgroundChecks) as PdfProbeDetailKey[];++export function backgroundChecksAfter(access: PdfAccess): PdfProbeDetailKey[] {+ return detailKeys.filter((key) => backgroundChecks[key].after(access));+}++export async function runBackgroundCheck<K extends PdfProbeDetailKey>(+ key: K,+ pdf: OpenedPdf,+): Promise<Partial<PdfProbeDetails>> {+ const details: Partial<PdfProbeDetails> = {};+ details[key] = await backgroundChecks[key].run(pdf);+ return details;+}diff --git a/frontend/src/editor/core/utils/pdfSignatureCms.test.ts b/frontend/src/editor/core/utils/pdfSignatureCms.test.tsnew file mode 100644index 0000000000..7856d01329--- /dev/null+++ b/frontend/src/editor/core/utils/pdfSignatureCms.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { readCmsSignatureFacts } from "@editor/utils/pdfSignatureCms";++const decode = (base64: string) =>+ Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+const BY_SERIAL = decode(+ "MIIIxgYJKoZIhvcNAQcCoIIItzCCCLMCAQExDTALBglghkgBZQMEAgEwCwYJKoZIhvcNAQcBoIIGTDCCAyAwggIIoAMCAQICAQEwDQYJKoZIhvcNAQELBQAwKTETMBEGA1UEAwwKVGVzdCBEZWNveTESMBAGA1UECgwJRGVjb3kgT3JnMB4XDTI2MTExNjEzNDUwMFoXDTM2MTExMzEzNDUwMFowKTETMBEGA1UEAwwKVGVzdCBEZWNveTESMBAGA1UECgwJRGVjb3kgT3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjUAD2cCj+U5fdv1O0qfK5dkaAJIEdmlNu7Raq0dtUZdDVLjbF8ijzPVrPRgisMEyW6ClQdPMfBYfxUTiRQoLtiJEWCaVnSuEmfPw//Ap9Vo+WviOn0VLdhkWliPM4qzkPnhL1Hy7zFpjGcmxeKiyCQaCqrrVjbE14UdNDcnCxQRU3RWaqUyyTMZLpogcOGddCg8qOo6K1i5+FxnBhtCmAha2tqiP6lhCgDkiCRHP46AO8DUpr4Cqse5IMJmlsjvmEPHkNC6vUMuKRyl2D5odj17AqwXi5FcBHzsCM2Pi0i9Pr4dnjXXKapt1HI7SnukfkPNllA9iIKsA3J0D9oRhtwIDAQABo1MwUTAfBgNVHSMEGDAWgBSlf0Lsd206tScuEfAyh09TpOqwhzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSlf0Lsd206tScuEfAyh09TpOqwhzANBgkqhkiG9w0BAQsFAAOCAQEAdizCkx+XbCGG7b0SkBartNmGJJE5AVCJc65AcR3lBWWnOjEpWfJda4gatEySD8JyHu2UQTxcIAUIUTVzL/dr6+C7WoXhjYaaBqS7NSp4tgCr9RPll9LCJHF2caW3q539EpabNETbqJERxyFei5Eqj2FJ5CFoxB9H5/AZXE2Yt9odjypM1qIoEEZBvXWlX9YaDN49QOyqgj0Wk3nN5C5XXc3aB4WKpsQCZ4Y8YcU1X+Z9v5NFvx7CtFfvcbmJUbmp9X32HtPfJe9oQ0zLA5juSCLVWmE3HWvcCD+XTv4qPJ1AyRE1gHATAxOo3PETVdtlkbu1/oZKvnvHqwNWLpkEtDCCAyQwggIMoAMCAQICAQEwDQYJKoZIhvcNAQELBQAwKzEUMBIGA1UEAwwLVGVzdCBTaWduZXIxEzARBgNVBAoMClNpZ25lciBPcmcwHhcNMjYxMTE2MTM0NTAwWhcNMzYxMTEzMTM0NTAwWjArMRQwEgYDVQQDDAtUZXN0IFNpZ25lcjETMBEGA1UECgwKU2lnbmVyIE9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMSTT+lVFn3CpkfMNeX1qmUpOznGTHWJJAHgHmc5loSFPMzwGwS/6+DvWVrMKJSKIJK1YsxOQP8m8L2JD1sbOzw0hAqII0Wz9sX5UvoHar1F17ceVSxUHxB2ufRYrvG+Rx8HcDzTbEDbEMygao65CW3UrE/I4JmK3aXeLKJEENyCOhRzIULqmoZqqbx7hGO8XLun37PHGt7aLMvVuLOe8gjhlZ+LjdZ22x4WiVHlIRMQERrZi4z4RiuJf244EL6UwQnz5yLttN8i/UX/uIGqjtHr+TvbzETePv/jMitoFQoReAEbV4DALIChoKKmhx7CBy9y+BRFg4o7+2mqArCm3qkCAwEAAaNTMFEwHwYDVR0jBBgwFoAUEXsrYDKzr60Ty7PR+iKTFpg+14AwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUEXsrYDKzr60Ty7PR+iKTFpg+14AwDQYJKoZIhvcNAQELBQADggEBAEYg+HCOBHEwimtyJdQxK9DGwQ2o9q2elUb+I3iSbG9deFvMUTubvZcCFokRVlDrlkMuIDi7qxEUmBWyRohpmX4ZwzjOIFbqvN58oFTJbDX2TzZEIXN29cjRJzwlClYmEs/XBc1n9FGdwo4WmlaRJH4NlIq/GwbR9wbvPzVGoxj3JYKHpSPsrqHspG+Yq9nKHIEFtue6rF1g5XZgNX0b8YvL71f9+nuAqomQYpvfVzqpywYqr36iv9OFcpBueTUrDss1S1vgiO0z2BMaOKKqEwLuYAPDhxCtVK09SyCXPafT1wHAiGHLjuG2YMlFS/yDbo0Tt194XZtAmvOTQe4cHH8xggJAMIICPAIBATAwMCsxFDASBgNVBAMMC1Rlc3QgU2lnbmVyMRMwEQYDVQQKDApTaWduZXIgT3JnAgEBMAsGCWCGSAFlAwQCAaCB5DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0yNjExMTYxMzQ1MDBaMC8GCSqGSIb3DQEJBDEiBCAs8k26X7CjDiboOyrFueKeGxYeXB+nQl5zBDNik4uYJDB5BgkqhkiG9w0BCQ8xbDBqMAsGCWCGSAFlAwQBKjALBglghkgBZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEFAASCAQAIyE+MDjI4lE/QcUGNMW5eI8wf8FfrTjF7bTzgy7KIWz2kq/I6mYB6DKUxm+n77FwOygpvvqYMXH7TkaSgBdgLBR5jf7nb3pPvpE2rFuqAXAs17cySe3Fa9vAJJx9h0j+KX6mtgWP+UTdNKiE2SAuf+ui9bxQo5drjcd+S2a7PhMaIZaQF1NwngSMc+fEOkyKtwEGfx+So175c2Squ4/QFkRr5BUdvkYTQCjWS1jkh+MjyPq2F/wmbn9+7w11L9wXpgjSULFi9xaK2XxknVP6PW0bAeDmwmevWSuT73JcA0D08v7JNkYBKCyHalRsgM85ml9NwzgYtnXPd49dVPsXH",+);+const BY_KEY_ID = decode(+ "MIIIqgYJKoZIhvcNAQcCoIIImzCCCJcCAQMxDTALBglghkgBZQMEAgEwCwYJKoZIhvcNAQcBoIIGTDCCAyAwggIIoAMCAQICAQEwDQYJKoZIhvcNAQELBQAwKTETMBEGA1UEAwwKVGVzdCBEZWNveTESMBAGA1UECgwJRGVjb3kgT3JnMB4XDTI2MTExNjEzNDUwMFoXDTM2MTExMzEzNDUwMFowKTETMBEGA1UEAwwKVGVzdCBEZWNveTESMBAGA1UECgwJRGVjb3kgT3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjUAD2cCj+U5fdv1O0qfK5dkaAJIEdmlNu7Raq0dtUZdDVLjbF8ijzPVrPRgisMEyW6ClQdPMfBYfxUTiRQoLtiJEWCaVnSuEmfPw//Ap9Vo+WviOn0VLdhkWliPM4qzkPnhL1Hy7zFpjGcmxeKiyCQaCqrrVjbE14UdNDcnCxQRU3RWaqUyyTMZLpogcOGddCg8qOo6K1i5+FxnBhtCmAha2tqiP6lhCgDkiCRHP46AO8DUpr4Cqse5IMJmlsjvmEPHkNC6vUMuKRyl2D5odj17AqwXi5FcBHzsCM2Pi0i9Pr4dnjXXKapt1HI7SnukfkPNllA9iIKsA3J0D9oRhtwIDAQABo1MwUTAfBgNVHSMEGDAWgBSlf0Lsd206tScuEfAyh09TpOqwhzAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSlf0Lsd206tScuEfAyh09TpOqwhzANBgkqhkiG9w0BAQsFAAOCAQEAdizCkx+XbCGG7b0SkBartNmGJJE5AVCJc65AcR3lBWWnOjEpWfJda4gatEySD8JyHu2UQTxcIAUIUTVzL/dr6+C7WoXhjYaaBqS7NSp4tgCr9RPll9LCJHF2caW3q539EpabNETbqJERxyFei5Eqj2FJ5CFoxB9H5/AZXE2Yt9odjypM1qIoEEZBvXWlX9YaDN49QOyqgj0Wk3nN5C5XXc3aB4WKpsQCZ4Y8YcU1X+Z9v5NFvx7CtFfvcbmJUbmp9X32HtPfJe9oQ0zLA5juSCLVWmE3HWvcCD+XTv4qPJ1AyRE1gHATAxOo3PETVdtlkbu1/oZKvnvHqwNWLpkEtDCCAyQwggIMoAMCAQICAQEwDQYJKoZIhvcNAQELBQAwKzEUMBIGA1UEAwwLVGVzdCBTaWduZXIxEzARBgNVBAoMClNpZ25lciBPcmcwHhcNMjYxMTE2MTM0NTAwWhcNMzYxMTEzMTM0NTAwWjArMRQwEgYDVQQDDAtUZXN0IFNpZ25lcjETMBEGA1UECgwKU2lnbmVyIE9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMSTT+lVFn3CpkfMNeX1qmUpOznGTHWJJAHgHmc5loSFPMzwGwS/6+DvWVrMKJSKIJK1YsxOQP8m8L2JD1sbOzw0hAqII0Wz9sX5UvoHar1F17ceVSxUHxB2ufRYrvG+Rx8HcDzTbEDbEMygao65CW3UrE/I4JmK3aXeLKJEENyCOhRzIULqmoZqqbx7hGO8XLun37PHGt7aLMvVuLOe8gjhlZ+LjdZ22x4WiVHlIRMQERrZi4z4RiuJf244EL6UwQnz5yLttN8i/UX/uIGqjtHr+TvbzETePv/jMitoFQoReAEbV4DALIChoKKmhx7CBy9y+BRFg4o7+2mqArCm3qkCAwEAAaNTMFEwHwYDVR0jBBgwFoAUEXsrYDKzr60Ty7PR+iKTFpg+14AwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUEXsrYDKzr60Ty7PR+iKTFpg+14AwDQYJKoZIhvcNAQELBQADggEBAEYg+HCOBHEwimtyJdQxK9DGwQ2o9q2elUb+I3iSbG9deFvMUTubvZcCFokRVlDrlkMuIDi7qxEUmBWyRohpmX4ZwzjOIFbqvN58oFTJbDX2TzZEIXN29cjRJzwlClYmEs/XBc1n9FGdwo4WmlaRJH4NlIq/GwbR9wbvPzVGoxj3JYKHpSPsrqHspG+Yq9nKHIEFtue6rF1g5XZgNX0b8YvL71f9+nuAqomQYpvfVzqpywYqr36iv9OFcpBueTUrDss1S1vgiO0z2BMaOKKqEwLuYAPDhxCtVK09SyCXPafT1wHAiGHLjuG2YMlFS/yDbo0Tt194XZtAmvOTQe4cHH8xggIkMIICIAIBA4AUEXsrYDKzr60Ty7PR+iKTFpg+14AwCwYJYIZIAWUDBAIBoIHkMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTExNjEzNDUwMFowLwYJKoZIhvcNAQkEMSIEICzyTbpfsKMOJug7KsW54p4bFh5cH6dCXnMEM2KTi5gkMHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFlAwQBFjALBglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0GCCqGSIb3DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMA0GCSqGSIb3DQEBAQUABIIBAAjIT4wOMjiUT9BxQY0xbl4jzB/wV+tOMXttPODLsohbPaSr8jqZgHoMpTGb6fvsXA7KCm++pgxcftORpKAF2AsFHmN/udvek++kTasW6oBcCzXtzJJ7cVr28AknH2HSP4pfqa2BY/5RN00qITZIC5/66L1vFCjl2uNx35LZrs+ExohlpAXU3CeBIxz58Q6TIq3AQZ/H5KjXvlzZKq7j9AWRGvkFR2+RhNAKNZLWOSH4yPI+rYX/CZuf37vDXUv3BemCNJQsWL3ForZfGSdU/o9bRsB4ObCZ69ZK5PvclwDQPTy/sk2RgEoLIdqVGyAzzmaX03DOBi2dc93j11U+xcc=",+);++describe("CMS signer certificate", () => {+ it("names the certificate matching issuer and serial, not another with the same serial", () => {+ const facts = readCmsSignatureFacts(BY_SERIAL);+ expect(facts.signerName).toBe("Test Signer");+ expect(facts.digestAlgorithm).toBe("SHA-256");+ expect(facts.digest).toHaveLength(32);+ });++ it("names the certificate matching a subjectKeyIdentifier signer", () => {+ expect(readCmsSignatureFacts(BY_KEY_ID).signerName).toBe("Test Signer");+ });++ it("gives no name when no embedded certificate matches", () => {+ const tampered = BY_SERIAL.slice();+ const serial = [0x02, 0x01, 0x01];+ let at = tampered.length - serial.length;+ while (at >= 0 && !serial.every((b, j) => tampered[at + j] === b)) at--;+ tampered[at + 2] = 0x02;+ expect(readCmsSignatureFacts(tampered).signerName).toBeNull();+ });+});diff --git a/frontend/src/editor/core/utils/pdfSignatureCms.ts b/frontend/src/editor/core/utils/pdfSignatureCms.tsnew file mode 100644index 0000000000..365c89e2ec--- /dev/null+++ b/frontend/src/editor/core/utils/pdfSignatureCms.ts@@ -0,0 +1,240 @@+interface Tlv {+ tag: number;+ start: number;+ contentEnd: number;+ end: number;+}++export interface CmsSignatureFacts {+ signerName: string | null;+ digest: Uint8Array | null;+ digestAlgorithm: AlgorithmIdentifier | null;+}++const OID_COMMON_NAME = "2.5.4.3";+const OID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4";+const OID_TIMESTAMP_TOKEN_INFO = "1.2.840.113549.1.9.16.1.4";+const OID_SUBJECT_KEY_IDENTIFIER = "2.5.29.14";+const DIGEST_BY_OID: Record<string, AlgorithmIdentifier> = {+ "1.3.14.3.2.26": "SHA-1",+ "2.16.840.1.101.3.4.2.1": "SHA-256",+ "2.16.840.1.101.3.4.2.2": "SHA-384",+ "2.16.840.1.101.3.4.2.3": "SHA-512",+};++function digestAlgorithm(+ bytes: Uint8Array,+ identifier: Tlv | undefined,+): AlgorithmIdentifier | null {+ const type = identifier && children(bytes, identifier)[0];+ return type?.tag === 0x06 ? (DIGEST_BY_OID[oid(bytes, type)] ?? null) : null;+}++function readTlv(+ bytes: Uint8Array,+ offset: number,+ limit = bytes.length,+ depth = 0,+): Tlv | null {+ if (offset + 2 > limit || depth > 32) return null;+ const tag = bytes[offset];+ let length = bytes[offset + 1];+ let start = offset + 2;+ if (length === 0x80) {+ let cursor = start;+ while (+ cursor + 2 <= limit &&+ !(bytes[cursor] === 0 && bytes[cursor + 1] === 0)+ ) {+ const child = readTlv(bytes, cursor, limit, depth + 1);+ if (!child) return null;+ cursor = child.end;+ }+ return cursor + 2 > limit+ ? null+ : { tag, start, contentEnd: cursor, end: cursor + 2 };+ }+ if (length & 0x80) {+ const count = length & 0x7f;+ if (count > 4 || start + count > limit) return null;+ length = 0;+ for (let i = 0; i < count; i++) length = length * 256 + bytes[start + i];+ start += count;+ }+ const end = start + length;+ return end > limit ? null : { tag, start, contentEnd: end, end };+}++function children(bytes: Uint8Array, parent: Tlv): Tlv[] {+ const out: Tlv[] = [];+ let offset = parent.start;+ while (offset < parent.contentEnd) {+ const child = readTlv(bytes, offset, parent.contentEnd);+ if (!child) break;+ out.push(child);+ offset = child.end;+ }+ return out;+}++function oid(bytes: Uint8Array, node: Tlv): string {+ const parts: number[] = [];+ let value = 0;+ for (let i = node.start; i < node.contentEnd; i++) {+ value = value * 128 + (bytes[i] & 0x7f);+ if (!(bytes[i] & 0x80)) {+ if (parts.length === 0)+ parts.push(+ value < 80 ? Math.floor(value / 40) : 2,+ value < 80 ? value % 40 : value - 80,+ );+ else parts.push(value);+ value = 0;+ }+ }+ return parts.join(".");+}++function sameBytes(bytes: Uint8Array, a: Tlv, b: Tlv): boolean {+ if (a.contentEnd - a.start !== b.contentEnd - b.start) return false;+ for (let i = 0; i < a.contentEnd - a.start; i++)+ if (bytes[a.start + i] !== bytes[b.start + i]) return false;+ return true;+}++function commonName(bytes: Uint8Array, name: Tlv): string | null {+ let found: string | null = null;+ for (const rdn of children(bytes, name))+ for (const attribute of children(bytes, rdn)) {+ const [type, value] = children(bytes, attribute);+ if (type?.tag === 0x06 && value && oid(bytes, type) === OID_COMMON_NAME)+ found = new TextDecoder().decode(+ bytes.subarray(value.start, value.contentEnd),+ );+ }+ return found;+}++function certificateIdentity(bytes: Uint8Array, certificate: Tlv) {+ const [tbs] = children(bytes, certificate);+ if (!tbs) return null;+ const fields = children(bytes, tbs);+ const offset = fields[0]?.tag === 0xa0 ? 1 : 0;+ const serial = fields[offset];+ const issuer = fields[offset + 2];+ const subject = fields[offset + 4];+ const extensions = fields.find((field) => field.tag === 0xa3);+ return serial && issuer && subject+ ? {+ serial,+ issuer,+ subject,+ keyIdentifier: extensions+ ? subjectKeyIdentifier(bytes, extensions)+ : null,+ }+ : null;+}++function subjectKeyIdentifier(bytes: Uint8Array, extensions: Tlv): Tlv | null {+ const list = children(bytes, extensions)[0];+ for (const extension of list ? children(bytes, list) : []) {+ const parts = children(bytes, extension);+ const value = parts.at(-1);+ if (+ parts[0]?.tag === 0x06 &&+ oid(bytes, parts[0]) === OID_SUBJECT_KEY_IDENTIFIER &&+ value?.tag === 0x04+ ) {+ const inner = readTlv(bytes, value.start, value.contentEnd);+ return inner?.tag === 0x04 ? inner : null;+ }+ }+ return null;+}++function attributeValue(+ bytes: Uint8Array,+ attributes: Tlv,+ wanted: string,+): Tlv | null {+ for (const attribute of children(bytes, attributes)) {+ const [type, values] = children(bytes, attribute);+ if (type?.tag === 0x06 && values && oid(bytes, type) === wanted)+ return children(bytes, values)[0] ?? null;+ }+ return null;+}++function timestampImprint(+ bytes: Uint8Array,+ encapsulated: Tlv,+): { digest: Uint8Array; algorithm: AlgorithmIdentifier | null } | null {+ const [type, explicit] = children(bytes, encapsulated);+ if (!type || oid(bytes, type) !== OID_TIMESTAMP_TOKEN_INFO || !explicit)+ return null;+ const octets = children(bytes, explicit)[0];+ const info = octets && readTlv(bytes, octets.start, octets.contentEnd);+ const imprint = info && children(bytes, info)[2];+ const [hashAlgorithm, hashed] = imprint ? children(bytes, imprint) : [];+ return hashed?.tag === 0x04+ ? {+ digest: bytes.slice(hashed.start, hashed.contentEnd),+ algorithm: digestAlgorithm(bytes, hashAlgorithm),+ }+ : null;+}++export function readCmsSignatureFacts(contents: Uint8Array): CmsSignatureFacts {+ const none = { signerName: null, digest: null, digestAlgorithm: null };+ const contentInfo = readTlv(contents, 0);+ const signedDataWrapper = contentInfo && children(contents, contentInfo)[1];+ const signedData =+ signedDataWrapper && children(contents, signedDataWrapper)[0];+ if (!signedData) return none;+ const fields = children(contents, signedData);+ const certificates = fields.find((f) => f.tag === 0xa0);+ const signerInfos = fields.filter((f) => f.tag === 0x31).at(-1);+ const signerInfo = signerInfos && children(contents, signerInfos)[0];+ if (!signerInfo) return none;+ const [, sid, signerDigestAlgorithm, signedAttributes] = children(+ contents,+ signerInfo,+ );+ const [sidIssuer, sidSerial] =+ sid?.tag === 0x30 ? children(contents, sid) : [];+ const sidKeyIdentifier = sid?.tag === 0x80 ? sid : undefined;+ const signerCert = certificates+ ? children(contents, certificates)+ .map((c) => certificateIdentity(contents, c))+ .find((c) =>+ !c+ ? false+ : sidKeyIdentifier+ ? !!c.keyIdentifier &&+ sameBytes(contents, c.keyIdentifier, sidKeyIdentifier)+ : !!sidIssuer &&+ !!sidSerial &&+ sameBytes(contents, c.serial, sidSerial) &&+ sameBytes(contents, c.issuer, sidIssuer),+ )+ : undefined;+ const imprint = fields[2] ? timestampImprint(contents, fields[2]) : null;+ const digestNode =+ signedAttributes?.tag === 0xa0+ ? attributeValue(contents, signedAttributes, OID_MESSAGE_DIGEST)+ : null;+ const signed =+ digestNode?.tag === 0x04+ ? {+ digest: contents.slice(digestNode.start, digestNode.contentEnd),+ algorithm: digestAlgorithm(contents, signerDigestAlgorithm),+ }+ : null;+ const found = imprint ?? signed;+ return {+ signerName: signerCert ? commonName(contents, signerCert.subject) : null,+ digest: found?.digest ?? null,+ digestAlgorithm: found?.algorithm ?? null,+ };+}diff --git a/frontend/src/editor/core/utils/pdfiumAccess.test.ts b/frontend/src/editor/core/utils/pdfiumAccess.test.tsindex e9fb5f092d..7f12b6f2fd 100644--- a/frontend/src/editor/core/utils/pdfiumAccess.test.ts+++ b/frontend/src/editor/core/utils/pdfiumAccess.test.ts@@ -9,6 +9,7 @@ function moduleFor(owner = false,revision = 6,signatures = 0,+ signatureBytes = 64,) {return {EPDF_IsEncrypted: () => true,@@ -16,6 +17,8 @@ function moduleFor(FPDF_GetDocUserPermissions: () => permissions,FPDF_GetSecurityHandlerRevision: () => revision,FPDF_GetSignatureCount: () => signatures,+ FPDF_GetSignatureObject: (_document: number, index: number) => index,+ FPDFSignatureObj_GetContents: () => signatureBytes,FPDF_GetPageCount: () => 3,} as unknown as WrappedPdfiumModule;}@@ -63,4 +66,10 @@ describe("PDFium access decisions", () => {readPdfiumAccess(moduleFor(-4, false, 6, -1), 1, "reader"),).toThrow("verify PDF security");});++ it("does not count an empty signature field as a signature", () => {+ expect(+ readPdfiumAccess(moduleFor(-4, false, 6, 1, 0), 1, "reader").signed,+ ).toBe(false);+ });});diff --git a/frontend/src/editor/core/utils/pdfiumAccess.ts b/frontend/src/editor/core/utils/pdfiumAccess.tsindex 6c564b149f..e894963fde 100644--- a/frontend/src/editor/core/utils/pdfiumAccess.ts+++ b/frontend/src/editor/core/utils/pdfiumAccess.ts@@ -1,5 +1,6 @@import type { WrappedPdfiumModule } from "@embedpdf/pdfium";import type { PdfAccess } from "@editor/services/pdfAccessService";+import { countPdfiumSignatures } from "@editor/utils/pdfiumSignatures";/** Reads the authenticated document without reopening it or changing its protection. */export function readPdfiumAccess(@@ -11,7 +12,7 @@ export function readPdfiumAccess(const ownerAuthenticated = encrypted && module.EPDF_IsOwnerUnlocked(document);const permissions = module.FPDF_GetDocUserPermissions(document);const encryptionRevision = module.FPDF_GetSecurityHandlerRevision(document);- const signatureCount = module.FPDF_GetSignatureCount(document);+ const signatureCount = countPdfiumSignatures(module, document);if (!Number.isInteger(permissions) ||signatureCount < 0 ||diff --git a/frontend/src/editor/core/utils/pdfiumSignatures.test.ts b/frontend/src/editor/core/utils/pdfiumSignatures.test.tsnew file mode 100644index 0000000000..290da87812--- /dev/null+++ b/frontend/src/editor/core/utils/pdfiumSignatures.test.ts@@ -0,0 +1,117 @@+// @vitest-environment node+import fs from "node:fs";+import path from "node:path";+import { webcrypto } from "node:crypto";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { init, type WrappedPdfiumModule } from "@embedpdf/pdfium";+import { readPdfiumAccess } from "@editor/utils/pdfiumAccess";+import { readPdfiumSignatures } from "@editor/utils/pdfiumSignatures";++const FIXTURES = path.join(import.meta.dirname, "../tests/test-fixtures");+let pdfium: WrappedPdfiumModule;++beforeAll(async () => {+ vi.stubGlobal("crypto", webcrypto);+ const wasm = fs.readFileSync(+ path.join(process.cwd(), "node_modules/@embedpdf/pdfium/dist/pdfium.wasm"),+ );+ pdfium = await init({+ wasmBinary: wasm.buffer.slice(+ wasm.byteOffset,+ wasm.byteOffset + wasm.byteLength,+ ),+ });+ pdfium.PDFiumExt_Init();+});++afterAll(() => {+ vi.unstubAllGlobals();+});++async function probe(name: string) {+ const bytes = fs.readFileSync(path.join(FIXTURES, name));+ const pointer = pdfium.pdfium.wasmExports.malloc(bytes.length);+ (pdfium.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8.set(+ bytes,+ pointer,+ );+ const document = pdfium.FPDF_LoadMemDocument(pointer, bytes.length, "");+ try {+ const signatures = await readPdfiumSignatures(pdfium, document, {+ pointer,+ length: bytes.length,+ });+ const heap = (pdfium.pdfium as unknown as { HEAPU8: Uint8Array }).HEAPU8;+ expect(+ Buffer.from(heap.subarray(pointer, pointer + bytes.length)).equals(bytes),+ ).toBe(true);+ return {+ signed: readPdfiumAccess(pdfium, document, "").signed,+ signatures,+ };+ } finally {+ pdfium.FPDF_CloseDocument(document);+ pdfium.pdfium.wasmExports.free(pointer);+ }+}++describe("local signature probe", () => {+ it("reads the signer and confirms an untouched signature", async () => {+ const { signed, signatures } = await probe("signature-one.pdf");+ expect(signed).toBe(true);+ expect(signatures).toEqual([+ expect.objectContaining({+ signerName: "Test Signer",+ reason: "Approved",+ subFilter: "adbe.pkcs7.detached",+ certificationLevel: 0,+ coversWholeFile: true,+ digestMatches: true,+ }),+ ]);+ expect(signatures[0].signedAt).toMatch(/^D:\d{14}/);+ });++ it("keeps an earlier signature intact when a later one countersigns", async () => {+ const { signatures } = await probe("signature-two.pdf");+ expect(+ signatures.map((s) => [s.reason, s.coversWholeFile, s.digestMatches]),+ ).toEqual([+ ["Approved", false, true],+ ["Countersigned", true, true],+ ]);+ });++ it("shows content added after signing without breaking the signature", async () => {+ const [signature] = (await probe("signature-changed-after.pdf")).signatures;+ expect(signature).toMatchObject({+ coversWholeFile: false,+ digestMatches: true,+ });+ });++ it("reports a signature whose bytes no longer match the file", async () => {+ const [signature] = (await probe("signature-rewritten.pdf")).signatures;+ expect(signature).toMatchObject({+ signerName: "Test Signer",+ digestMatches: false,+ });+ });++ it("checks a document timestamp against its message imprint", async () => {+ const [signature] = (await probe("signature-timestamp.pdf")).signatures;+ expect(signature).toMatchObject({+ subFilter: "ETSI.RFC3161",+ coversWholeFile: true,+ digestMatches: true,+ });+ expect(signature.signerName).toMatch(/Timestamp/);+ });++ it("treats an empty signature field as unsigned", async () => {+ expect(await probe("signature-empty-field.pdf")).toEqual({+ signed: false,+ signatures: [],+ });+ });+});diff --git a/frontend/src/editor/core/utils/pdfiumSignatures.ts b/frontend/src/editor/core/utils/pdfiumSignatures.tsnew file mode 100644index 0000000000..e106a31e8a--- /dev/null+++ b/frontend/src/editor/core/utils/pdfiumSignatures.ts@@ -0,0 +1,173 @@+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import { readCmsSignatureFacts } from "@editor/utils/pdfSignatureCms";++export interface PdfSignatureInfo {+ signerName: string | null;+ signedAt: string | null;+ reason: string | null;+ subFilter: string | null;+ certificationLevel: number;+ coversWholeFile: boolean;+ digestMatches: boolean | null;+}++function heap(module: WrappedPdfiumModule): Uint8Array<ArrayBuffer> {+ return (+ module.pdfium as typeof module.pdfium & {+ HEAPU8: Uint8Array<ArrayBuffer>;+ }+ ).HEAPU8;+}++function readBuffer(+ module: WrappedPdfiumModule,+ read: (signature: number, buffer: number, length: number) => number,+ signature: number,+): Uint8Array {+ const length = read(signature, 0, 0);+ if (length <= 0) return new Uint8Array();+ const pointer = module.pdfium.wasmExports.malloc(length);+ if (!pointer) return new Uint8Array();+ try {+ read(signature, pointer, length);+ return heap(module).slice(pointer, pointer + length);+ } finally {+ module.pdfium.wasmExports.free(pointer);+ }+}++function text(+ bytes: Uint8Array,+ encoding: "utf-16le" | "latin1",+): string | null {+ const value = new TextDecoder(encoding).decode(bytes).replace(/\0+$/, "");+ return value === "" ? null : value;+}++export function countPdfiumSignatures(+ module: WrappedPdfiumModule,+ document: number,+): number {+ const total = module.FPDF_GetSignatureCount(document);+ if (total < 0) return total;+ let signed = 0;+ for (let i = 0; i < total; i++)+ if (+ module.FPDFSignatureObj_GetContents(+ module.FPDF_GetSignatureObject(document, i),+ 0,+ 0,+ ) > 0+ )+ signed++;+ return signed;+}++function byteRange(module: WrappedPdfiumModule, signature: number): number[] {+ const count = module.FPDFSignatureObj_GetByteRange(signature, 0, 0);+ if (count !== 4) return [];+ const pointer = module.pdfium.wasmExports.malloc(count * 4);+ if (!pointer) return [];+ try {+ module.FPDFSignatureObj_GetByteRange(signature, pointer, count);+ return Array.from(new Int32Array(heap(module).buffer, pointer, count));+ } finally {+ module.pdfium.wasmExports.free(pointer);+ }+}++async function digestMatches(+ module: WrappedPdfiumModule,+ file: { pointer: number; length: number },+ range: number[],+ expected: Uint8Array | null,+ algorithm: AlgorithmIdentifier | null,+): Promise<boolean | null> {+ if (!expected || !algorithm || range.length !== 4) return null;+ const [start, firstLength, secondStart, secondLength] = range;+ if (+ range.some((n) => n < 0) ||+ start + firstLength > secondStart ||+ secondStart + secondLength > file.length+ )+ return false;+ const bytes = heap(module);+ const first = file.pointer + start;+ const gapStart = first + firstLength;+ const second = file.pointer + secondStart;+ const gap = bytes.slice(gapStart, second);+ bytes.copyWithin(gapStart, second, second + secondLength);+ try {+ const actual = new Uint8Array(+ await crypto.subtle.digest(+ algorithm,+ bytes.subarray(first, gapStart + secondLength),+ ),+ );+ return actual.every((value, i) => value === expected[i]);+ } finally {+ bytes.copyWithin(second, gapStart, gapStart + secondLength);+ bytes.set(gap, gapStart);+ }+}++export async function readPdfiumSignatures(+ module: WrappedPdfiumModule,+ document: number,+ file: { pointer: number; length: number },+): Promise<PdfSignatureInfo[]> {+ const read: {+ info: PdfSignatureInfo;+ range: number[];+ digest: Uint8Array | null;+ digestAlgorithm: AlgorithmIdentifier | null;+ }[] = [];+ const total = module.FPDF_GetSignatureCount(document);+ for (let i = 0; i < total; i++) {+ const signature = module.FPDF_GetSignatureObject(document, i);+ const contents = readBuffer(+ module,+ module.FPDFSignatureObj_GetContents,+ signature,+ );+ if (contents.length === 0) continue;+ const range = byteRange(module, signature);+ const facts = readCmsSignatureFacts(contents);+ const subFilter = text(+ readBuffer(module, module.FPDFSignatureObj_GetSubFilter, signature),+ "latin1",+ );+ const encapsulatesDigest = subFilter === "adbe.pkcs7.sha1";+ read.push({+ range,+ digest: encapsulatesDigest ? null : facts.digest,+ digestAlgorithm: facts.digestAlgorithm,+ info: {+ signerName: facts.signerName,+ signedAt: text(+ readBuffer(module, module.FPDFSignatureObj_GetTime, signature),+ "latin1",+ ),+ reason: text(+ readBuffer(module, module.FPDFSignatureObj_GetReason, signature),+ "utf-16le",+ ),+ subFilter,+ certificationLevel:+ module.FPDFSignatureObj_GetDocMDPPermission(signature),+ coversWholeFile:+ range.length === 4 && range[2] + range[3] === file.length,+ digestMatches: null,+ },+ });+ }+ for (const entry of read)+ entry.info.digestMatches = await digestMatches(+ module,+ file,+ entry.range,+ entry.digest,+ entry.digestAlgorithm,+ ).catch(() => null);+ return read.map((entry) => entry.info);+}diff --git a/frontend/src/editor/core/utils/toolIOCompat.ts b/frontend/src/editor/core/utils/toolIOCompat.tsindex eb46341185..970f50276b 100644--- a/frontend/src/editor/core/utils/toolIOCompat.ts+++ b/frontend/src/editor/core/utils/toolIOCompat.ts@@ -17,7 +17,10 @@ import {import { detectFileExtension, getFileFormats } from "@editor/utils/fileUtils";import type { StirlingFileStub } from "@editor/types/fileContext";import { getPdfAccess } from "@editor/services/pdfAccessService";-import { supportsSessionUnlock } from "@editor/services/pdfSessionUnlock";+import {+ signedPdfEditRefused,+ supportsSessionUnlock,+} from "@editor/services/pdfSessionUnlock";export type ToolDiagnosticSeverity = "ERROR" | "WARN" | "INFO";@@ -264,8 +267,8 @@ export function toolAcceptsFormat(}/**- * Uses detected encryption and endpoint input restrictions. Encrypted PDFs require declared support;- * undeclared endpoints keep their own validation for other inputs.+ * Uses detected encryption, the signed-PDF edit policy and endpoint input restrictions. Encrypted PDFs+ * require declared support; undeclared endpoints keep their own validation for other inputs.*/export function toolAcceptsFile(operation: string | undefined,@@ -273,6 +276,7 @@ export function toolAcceptsFile(id?: string;},): boolean {+ if (signedPdfEditRefused(getPdfAccess(file.id), operation)) return false;const spec = operation ? toolIOFor(operation) : undefined;const formats =getPdfAccess(file.id) && supportsSessionUnlock(operation)diff --git a/frontend/src/editor/core/workers/pdfAccessWorker.test.ts b/frontend/src/editor/core/workers/pdfAccessWorker.test.tsindex 242899bea5..b6180f7358 100644--- a/frontend/src/editor/core/workers/pdfAccessWorker.test.ts+++ b/frontend/src/editor/core/workers/pdfAccessWorker.test.ts@@ -4,8 +4,13 @@ import type { PdfAccessRequest } from "@editor/workers/pdfAccessWorker";const init = vi.hoisted(() => vi.fn());vi.mock("@embedpdf/pdfium", () => ({ init }));-vi.mock("@editor/utils/pdfiumAccess", () => ({- readPdfiumAccess: () => ({ encrypted: false }),+const readAccess = vi.hoisted(() => vi.fn(() => ({ encrypted: false })));+const readSignatures = vi.hoisted(() =>+ vi.fn(async () => [{ signerName: "Test Signer" }]),+);+vi.mock("@editor/utils/pdfiumAccess", () => ({ readPdfiumAccess: readAccess }));+vi.mock("@editor/utils/pdfiumSignatures", () => ({+ readPdfiumSignatures: readSignatures,}));const scope = {@@ -26,6 +31,7 @@ const ready = {const request: PdfAccessRequest = {file: new Blob(["PDF"]),password: "",+ runBackgroundChecks: true,wasmUrl: "/pdfium.wasm",wasmModule: new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]),@@ -55,6 +61,7 @@ it("instantiates the shared module without fetching WASM again", async () => {expect(fetch).not.toHaveBeenCalled();expect(scope.postMessage).toHaveBeenCalledWith({access: { encrypted: false },+ background: false,});expect(ready.pdfium.wasmExports.free).toHaveBeenCalledWith(1);});@@ -88,5 +95,53 @@ it("falls back to the WASM asset when compilation is unavailable", async () => {expect(init).toHaveBeenCalledExactlyOnceWith({ wasmBinary: bytes });expect(scope.postMessage).toHaveBeenCalledWith({access: { encrypted: false },+ background: false,});});++it("runs the signature check in the background after the blocking answer for a signed file", async () => {+ init.mockResolvedValue(ready);+ readAccess.mockReturnValueOnce({ encrypted: false, signed: true } as never);+ await scope.onmessage!({ data: request });+ expect(+ scope.postMessage.mock.calls.map(([message]) => Object.keys(message)),+ ).toEqual([["access", "background"], ["details"], ["done"]]);+ expect(scope.postMessage.mock.calls[1][0]).toEqual({+ details: { signatures: [{ signerName: "Test Signer" }] },+ });+ expect(readSignatures).toHaveBeenCalledWith(ready, 1, {+ pointer: 1,+ length: 3,+ });+});++it("skips background checks when the request does not ask for them", async () => {+ init.mockResolvedValue(ready);+ readAccess.mockReturnValueOnce({ encrypted: false, signed: true } as never);+ await scope.onmessage!({ data: { ...request, runBackgroundChecks: false } });+ expect(scope.postMessage.mock.calls.map(([message]) => message)).toEqual([+ { access: { encrypted: false, signed: true }, background: false },+ ]);+ expect(readSignatures).not.toHaveBeenCalled();+});++it("still finishes when a background check fails", async () => {+ init.mockResolvedValue(ready);+ readAccess.mockReturnValueOnce({ encrypted: false, signed: true } as never);+ readSignatures.mockRejectedValueOnce(new Error("Malformed signature"));+ await scope.onmessage!({ data: request });+ expect(scope.postMessage.mock.calls.map(([message]) => message)).toEqual([+ { access: { encrypted: false, signed: true }, background: true },+ { done: true },+ ]);+ expect(ready.pdfium.wasmExports.free).toHaveBeenCalledWith(1);+});++it("initialises PDFium once for consecutive files and wipes each file before freeing it", async () => {+ init.mockResolvedValue(ready);+ await scope.onmessage!({ data: request });+ await scope.onmessage!({ data: { ...request, file: new Blob(["XYZ"]) } });+ expect(init).toHaveBeenCalledOnce();+ expect(Array.from(ready.pdfium.HEAPU8.subarray(1, 4))).toEqual([0, 0, 0]);+ expect(ready.pdfium.wasmExports.free).toHaveBeenCalledTimes(2);+});diff --git a/frontend/src/editor/core/workers/pdfAccessWorker.ts b/frontend/src/editor/core/workers/pdfAccessWorker.tsindex a993cb12d1..dafe2d0470 100644--- a/frontend/src/editor/core/workers/pdfAccessWorker.ts+++ b/frontend/src/editor/core/workers/pdfAccessWorker.ts@@ -1,61 +1,145 @@-import { init, type PdfiumModule } from "@embedpdf/pdfium";+/**+ * The local PDF probe: one PDFium read of a file's bytes that answers every local check, so callers+ * never parse the same file twice. Scheduled, cached and cancelled by `services/pdfAccessService.ts`;+ * the checks themselves, and which phase each belongs to, are defined in `utils/pdfProbeChecks.ts`.+ *+ * Replies, in order: `access` (the blocking answer, saying whether background checks follow), one+ * `details` per background check that succeeds, then `done`.+ *+ * Local signature results are integrity evidence, not identity: the signature value and certificate+ * chain are never verified here, so whether the signer is trusted needs the backend.+ * Background checks run only when the request asks for them. Hashing every signed byte grows with+ * file size: for a file too large to reuse its worker, the queue slot is freed as soon as `access` is+ * sent, and its bytes still count against the memory budget until `done`.+ *+ * Workers are reused only after small unencrypted files, because WASM memory never shrinks and freed+ * pages keep their contents; every other file gets a fresh worker, and a clean spare is started for the next.+ *+ * Other reads of the same bytes that belong in this probe, each a separate parse today:+ * - `components/viewer/pdfViewerAccess.ts` reads `signed` again from the viewer's own PDFium document.+ * - `services/fileAnalyzer.ts` opens the file with PDF.js for the page count and encryption.+ * - `utils/pdfEncryptionProbe.ts` scans the trailer for an encryption hint on upload.+ * Files are probed on first use (viewer open, tool preflight), so a tool can accept a signed file+ * that has not been opened yet and refuse it only at Run. Probing each PDF when it is added closes+ * that gap; it needs a size cap, since the whole file is copied into WASM memory.+ * Planned checks (metadata, images, JavaScript, attachments, form fields) go in `pdfProbeChecks.ts`+ * too, mirrored on the backend through JPDFium so both sides agree.+ */+import {+ init,+ type PdfiumModule,+ type WrappedPdfiumModule,+} from "@embedpdf/pdfium";import { readPdfiumAccess } from "@editor/utils/pdfiumAccess";+import {+ backgroundChecksAfter,+ runBackgroundCheck,+ type PdfProbeDetails,+} from "@editor/utils/pdfProbeChecks";import type { PdfAccess } from "@editor/services/pdfAccessService";-/** A worker owns one inspection; termination releases its entire WASM heap. */export interface PdfAccessRequest {file: Blob;password: string;+ runBackgroundChecks: boolean;+ wasmUrl: string;+ wasmModule: WebAssembly.Module | null;+}++export interface PdfAccessWarmup {+ warmup: true;wasmUrl: string;wasmModule: WebAssembly.Module | null;}export type PdfAccessResponse =- | { access: PdfAccess }+ | { access: PdfAccess; background: boolean }+ | { details: Partial<PdfProbeDetails> }+ | { done: true }| { error: string; code?: number };-self.onmessage = async ({ data }: MessageEvent<PdfAccessRequest>) => {+let pdfium: Promise<WrappedPdfiumModule> | undefined;++async function loadPdfium(+ request: PdfAccessRequest | PdfAccessWarmup,+): Promise<WrappedPdfiumModule> {+ let rejectInstantiation!: (error: unknown) => void;+ const instantiationFailed = new Promise<never>((_, reject) => {+ rejectInstantiation = reject;+ });+ const options: Partial<PdfiumModule> & {+ wasmBinary?: ArrayBuffer;+ instantiateWasm?: (+ imports: WebAssembly.Imports,+ ready: (+ instance: WebAssembly.Instance,+ module: WebAssembly.Module,+ ) => void,+ ) => void;+ } = {};+ const precompiled = request.wasmModule;+ if (precompiled) {+ options.instantiateWasm = (imports, ready) => {+ void WebAssembly.instantiate(precompiled, imports)+ .then((instance) => ready(instance, precompiled))+ .catch(rejectInstantiation);+ };+ } else {+ const response = await fetch(request.wasmUrl);+ if (!response.ok) throw new Error("Unable to load PDF security reader");+ options.wasmBinary = await response.arrayBuffer();+ }+ const module = await Promise.race([init(options), instantiationFailed]);+ module.PDFiumExt_Init();+ return module;+}++function heap(module: WrappedPdfiumModule): Uint8Array {+ return (module.pdfium as typeof module.pdfium & { HEAPU8: Uint8Array })+ .HEAPU8;+}++async function copyIntoHeap(+ module: WrappedPdfiumModule,+ file: Blob,+ pointer: number,+) {+ const reader = file.stream().getReader();+ let offset = pointer;+ for (+ let chunk = await reader.read();+ !chunk.done;+ chunk = await reader.read()+ ) {+ heap(module).set(chunk.value, offset);+ offset += chunk.value.length;+ }+}++self.onmessage = async ({+ data,+}: MessageEvent<PdfAccessRequest | PdfAccessWarmup>) => {+ if ("warmup" in data) {+ pdfium ??= loadPdfium(data);+ await pdfium.catch(() => {+ pdfium = undefined;+ });+ return;+ }try {- let rejectInstantiation!: (error: unknown) => void;- const instantiationFailed = new Promise<never>((_, reject) => {- rejectInstantiation = reject;+ pdfium ??= loadPdfium(data);+ const module = await pdfium.catch((error: unknown) => {+ pdfium = undefined;+ throw error;});- const options: Partial<PdfiumModule> & {- wasmBinary?: ArrayBuffer;- instantiateWasm?: (- imports: WebAssembly.Imports,- ready: (- instance: WebAssembly.Instance,- module: WebAssembly.Module,- ) => void,- ) => void;- } = {};- const precompiled = data.wasmModule;- if (precompiled) {- options.instantiateWasm = (imports, ready) => {- void WebAssembly.instantiate(precompiled, imports)- .then((instance) => ready(instance, precompiled))- .catch(rejectInstantiation);- };- } else {- const response = await fetch(data.wasmUrl);- if (!response.ok) throw new Error("Unable to load PDF security reader");- options.wasmBinary = await response.arrayBuffer();- }- const module = await Promise.race([init(options), instantiationFailed]);- module.PDFiumExt_Init();- const bytes = new Uint8Array(await data.file.arrayBuffer());- const pointer = module.pdfium.wasmExports.malloc(bytes.length);+ const length = data.file.size;+ const pointer = module.pdfium.wasmExports.malloc(Math.max(length, 1));if (!pointer) throw new Error("Unable to allocate memory for this PDF");try {- // malloc can grow WASM memory, so read its current view after allocation.- const runtime = module.pdfium as typeof module.pdfium & {- HEAPU8: Uint8Array;- };- runtime.HEAPU8.set(bytes, pointer);+ await copyIntoHeap(module, data.file, pointer);const document = module.FPDF_LoadMemDocument(pointer,- bytes.length,+ length,data.password,);if (!document) {@@ -68,17 +152,32 @@ self.onmessage = async ({ data }: MessageEvent<PdfAccessRequest>) => {try {const access = readPdfiumAccess(module, document, data.password);if (access.encrypted && data.password !== "") {- const empty = module.FPDF_LoadMemDocument(pointer, bytes.length, "");+ const empty = module.FPDF_LoadMemDocument(pointer, length, "");if (empty) module.FPDF_CloseDocument(empty);else if (module.FPDF_GetLastError() !== 4)throw new Error("Unable to verify the PDF opening password");access.requiresOpeningPassword = !empty;}- self.postMessage({ access } satisfies PdfAccessResponse);+ const background = data.runBackgroundChecks+ ? backgroundChecksAfter(access)+ : [];+ self.postMessage({+ access,+ background: background.length > 0,+ } satisfies PdfAccessResponse);+ if (background.length === 0) return;+ const pdf = { module, document, file: { pointer, length } };+ for (const key of background) {+ const details = await runBackgroundCheck(key, pdf).catch(() => null);+ if (details)+ self.postMessage({ details } satisfies PdfAccessResponse);+ }+ self.postMessage({ done: true } satisfies PdfAccessResponse);} finally {module.FPDF_CloseDocument(document);}} finally {+ heap(module).fill(0, pointer, pointer + length);module.pdfium.wasmExports.free(pointer);}} catch {diff --git a/frontend/src/editor/desktop/utils/automationExecutor.test.ts b/frontend/src/editor/desktop/utils/automationExecutor.test.tsindex 254aa557c7..79f43a6249 100644--- a/frontend/src/editor/desktop/utils/automationExecutor.test.ts+++ b/frontend/src/editor/desktop/utils/automationExecutor.test.ts@@ -23,10 +23,97 @@ vi.mock("@editor/services/serverPipeline", () => ({downloadServerPipelineOutput: mocks.download,}));import { executeAutomationSequence } from "@editor/utils/automationExecutor";+import {+ clearPdfAccess,+ rememberUnencryptedPdf,+ setSignedPdfEditPolicy,+} from "@editor/services/pdfAccessService";import { ToolType } from "@editor/hooks/tools/shared/useToolOperation";beforeEach(() => {vi.resetAllMocks();+ clearPdfAccess();+ setSignedPdfEditPolicy(false);+});++test("refuses a signed input before submitting a pipeline that rewrites it", async () => {+ setSignedPdfEditPolicy(true);+ const signed = new File(["signed"], "signed.pdf", {+ type: "application/pdf",+ });+ rememberUnencryptedPdf(signed, 1, true);+ const onStepError = vi.fn();+ const registry = {+ rotate: {+ operationConfig: {+ toolType: ToolType.singleFile,+ endpoint: "/api/v1/general/rotate-pdf",+ buildFormData: () => new FormData(),+ defaultParameters: {},+ },+ },+ } as unknown as ToolRegistry;+ await expect(+ executeAutomationSequence(+ {+ id: "auto",+ name: "Pipeline",+ operations: [{ operation: "rotate", parameters: {} }],+ createdAt: "",+ updatedAt: "",+ },+ [signed],+ registry,+ undefined,+ undefined,+ onStepError,+ ),+ ).rejects.toThrow("digitally signed");+ expect(mocks.submit).not.toHaveBeenCalled();+ expect(onStepError).toHaveBeenCalledOnce();+});++test("lets a signed input through a pipeline whose first step converts it away from PDF", async () => {+ setSignedPdfEditPolicy(true);+ const signed = new File(["signed"], "signed.pdf", {+ type: "application/pdf",+ });+ rememberUnencryptedPdf(signed, 1, true);+ const registry = {+ toImage: {+ operationConfig: {+ toolType: ToolType.singleFile,+ endpoint: "/api/v1/convert/pdf/img",+ buildFormData: () => new FormData(),+ defaultParameters: {},+ },+ },+ rotate: {+ operationConfig: {+ toolType: ToolType.singleFile,+ endpoint: "/api/v1/general/rotate-pdf",+ buildFormData: () => new FormData(),+ defaultParameters: {},+ },+ },+ } as unknown as ToolRegistry;+ mocks.submit.mockResolvedValue("run");+ mocks.wait.mockResolvedValue({ outputs: [] });+ await executeAutomationSequence(+ {+ id: "auto",+ name: "Pipeline",+ operations: [+ { operation: "toImage", parameters: {} },+ { operation: "rotate", parameters: {} },+ ],+ createdAt: "",+ updatedAt: "",+ },+ [signed],+ registry,+ );+ expect(mocks.submit).toHaveBeenCalledOnce();});test("sends locally supported tool steps together and never calls the local executor", async () => {const buildFormData = () => {diff --git a/frontend/src/editor/desktop/utils/automationExecutor.ts b/frontend/src/editor/desktop/utils/automationExecutor.tsindex 1ffe9a1eb0..74a22b9f4a 100644--- a/frontend/src/editor/desktop/utils/automationExecutor.ts+++ b/frontend/src/editor/desktop/utils/automationExecutor.ts@@ -14,6 +14,8 @@ import type { BackendPipelineStep } from "@editor/services/policyPipeline";import type { ToolId } from "@editor/types/toolId";import { ToolType } from "@editor/hooks/tools/shared/useToolOperation";import { objectToFormData } from "@editor/hooks/tools/shared/toolApiMapping";+import { assertSignedPdfsEditable } from "@editor/services/pdfSessionUnlock";+import { toolIOFor } from "@editor/types/toolIO";/** Desktop automation executes as one server pipeline, including locally available tools. */export const executeAutomationSequence: typeof CoreExecuteAutomationSequence =@@ -78,6 +80,11 @@ export const executeAutomationSequence: typeof CoreExecuteAutomationSequence =);let currentStep = -1;try {+ for (const step of steps) {+ await assertSignedPdfsEditable(files, step.operation, false);+ const produces = toolIOFor(step.operation)?.produces;+ if (produces !== "PDF" && produces !== "PDF_ENCRYPTED") break;+ }const runId = await submitServerPipeline(session,automation.name,diff --git a/frontend/src/editor/proprietary/components/chat/ChatContext.signedPdf.test.tsx b/frontend/src/editor/proprietary/components/chat/ChatContext.signedPdf.test.tsxnew file mode 100644index 0000000000..3911cc0912--- /dev/null+++ b/frontend/src/editor/proprietary/components/chat/ChatContext.signedPdf.test.tsx@@ -0,0 +1,155 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import apiClient from "@editor/services/apiClient";+import { createStirlingFile } from "@editor/types/fileContext";+import {+ clearPdfAccess,+ ensureLocalPdfAccess,+ rememberPdfAccess,+ setSignedPdfEditPolicy,+ type PdfAccess,+} from "@editor/services/pdfAccessService";+import { signedPdfEditsBlockedMessage } from "@editor/services/pdfSessionUnlock";+import { ChatProvider, useChat } from "@editor/components/chat/ChatContext";++const consumeFiles = vi.fn();+let chatMessages: string[] = [];+const signedAccess: PdfAccess = {+ password: "",+ encrypted: false,+ signed: true,+ ownerAuthenticated: false,+ permissions: -1,+ pageCount: 1,+};+const signed = createStirlingFile(+ new File(["%PDF-1.7"], "contract.pdf", { type: "application/pdf" }),+);++vi.mock("@editor/contexts/FileContext", () => ({+ useAllFiles: () => ({+ files: [signed],+ fileStubs: [{ id: signed.fileId, name: signed.name }],+ }),+ useFileActions: () => ({ actions: { consumeFiles, addFiles: vi.fn() } }),+}));+vi.mock("@editor/services/pdfAccessService", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@editor/services/pdfAccessService")+ >()),+ ensureLocalPdfAccess: vi.fn(),+}));+vi.mock("@editor/services/apiClient", () => ({ default: { get: vi.fn() } }));+vi.mock("@editor/contexts/file/fileActions", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@editor/contexts/file/fileActions")+ >()),+ generateProcessedFileMetadata: async () => undefined,+}));+vi.mock("@editor/services/aiBaseUrl", () => ({+ getAiBaseUrl: async () => "http://ai.test",+}));+vi.mock("@editor/services/apiClientSetup", () => ({+ getAuthHeaders: async () => ({}),+}));++function stream(...frames: Array<[string, unknown]>): Response {+ const body = frames+ .map(([event, data]) => `event:${event}\ndata:${JSON.stringify(data)}\n\n`)+ .join("");+ return new Response(new TextEncoder().encode(body));+}++const rotate = {+ phase: "executing_tool",+ timestamp: 1,+ tool: "/api/v1/general/rotate-pdf",+ stepIndex: 1,+ stepCount: 1,+};+const rotated = {+ outcome: "completed",+ summary: "Rotated.",+ resultFiles: [+ {+ fileId: "out-1",+ fileName: "contract.pdf",+ contentType: "application/pdf",+ sourceIndex: 0,+ },+ ],+};++async function send(response: Response) {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => response),+ );+ const { result } = renderHook(() => useChat(), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <ChatProvider>{children}</ChatProvider>+ ),+ });+ await act(() => result.current.sendMessage("rotate it"));+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ chatMessages = result.current.messages.map((m) => m.content);+ return result.current.messages.at(-1)?.content;+}++beforeEach(() => {+ vi.clearAllMocks();+ clearPdfAccess();+ setSignedPdfEditPolicy(true);+ rememberPdfAccess(signed, signedAccess);+});+afterEach(() => {+ setSignedPdfEditPolicy(false);+ vi.unstubAllGlobals();+});++describe("AI chat on a signed PDF while changes are blocked", () => {+ it("stops at the first step that would rewrite it and imports nothing", async () => {+ await expect(+ send(stream(["progress", rotate], ["result", rotated])),+ ).resolves.toBe(signedPdfEditsBlockedMessage());+ expect(+ chatMessages.filter((m) => m === signedPdfEditsBlockedMessage()),+ ).toHaveLength(1);+ expect(apiClient.get).not.toHaveBeenCalled();+ expect(consumeFiles).not.toHaveBeenCalled();+ });++ it("reads a file nobody has opened before importing what the chat produced", async () => {+ clearPdfAccess();+ vi.mocked(ensureLocalPdfAccess).mockResolvedValue(signedAccess);+ await expect(+ send(stream(["progress", rotate], ["result", rotated])),+ ).resolves.toBe(signedPdfEditsBlockedMessage());+ expect(ensureLocalPdfAccess).toHaveBeenCalledWith(+ signed,+ expect.any(AbortSignal),+ );+ expect(consumeFiles).not.toHaveBeenCalled();+ });++ it("still answers questions that change nothing", async () => {+ await expect(+ send(+ stream([+ "result",+ { outcome: "answer", answer: "It has five clauses." },+ ]),+ ),+ ).resolves.toContain("five clauses");+ });++ it("imports results normally while the setting is off", async () => {+ setSignedPdfEditPolicy(false);+ vi.mocked(apiClient.get).mockResolvedValue({+ data: new Blob(["%PDF-1.7 rotated"], { type: "application/pdf" }),+ });+ await send(stream(["progress", rotate], ["result", rotated]));+ await waitFor(() => expect(consumeFiles).toHaveBeenCalledOnce());+ });+});diff --git a/frontend/src/editor/proprietary/components/chat/ChatContext.tsx b/frontend/src/editor/proprietary/components/chat/ChatContext.tsxindex 3fbe648d4d..5963c749c9 100644--- a/frontend/src/editor/proprietary/components/chat/ChatContext.tsx+++ b/frontend/src/editor/proprietary/components/chat/ChatContext.tsx@@ -28,6 +28,13 @@ import {type StirlingFileStub,} from "@editor/types/fileContext";import type { ToolOperation } from "@editor/types/file";+import { getPdfAccess } from "@editor/services/pdfAccessService";+import {+ assertSignedPdfsEditable,+ SignedPdfEditsBlockedError,+ signedPdfEditRefused,+ signedPdfEditsBlockedMessage,+} from "@editor/services/pdfSessionUnlock";import { uploadSafeFormData } from "@editor/utils/inMemoryUpload";export enum ChatRole {@@ -328,6 +335,22 @@ interface ProgressEvent {engineDetail?: AnyEngineProgressDetail;}+/** Reads any source not read yet; true when a tool the run used would rewrite a signed source. */+async function rewroteSignedSource(+ sources: readonly File[],+ tools: readonly string[],+ signal: AbortSignal,+): Promise<boolean> {+ try {+ for (const tool of tools)+ await assertSignedPdfsEditable(sources, tool, false, signal);+ return false;+ } catch (error) {+ if (error instanceof SignedPdfEditsBlockedError) return true;+ throw error;+ }+}+async function consumeSSEStream(response: Response,handlers: {@@ -647,15 +670,88 @@ export function ChatProvider({ children }: { children: ReactNode }) {}let receivedResult = false;+ let handledResult: Promise<void> = Promise.resolve();const toolsUsed: string[] = [];+ let refused = false;+ const refuseSignedEdit = () => {+ refused = true;+ dispatch({+ type: "ADD_MESSAGE",+ message: {+ id: generateId(),+ role: ChatRole.ASSISTANT,+ content: signedPdfEditsBlockedMessage(),+ timestamp: Date.now(),+ },+ });+ };++ const showResult = (data: AiWorkflowResponse) => {+ // The agent's tool calls run server-side, so a usage-limit 402 surfaces here on the+ // result (not via the apiClient interceptor that pops the modal for direct calls).+ // Fire the matching modal and replace the raw "tool failed: 402…" reason with a+ // brief, non-alarming line.+ const localLimit = data.errorCode === "FREE_TIER_EXHAUSTED";+ const isLimit = localLimit || isPaygLimitCode(data.errorCode);+ if (localLimit) {+ reportFreeTierExhausted();+ } else if (isLimit) {+ dispatchPaygLimitReached(data.errorSubscribed ?? null);+ }+ const replyContent = isLimit+ ? t(+ "chat.responses.usage_limit_reached",+ "You've reached your usage limit. Check your plan options to keep going.",+ )+ : formatWorkflowResponse(data, t);+ dispatch({+ type: "ADD_MESSAGE",+ message: {+ id: generateId(),+ role: ChatRole.ASSISTANT,+ content: replyContent,+ timestamp: Date.now(),+ toolsUsed: toolsUsed.length > 0 ? toolsUsed : undefined,+ progressLog:+ progressLogLocal.length > 0 ? [...progressLogLocal] : undefined,+ durationMs: Date.now() - startTime,+ },+ });+ if (data.fileId || data.resultFiles?.length) {+ importResultFile(data, sourceStubs).catch((err) => {+ console.error("Failed to import AI result file", err);+ dispatch({+ type: "ADD_MESSAGE",+ message: {+ id: generateId(),+ role: ChatRole.ASSISTANT,+ content: "The file was processed but I couldn't download it.",+ timestamp: Date.now(),+ },+ });+ });+ }+ };await consumeSSEStream(response, {onProgress: (data) => {+ if (refused) return;if (data.phase === AiWorkflowPhase.EXECUTING_TOOL &&typeof data.tool === "string") {- toolsUsed.push(data.tool);+ const tool = data.tool;+ toolsUsed.push(tool);+ if (+ sourceFiles.some((file) =>+ signedPdfEditRefused(getPdfAccess(file), tool),+ )+ ) {+ dispatch({ type: "SET_PROGRESS", progress: null });+ refuseSignedEdit();+ controller.abort();+ return;+ }}const progressItem: AiWorkflowProgress = {phase: data.phase as AiWorkflowPhase,@@ -669,54 +765,18 @@ export function ChatProvider({ children }: { children: ReactNode }) {},onResult: (data) => {receivedResult = true;+ if (refused) return;dispatch({ type: "SET_PROGRESS", progress: null });- // The agent's tool calls run server-side, so a usage-limit 402 surfaces here on the- // result (not via the apiClient interceptor that pops the modal for direct calls).- // Fire the matching modal and replace the raw "tool failed: 402…" reason with a- // brief, non-alarming line.- const localLimit = data.errorCode === "FREE_TIER_EXHAUSTED";- const isLimit = localLimit || isPaygLimitCode(data.errorCode);- if (localLimit) {- reportFreeTierExhausted();- } else if (isLimit) {- dispatchPaygLimitReached(data.errorSubscribed ?? null);- }- const replyContent = isLimit- ? t(- "chat.responses.usage_limit_reached",- "You've reached your usage limit. Check your plan options to keep going.",- )- : formatWorkflowResponse(data, t);- dispatch({- type: "ADD_MESSAGE",- message: {- id: generateId(),- role: ChatRole.ASSISTANT,- content: replyContent,- timestamp: Date.now(),- toolsUsed: toolsUsed.length > 0 ? toolsUsed : undefined,- progressLog:- progressLogLocal.length > 0- ? [...progressLogLocal]- : undefined,- durationMs: Date.now() - startTime,- },+ handledResult = rewroteSignedSource(+ sourceFiles,+ toolsUsed,+ controller.signal,+ ).then((refused) => {+ if (controller.signal.aborted || abortRef.current !== controller)+ return;+ if (refused) refuseSignedEdit();+ else showResult(data);});- if (data.fileId || data.resultFiles?.length) {- importResultFile(data, sourceStubs).catch((err) => {- console.error("Failed to import AI result file", err);- dispatch({- type: "ADD_MESSAGE",- message: {- id: generateId(),- role: ChatRole.ASSISTANT,- content:- "The file was processed but I couldn't download it.",- timestamp: Date.now(),- },- });- });- }},onError: (data) => {receivedResult = true;@@ -733,6 +793,7 @@ export function ChatProvider({ children }: { children: ReactNode }) {},});+ await handledResult;if (!receivedResult) {throw new Error("Stream ended without a result");}diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx b/frontend/src/editor/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsxindex 92364e5acd..80624ebd2c 100644--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/AdminSecurityPage.tsx@@ -189,6 +189,25 @@ export default function AdminSecurityPage() {})}/>+ <SettingsToggleRow+ label={t(+ "admin.settings.security.blockSignedPdfEdits.label",+ "Block changes to signed PDFs",+ )}+ info={t(+ "admin.settings.security.blockSignedPdfEdits.description",+ "Signed PDFs can still be viewed, printed, converted or signed again, but not changed in the app. API calls and server pipelines are not affected.",+ )}+ pending={security.isFieldPending("blockSignedPdfEdits")}+ checked={security.settings?.blockSignedPdfEdits ?? false}+ disabled={!loginEnabled}+ onChange={(checked) =>+ security.setSettings({+ ...security.settings,+ blockSignedPdfEdits: checked,+ })+ }+ /></SettingsCard><SettingsCardid="securityAuthentication"diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.tsindex fd058e74ab..34a883bb9c 100644--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts@@ -76,6 +76,7 @@ export function saveSecuritySettings(const deltaSettings: Record<string, unknown> = {"security.enableLogin": securitySettings.enableLogin,"security.honorOwnerPasswords": securitySettings.honorOwnerPasswords,+ "security.blockSignedPdfEdits": securitySettings.blockSignedPdfEdits,"security.loginMethod": securitySettings.loginMethod,"security.loginAttemptCount": securitySettings.loginAttemptCount,"security.loginResetTimeMinutes": securitySettings.loginResetTimeMinutes,diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.tsindex 6a7cc877ed..8c958a2af7 100644--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts@@ -4,6 +4,7 @@export interface SecuritySettingsData {enableLogin?: boolean;honorOwnerPasswords?: boolean;+ blockSignedPdfEdits?: boolean;loginMethod?: string;loginAttemptCount?: number;loginResetTimeMinutes?: number;