Skip to content

[Bug] Saving metadata to encrypted PDF silently corrupts the file #368

Description

@santisbon

What went wrong?

When writing metadata to an encrypted PDF (even one that opens freely and allows all operations) the file becomes corrupted with no indication to the user that anything's wrong. You don't find out until you try to peek or read the book and realize that readers reject the corrupted file.

Here's where the file is loaded ignoring encryption:
https://github.com/bookorbit/bookorbit/blob/main/server/src/modules/file-write/formats/pdf/pdf-format-writer.ts#L33

And here's where it's saved without re-encrypting
https://github.com/bookorbit/bookorbit/blob/main/server/src/modules/file-write/formats/pdf/pdf-format-writer.ts#L38

Suggested fix: Check PDFDocument.isEncrypted and if true return { status: 'skipped', reason: 'encrypted-pdf' } similar to what it does in the dryRun.
https://pdf-lib.js.org/docs/api/classes/pdfdocument#isencrypted

Steps to reproduce

  1. Download an encrypted PDF like https://courses.csail.mit.edu/6.042/spring18/mcs.pdf.
  2. Upload to BookOrbit.
  3. Verify you can read the book just fine.
  4. Edit metadata and write it to the file. You'll see a success message.
  5. Try to peek or read the file again. You'll see Error loading document. FPDF_LoadMemDocument Failed. Error Code: 3.

You can verify that the file is encrypted with

pdfinfo ~/Downloads/mcs.pdf
# Encrypted:       yes (print:yes copy:yes change:yes addNotes:yes algorithm:RC4)
qpdf --show-encryption ~/Downloads/mcs.pdf
# R = 3
# P = -4
# User password = 
# Supplied password is user password
# extract for accessibility: allowed
# extract for any purpose: allowed
# print low resolution: allowed
# print high resolution: allowed
# modify document assembly: allowed
# modify forms: allowed
# modify annotations: allowed
# modify other: allowed
# modify anything: allowed

Expected vs actual behavior

Expected: Writing metadata to encrypted PDF skips the file write and writes to database only.
Actual: Writes unencrypted byte streams to the file, corrupting it.

Your setup

Book Orbit v1.10.0 bookorbit/bookorbit:latest
Deployment: Kubernetes
OS: Ubuntu 26.04
Browser: Brave

Relevant logs (optional)

Screenshots (optional)

No response

Before submitting

  • I've searched existing issues and this hasn't been reported yet.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreleasedIssue or PR is included in a released version.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions