diff --git a/fixtures/encryption/r4-cleartext-metadata.pdf b/fixtures/encryption/r4-cleartext-metadata.pdf new file mode 100644 index 00000000..0a1a4283 Binary files /dev/null and b/fixtures/encryption/r4-cleartext-metadata.pdf differ diff --git a/src/api/pdf-security.test.ts b/src/api/pdf-security.test.ts index 0ef22717..c6c3567e 100644 --- a/src/api/pdf-security.test.ts +++ b/src/api/pdf-security.test.ts @@ -115,6 +115,28 @@ describe("PDF security API", () => { // User doesn't have modify permission expect(() => pdf.removeProtection()).toThrow(PermissionDeniedError); }); + + it("removeProtection({ ignorePermissions: true }) succeeds without modify permission", async () => { + const bytes = await loadFixture("encryption", "PasswordSample-40bit.pdf"); + const pdf = await PDF.load(bytes, { credentials: "user" }); + + expect(() => pdf.removeProtection({ ignorePermissions: true })).not.toThrow(); + + const savedBytes = await pdf.save(); + const reloaded = await PDF.load(savedBytes); + + expect(reloaded.isEncrypted).toBe(false); + expect(reloaded.getPageCount()).toBe(pdf.getPageCount()); + }); + + it("removeProtection({ ignorePermissions: false }) still enforces permissions", async () => { + const bytes = await loadFixture("encryption", "PasswordSample-40bit.pdf"); + const pdf = await PDF.load(bytes, { credentials: "user" }); + + expect(() => pdf.removeProtection({ ignorePermissions: false })).toThrow( + PermissionDeniedError, + ); + }); }); describe("encrypted documents - owner password", () => { @@ -467,4 +489,62 @@ describe("PDF security API", () => { expect(unauthenticated.isAuthenticated).toBe(false); }); }); + + // https://github.com/LibPDF-js/core/issues/97 + describe("EncryptMetadata false", () => { + const decode = (bytes: Uint8Array) => new TextDecoder("windows-1252").decode(bytes); + + it("keeps an R4 cleartext-metadata PDF openable after a full save", async () => { + const bytes = await loadFixture("encryption", "r4-cleartext-metadata.pdf"); + const pdf = await PDF.load(bytes); + + expect(pdf.isAuthenticated).toBe(true); + expect(pdf.getSecurity().encryptMetadata).toBe(false); + + pdf.setTitle("changed"); + const savedBytes = await pdf.save(); + + expect(decode(savedBytes)).toMatch(/\/EncryptMetadata\s+false\b/); + expect(decode(savedBytes)).not.toContain("/EncryptMetadata /false"); + + const reloaded = await PDF.load(savedBytes); + + expect(reloaded.isAuthenticated).toBe(true); + expect(reloaded.getSecurity().encryptMetadata).toBe(false); + expect(reloaded.getTitle()).toBe("changed"); + }); + + it("keeps an R4 cleartext-metadata PDF openable after an incremental save", async () => { + const bytes = await loadFixture("encryption", "r4-cleartext-metadata.pdf"); + const pdf = await PDF.load(bytes); + + pdf.setTitle("changed"); + const savedBytes = await pdf.save({ incremental: true }); + + expect(decode(savedBytes)).not.toContain("/EncryptMetadata /false"); + + const reloaded = await PDF.load(savedBytes); + + expect(reloaded.isAuthenticated).toBe(true); + expect(reloaded.getSecurity().encryptMetadata).toBe(false); + expect(reloaded.getTitle()).toBe("changed"); + }); + + it("writes a valid R6 dictionary for setProtection({ encryptMetadata: false })", async () => { + const bytes = await loadFixture("basic", "rot0.pdf"); + const pdf = await PDF.load(bytes); + + pdf.setProtection({ ownerPassword: "owner", encryptMetadata: false }); + const savedBytes = await pdf.save(); + + expect(decode(savedBytes)).toMatch(/\/EncryptMetadata\s+false\b/); + expect(decode(savedBytes)).not.toContain("/EncryptMetadata /false"); + + // /Perms encodes EncryptMetadata, so a mismatch would fail authentication + const reloaded = await PDF.load(savedBytes); + + expect(reloaded.isAuthenticated).toBe(true); + expect(reloaded.getSecurity().encryptMetadata).toBe(false); + }); + }); }); diff --git a/src/api/pdf-security.ts b/src/api/pdf-security.ts index 54539316..ba8ef9fc 100644 --- a/src/api/pdf-security.ts +++ b/src/api/pdf-security.ts @@ -62,6 +62,20 @@ export interface ProtectionOptions { encryptMetadata?: boolean; } +/** + * Options for removing document protection. + */ +export interface RemoveProtectionOptions { + /** + * Skip the owner access / modify permission check. + * + * Any successfully decrypted document (including one opened with only + * the user password) can then be saved without encryption. + * @default false + */ + ignorePermissions?: boolean; +} + /** * Detailed security information about a document. */ diff --git a/src/api/pdf.ts b/src/api/pdf.ts index 2de5886a..a371b923 100644 --- a/src/api/pdf.ts +++ b/src/api/pdf.ts @@ -83,6 +83,7 @@ import type { EncryptionAlgorithmOption, PendingSecurityState, ProtectionOptions, + RemoveProtectionOptions, SecurityInfo, } from "./pdf-security"; import { PDFSignature } from "./pdf-signature"; @@ -923,9 +924,12 @@ export class PDF { * Remove all encryption from the document. * * After calling this, the document will be saved without encryption. - * Requires owner access, or user access with modify permission. + * Requires owner access, or user access with modify permission, unless + * `ignorePermissions` is set. * + * @param options - Removal options * @throws {PermissionDeniedError} If insufficient permissions to remove protection + * and `ignorePermissions` is not set * * @example * ```typescript @@ -933,9 +937,13 @@ export class PDF { * const pdf = await PDF.load(bytes, { credentials: "ownerPassword" }); * pdf.removeProtection(); * const unprotectedBytes = await pdf.save(); + * + * // Remove encryption with only the user password + * const restricted = await PDF.load(bytes, { credentials: "userPassword" }); + * restricted.removeProtection({ ignorePermissions: true }); * ``` */ - removeProtection(): void { + removeProtection(options: RemoveProtectionOptions = {}): void { // For unencrypted documents, this is a no-op if (!this.isEncrypted) { return; @@ -948,7 +956,7 @@ export class PDF { } // Check permissions - if (!handler.hasOwnerAccess && !handler.permissions.modify) { + if (!options.ignorePermissions && !handler.hasOwnerAccess && !handler.permissions.modify) { throw new PermissionDeniedError( "Cannot remove protection: requires owner access or modify permission", "modify", diff --git a/src/index.ts b/src/index.ts index 742e4c7e..b40e5732 100644 --- a/src/index.ts +++ b/src/index.ts @@ -95,6 +95,7 @@ export type { PermissionOptions, Permissions, ProtectionOptions, + RemoveProtectionOptions, SecurityInfo, } from "./api/pdf-security"; export { PermissionDeniedError, SecurityError } from "./security/errors"; diff --git a/src/security/encryption-dict.test.ts b/src/security/encryption-dict.test.ts index e4ba6dec..e7a6564e 100644 --- a/src/security/encryption-dict.test.ts +++ b/src/security/encryption-dict.test.ts @@ -161,6 +161,21 @@ describe("parseEncryptionDict", () => { expect(result.encryptMetadata).toBe(false); }); + it("should leniently parse EncryptMetadata written as the name /false", () => { + // Older libpdf versions wrote /EncryptMetadata /false + const dict = createR4Dict({ EncryptMetadata: PdfName.of("false") }); + const result = parseEncryptionDict(dict); + + expect(result.encryptMetadata).toBe(false); + }); + + it("should treat other EncryptMetadata names as the default (true)", () => { + const dict = createR4Dict({ EncryptMetadata: PdfName.of("true") }); + const result = parseEncryptionDict(dict); + + expect(result.encryptMetadata).toBe(true); + }); + it("should parse crypt filters", () => { const stdCF = PdfDict.of({ CFM: PdfName.of("AESV2"), diff --git a/src/security/encryption-dict.ts b/src/security/encryption-dict.ts index 66e24607..0e56a22b 100644 --- a/src/security/encryption-dict.ts +++ b/src/security/encryption-dict.ts @@ -300,7 +300,7 @@ export function parseEncryptionDict(dict: PdfDict): EncryptionDict { const permissions = parsePermissions(permissionsRaw); // Parse EncryptMetadata (R4+) - const encryptMetadata = dict.getBool("EncryptMetadata")?.value ?? true; + const encryptMetadata = parseEncryptMetadata(dict); // Parse R5-R6 specific fields let ownerEncryptionKey: Uint8Array | undefined; @@ -400,6 +400,32 @@ function validateVersionRevision(version: EncryptionVersion, revision: Encryptio } } +/** + * Parse /EncryptMetadata, defaulting to true. + * + * The spec defines this as a boolean, but earlier versions of this library + * wrote it as the name /false. Those files were encrypted with + * EncryptMetadata = false, so treat the name /false as the boolean false + * to keep them readable. + * + * TODO(1.0): Remove the name fallback. See https://github.com/LibPDF-js/core/issues/97 + */ +function parseEncryptMetadata(dict: PdfDict): boolean { + const bool = dict.getBool("EncryptMetadata"); + + if (bool) { + return bool.value; + } + + const name = dict.getName("EncryptMetadata"); + + if (name?.value === "false") { + return false; + } + + return true; +} + /** * Check if a dictionary represents an encrypted document. * diff --git a/src/security/encryption-generator.ts b/src/security/encryption-generator.ts index e5f2e080..2fd072d6 100644 --- a/src/security/encryption-generator.ts +++ b/src/security/encryption-generator.ts @@ -8,6 +8,7 @@ */ import type { ProtectionOptions } from "#src/api/pdf-security"; +import { PdfBool } from "#src/objects/pdf-bool"; import { PdfDict } from "#src/objects/pdf-dict"; import { PdfName } from "#src/objects/pdf-name"; import { PdfNumber } from "#src/objects/pdf-number"; @@ -112,7 +113,7 @@ export function generateEncryption(options: ProtectionOptions): GeneratedEncrypt // Only add EncryptMetadata if false (true is the default) if (!encryptMetadata) { - encryptDict.set("EncryptMetadata", PdfName.of("false")); + encryptDict.set("EncryptMetadata", PdfBool.FALSE); } // Create an EncryptionDict object for the security handler @@ -243,7 +244,7 @@ export function reconstructEncryptDict(encryption: EncryptionDict): PdfDict { // EncryptMetadata (only if false, true is default) if (!encryption.encryptMetadata) { - dict.set("EncryptMetadata", PdfName.of("false")); + dict.set("EncryptMetadata", PdfBool.FALSE); } return dict;