Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added fixtures/encryption/r4-cleartext-metadata.pdf
Binary file not shown.
80 changes: 80 additions & 0 deletions src/api/pdf-security.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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);
});
});
});
14 changes: 14 additions & 0 deletions src/api/pdf-security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
14 changes: 11 additions & 3 deletions src/api/pdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import type {
EncryptionAlgorithmOption,
PendingSecurityState,
ProtectionOptions,
RemoveProtectionOptions,
SecurityInfo,
} from "./pdf-security";
import { PDFSignature } from "./pdf-signature";
Expand Down Expand Up @@ -923,19 +924,26 @@ 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
* // Remove encryption from a document
* 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;
Expand All @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export type {
PermissionOptions,
Permissions,
ProtectionOptions,
RemoveProtectionOptions,
SecurityInfo,
} from "./api/pdf-security";
export { PermissionDeniedError, SecurityError } from "./security/errors";
Expand Down
15 changes: 15 additions & 0 deletions src/security/encryption-dict.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
28 changes: 27 additions & 1 deletion src/security/encryption-dict.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
Expand Down
5 changes: 3 additions & 2 deletions src/security/encryption-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
Loading