Skip to content

fix: inability to download encrypted pdfs from pdf preview#40517

Open
nazabucciarelli wants to merge 4 commits into
developfrom
fix/pdf-viewer-encrypted-room
Open

fix: inability to download encrypted pdfs from pdf preview#40517
nazabucciarelli wants to merge 4 commits into
developfrom
fix/pdf-viewer-encrypted-room

Conversation

@nazabucciarelli
Copy link
Copy Markdown
Contributor

@nazabucciarelli nazabucciarelli commented May 13, 2026

Proposed changes (including videos or screenshots)

I’ll divide the fix in 2 steps:

1- Rocket.Chat Electron Repo: I’ll need to add ‘blob:’ as a supported protocol in src/documentViewer/ipc.ts so that the sent blob is served by the PDF viewer in Electron. This one-line PR was raised for that.

2- Rocket.Chat Main Repo: In the GenericFileAttachment component (the one that renders attachments), I've added two different flows for the electron path:

  1. If the PDF is encrypted, it will be fetched using the service worker and converted to blob, so in that way the electron embedded PDF preview is able to manage the download. If the PDF exceeds the MAX_FILE_SIZE_PREVIEW const, it won't be converted to blob but downloaded, otherwise it would be very resource consuming. To avoid memory leaks, blob urls are properly revoked.
  2. If the PDF isn't encrypted, no functional changes are expected. As you can see that flow wasn't touched.

No tests will be implemented since we can't test the PDF viewer from the Electron app.

Issue(s)

SUP-1022 Download fail on Encrypted rooms PDF Viewer

Steps to test or reproduce

Steps to reproduce on Electron and Browser:

  • Enable encryption in room
  • Upload a .pdf
  • Open file on PDF viewer
  • Click "Download"
  • Save
  • Fail with "Download error - The download of .txt was interrupted

Further comments

Summary by CodeRabbit

  • Bug Fixes
    • Fixed inability to download encrypted PDF files on the desktop app.
    • Desktop document viewer now opens and displays encrypted PDFs inline when possible.
    • Added size-based fallback to switch to download mode for encrypted PDFs that exceed preview limits.

Review Change Stack

Comment thread apps/meteor/client/hooks/useDownloadFromServiceWorker.ts Fixed
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented May 13, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 13, 2026

🦋 Changeset detected

Latest commit: 78225b7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 42 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/api-client Patch
@rocket.chat/apps Patch
@rocket.chat/core-services Patch
@rocket.chat/cron Patch
@rocket.chat/ddp-client Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/http-router Patch
@rocket.chat/livechat Patch
@rocket.chat/model-typings Patch
@rocket.chat/models Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-client Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/ui-voip Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/license Patch
@rocket.chat/media-calls Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/pdf-worker Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/mock-providers Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch
@rocket.chat/server-fetch Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/ui-composer Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e690c035-5844-4d30-9c6f-0359538101e0

📥 Commits

Reviewing files that changed from the base of the PR and between ab04cdf and 78225b7.

📒 Files selected for processing (1)
  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build

Walkthrough

GenericFileAttachment detects encrypted /file-decrypt/ links and, for PDFs on desktop, either opens decrypted blobs in the desktop document viewer (with object URL lifecycle and aborts) or falls back to the service-worker download flow for large files; includes a changeset entry.

Changes

Encrypted PDF Viewing on Desktop

Layer / File(s) Summary
Resource management setup and imports
apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
React imports add useEffect/useRef; MAX_FILE_SIZE_PREVIEW and download helpers are imported; blobUrlRef and abortControllerRef are added and a cleanup effect aborts in-flight fetches and revokes object URLs on unmount.
Encrypted PDF detection and viewing handler
apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
handleTitleClick becomes async and detects encrypted /file-decrypt/ links; for PDFs with window.RocketChatDesktop?.openDocumentViewer, encrypted files are either routed to the service-worker when over MAX_FILE_SIZE_PREVIEW or fetched/decrypted, converted to object URLs, opened in the desktop viewer, and prior URLs/fetches are cleaned up; encrypted non-PDF links continue to download via service worker; non-encrypted PDFs still open with contentDisposition=inline.
Release documentation
.changeset/fine-jokes-trade.md
Add changeset entry for a patch release documenting the fix for downloading encrypted PDFs on desktop.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing the inability to download encrypted PDFs from the PDF preview, which matches the core objective and primary code changes in GenericFileAttachment.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • SUP-1022: Request failed with status code 401

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 13, 2026

Codecov Report

❌ Patch coverage is 11.47541% with 54 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.59%. Comparing base (1acd37a) to head (78225b7).
⚠️ Report is 33 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40517      +/-   ##
===========================================
- Coverage    69.63%   69.59%   -0.05%     
===========================================
  Files         3318     3325       +7     
  Lines       121981   122853     +872     
  Branches     21813    21876      +63     
===========================================
+ Hits         84947    85499     +552     
- Misses       33701    34007     +306     
- Partials      3333     3347      +14     
Flag Coverage Δ
e2e 59.06% <13.51%> (-0.01%) ⬇️
e2e-api 46.22% <ø> (-0.02%) ⬇️
unit 70.32% <3.27%> (-0.11%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates file attachment handling so PDF attachments—especially encrypted PDFs—can be previewed inline and downloaded from the PDF viewer instead of failing through the previous encrypted download path.

Changes:

  • Adds a helper to request decrypted attachment bytes from the service worker.
  • Routes PDF title clicks through browser/native PDF preview or Electron document viewer.
  • Preserves the existing service-worker download path for encrypted non-PDF files.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
apps/meteor/client/hooks/useDownloadFromServiceWorker.ts Adds getDecryptedBuffer for retrieving decrypted attachment data from the service worker.
apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx Splits PDF handling into encrypted blob-preview and non-encrypted inline-preview flows.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/meteor/client/hooks/useDownloadFromServiceWorker.ts Outdated
@nazabucciarelli nazabucciarelli force-pushed the fix/pdf-viewer-encrypted-room branch from 3d105f4 to 77b5b46 Compare May 14, 2026 22:06
@nazabucciarelli nazabucciarelli marked this pull request as ready for review May 14, 2026 22:28
@nazabucciarelli nazabucciarelli requested a review from a team as a code owner May 14, 2026 22:28
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx`:
- Around line 38-45: The cleanup effect currently revokes blobUrlRef.current on
unmount but doesn’t prevent a concurrent fetch from later assigning a new blob
URL, causing a leak; update the component to add a mounted flag (e.g., let
isMounted = true in useEffect and set false on cleanup) and/or use an
AbortController to cancel the in-flight fetch, and only set blobUrlRef.current
(and call URL.createObjectURL) if isMounted is true and the fetch was not
aborted; apply the same guard to the fetch logic referenced around the
download/fetch function (the code that assigns blobUrlRef.current, lines ~66-71)
so any newly created blob URL is only stored while mounted and revoked on
cleanup (and abort the fetch on unmount).
- Around line 63-71: The blob URL leak happens when multiple clicks start
overlapping fetches because only blobUrlRef.current is tracked; fix by
introducing an AbortController stored (e.g., in a ref like fetchAbortRef) and
before starting a new fetch abort any in-flight request and revoke any
previously created blob URL (blobUrlRef.current) to ensure cleanup; then create
a new AbortController for the new fetch, pass its signal to fetch(getURL(link)),
await response.blob(), create the new object URL, set blobUrlRef.current and
openDocumentViewer(blobUrl, format, title ?? ''), and ensure you handle
AbortError (skip revoke if already revoked) and always revoke old blob URLs when
replacing them to prevent leaks.
- Around line 66-71: Wrap the fetch/get blob sequence in a try-catch around the
code that calls fetch(getURL(link)), response.blob(), URL.createObjectURL and
openDocumentViewer so network or blob errors are caught; on success set
blobUrlRef.current and call openDocumentViewer(blobUrl, format, title ?? ''), on
failure log the error (console.error) and surface a user-facing error (e.g.,
show a toast/alert or call a provided notification helper) so clicking gives
feedback; also ensure any created object URL is revoked on error/cleanup (use
URL.revokeObjectURL) so resources aren’t leaked and blobUrlRef.current is only
assigned after successful creation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6ad6eb8c-d3d7-4ff1-a1fa-efdb623d2af3

📥 Commits

Reviewing files that changed from the base of the PR and between 2d32e52 and 339c708.

📒 Files selected for processing (2)
  • .changeset/fine-jokes-trade.md
  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
📜 Review details
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
🧠 Learnings (3)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/fine-jokes-trade.md
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx
🔇 Additional comments (1)
.changeset/fine-jokes-trade.md (1)

1-5: LGTM!

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx">

<violation number="1" location="apps/meteor/client/components/message/content/attachments/file/GenericFileAttachment.tsx:79">
P2: Check `response.ok` before converting to blob; HTTP error responses currently get opened in the PDF viewer as if they were valid files.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
Re-trigger cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants