Skip to content

feat(editor): preview Word, PowerPoint and Excel files - #29678

Open
nebourocket wants to merge 1 commit into
stablyai:mainfrom
nebourocket:feat/office-document-preview
Open

nebourocket wants to merge 1 commit into
stablyai:mainfrom
nebourocket:feat/office-document-preview

Conversation

@nebourocket

Copy link
Copy Markdown

ELI5

Before, opening a Word, PowerPoint or Excel file in Orca showed "Binary file — cannot display". Now the tab shows the document itself: Word pages, PowerPoint slides, and Excel sheets as a table. It is view-only, the same as the PDF preview.

What Changed

Before: .docx, .pptx and .xlsx tabs showed "Binary file — cannot display".
After: they open as read-only previews, with a footer label ("Word preview" / "PowerPoint preview" / "Excel preview") like the PDF viewer.

How it works:

  • Reading the file. Orca already sends images and PDFs to the renderer as base64 when their extension is in a "previewable binary" MIME table. I added one shared table (src/shared/office-document-mime-types.ts) and spread it into the three tables that decide this: local IPC (filesystem-file-content-inspection.ts), runtime / SSH previews (file-preview-budget.ts), and the renderer's paged remote reads (runtime-paged-file-read.ts). One table keeps the three routes in step. Size limits stay as they are (50 MB local, the existing RPC budget remotely).
  • Showing the file. ImageViewer already branches to PdfViewer by MIME type. It now branches Office MIME types to a new office/OfficeDocumentViewer, which lazy-loads one renderer per format in its own chunk:
    • Word: docx-preview (renderAltChunks: false, so no author HTML in an iframe)
    • PowerPoint: @aiden0z/pptx-renderer (its recommended zip limits, windowed and lazy slides, PDF.js fallback off)
    • Excel: read-excel-file, drawn with the existing read-only CsvGrid, plus sheet tabs
  • Guards:
    • Chat image access (isChatImage) is now limited to image/* instead of "every previewable type except PDF". Without this change, Office files would have become chat images.
    • Before rendering, the zip's central directory is read without inflating anything. A file that declares more than 256 MB uncompressed (the same total pptx-renderer uses) or more than 4000 entries is refused, because docx-preview and read-excel-file have no inflate limit of their own.
    • Links inside a document never navigate Orca's window. http(s) links go through the existing CSV/markdown link routing. #bookmark links scroll inside the preview. Every other scheme is ignored.

Why

Office files are common in agent workspaces: reports, decks and data that agents produce or read. Today, checking one means leaving Orca.

Alternatives I considered:

Known limits: the preview is read-only. Excel shows cell values (cached formula results), not formatting or charts. PowerPoint rendering is browser-based, so complex effects and missing fonts can differ from PowerPoint. Legacy .doc/.ppt/.xls are not handled.

Linked Issue

Fixes #8301

Visual Proof

Before: these tabs showed "Binary file — cannot display". After (hidden-window Electron captures from the new e2e spec):

Word
docx

PowerPoint
pptx

Excel (sheet tabs at the bottom)
xlsx

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Automated tests:

  • New e2e tests/e2e/office-document-preview.spec.ts, using small generated fixtures in tests/e2e/fixtures/office/. It opens all three formats, checks the rendered content, and switches Excel sheets. It passes with --project=electron-headless.
  • Unit tests: xlsx-sheet-grid (cell text and padding), office-zip-budget (budget accept and refuse, non-zip input), local read of a .docx (MIME and base64), chat-image refusal of .pptx, and renderer previewableBinaryMimeType for Office extensions.

Checks run:

  • pnpm tc
  • pnpm run check:code-quality:changed
  • oxlint
  • localization extraction, catalogs and coverage
  • check:max-lines-ratchet
  • the related Vitest suites (94 tests)

Platforms: tested on Linux (WSL2). Not tested on macOS, Windows or a real SSH host. The change is platform-neutral renderer code, plus MIME-table entries on the existing read paths.

AI Disclosure

Written with Claude Code (Claude Opus 5.5). I reviewed the code and verified it with the tests above.

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: the guards above (no alt-chunk iframes, links routed or blocked, zip budget, chat stays image-only). The renderers build the DOM themselves, with no eval.
  • SSH and remote: the runtime table and the renderer paged-read table both include the Office types.
  • Mobile: unchanged, because it classifies files by extension.
  • Performance: the renderers load only when an Office file is opened. The chunks are about 76 KB for Word, 54 KB for Excel and 1.1 MB for PowerPoint (ECharts for charts).

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred). Typecheck, the changed-code gate, oxlint, localization checks, the related tests and the electron-vite build pass locally. CI will cover the full suites.

Open .docx, .pptx and .xlsx files as read-only previews in editor tabs,
next to the existing image and PDF previews.

- One shared Office MIME table feeds the local IPC, runtime/SSH and
  renderer paged-read routes so every route previews the same files.
- docx-preview, @aiden0z/pptx-renderer and read-excel-file are
  lazy-loaded in their own chunks; sheets reuse the CSV grid.
- Zips whose central directory declares more than 256 MB, document
  links, and chat image access are guarded.
Copilot AI balanced review requested due to automatic review settings October 16, 2026 13:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@facu-1921

Copy link
Copy Markdown

banco una banda

@coderabbitai

coderabbitai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds in-editor previews for DOCX, PPTX, and XLSX files. Shared MIME mappings connect these formats to file inspection, runtime preview detection, and the editor viewer. The viewer decodes content and checks ZIP limits before selecting a format-specific renderer. The new views render documents, slides, and spreadsheet grids. Tests cover file handling, MIME detection, ZIP budgets, grid conversion, and end-to-end previews.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to f7e95

A crafted Office file could consume substantially more memory than the preview limit permits. Enforce the limit during decompression before merging.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning PR #29678 implements in-editor previews for DOCX, PPTX, and XLSX, including Office MIME routing, selectable rendered content, Excel sheet tabs, and automated preview tests. Direct issue #8301 also req… Add the #8301 text-selection and annotation or agent-context integration. Expose DOCX, PPTX, and XLSX content through workspace context for agents. Add automated tests for these workflows.
Docstring Coverage Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 20 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: adding Word, PowerPoint, and Excel previews in the editor.
Description check Passed The description covers the required sections, explains the user-visible change and implementation, links issue #8301, includes visual proof, documents testing and platform coverage, and records known …
Out of Scope Changes check Passed The changed files support the Office-preview objective in #8301. MIME routing, lazy viewers, ZIP limits, link handling, chat-image restriction, localization, unit tests, and end-to-end tests are direc…
Full details: Description check

Explanation

The description covers the required sections, explains the user-visible change and implementation, links issue #8301, includes visual proof, documents testing and platform coverage, and records known limits and security considerations. The full test and build checklist remains unchecked, but the description explains which checks passed locally and that CI will cover the remaining suites.

Full details: Out of Scope Changes check

Explanation

The changed files support the Office-preview objective in #8301. MIME routing, lazy viewers, ZIP limits, link handling, chat-image restriction, localization, unit tests, and end-to-end tests are directly related implementation or validation. No unrelated change is demonstrated by the available whole-PR summary.

Full details: Linked Issues check

Explanation

PR #29678 implements in-editor previews for DOCX, PPTX, and XLSX, including Office MIME routing, selectable rendered content, Excel sheet tabs, and automated preview tests. Direct issue #8301 also requires text selection for annotation or agent context and agent access to document content through workspace context. The PR explicitly describes the viewers as read-only and does not implement those integrations. The available summary does not establish that the existing workspace context already reads these formats.

Resolution

Add the #8301 text-selection and annotation or agent-context integration. Expose DOCX, PPTX, and XLSX content through workspace context for agents. Add automated tests for these workflows.

Full details: Docstring Coverage

Explanation

Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 20 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 04a4ee7c-3df9-42ca-865a-128fa252650f
📥 Commits

Reviewing files that changed from the base of the PR and between 5bad9cb and f7e95b2.

⛔ Files ignored due to path filters: 4
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • tests/e2e/fixtures/office/deck.pptx is excluded by !**/*.pptx
  • tests/e2e/fixtures/office/engines.xlsx is excluded by !**/*.xlsx
  • tests/e2e/fixtures/office/report.docx is excluded by !**/*.docx
📒 Files selected for processing: 22
  • package.json
  • src/main/ipc/filesystem/filesystem-file-content-inspection.ts
  • src/main/ipc/filesystem/local-regular-file-read.test.ts
  • src/main/ipc/local-file-access-resolution.test.ts
  • src/main/ipc/local-file-access-resolution.ts
  • src/main/runtime/files/file-preview-budget.ts
  • src/renderer/src/components/editor/ImageViewer.tsx
  • src/renderer/src/components/editor/office/DocxDocumentView.tsx
  • src/renderer/src/components/editor/office/OfficeDocumentViewer.tsx
  • src/renderer/src/components/editor/office/PptxDocumentView.tsx
  • src/renderer/src/components/editor/office/XlsxDocumentView.tsx
  • src/renderer/src/components/editor/office/office-document-bytes.ts
  • src/renderer/src/components/editor/office/office-document-links.ts
  • src/renderer/src/components/editor/office/office-zip-budget.test.ts
  • src/renderer/src/components/editor/office/office-zip-budget.ts
  • src/renderer/src/components/editor/office/xlsx-sheet-grid.test.ts
  • src/renderer/src/components/editor/office/xlsx-sheet-grid.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/runtime/runtime-paged-file-read.test.ts
  • src/renderer/src/runtime/runtime-paged-file-read.ts
  • src/shared/office-document-mime-types.ts
  • tests/e2e/office-document-preview.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

const href = anchor.getAttribute('href') ?? ''
if (href.startsWith('#')) {
// Why: a native hash jump would change Orca's own location, so scroll to the bookmark instead.
const id = decodeURIComponent(href.slice(1))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Catch URIError from decodeURIComponent.

decodeURIComponent throws a URIError for malformed input such as #%E0. Document authors control these hrefs. The error escapes the click handler and the bookmark jump does nothing. Fall back to the raw value when decoding fails.

Proposed fix
--- "a/src/renderer/src/components/editor/office/office-document-links.ts"
+++ "b/src/renderer/src/components/editor/office/office-document-links.ts"
@@ -17,7 +17,12 @@
   const href = anchor.getAttribute('href') ?? ''
   if (href.startsWith('#')) {
     // Why: a native hash jump would change Orca's own location, so scroll to the bookmark instead.
-    const id = decodeURIComponent(href.slice(1))
+    let id = href.slice(1)
+    try {
+      id = decodeURIComponent(id)
+    } catch {
+      // keep raw fragment
+    }
     const target = [...container.querySelectorAll('[id],[name]')].find(
       (element) => element.id === id || element.getAttribute('name') === id
     )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const id = decodeURIComponent(href.slice(1))
let id = href.slice(1)
try {
id = decodeURIComponent(id)
} catch {
// keep raw fragment
}

Comment on lines +13 to +19
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
const end = findEndOfCentralDirectory(view)
if (end === null) {
return false
}
const entryCount = view.getUint16(end + 10, true)
let offset = view.getUint32(end + 16, true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- helper ---'
nl -ba src/renderer/src/components/editor/office/office-zip-budget.ts
printf '%s\n' '--- references ---'
rg -n -F --glob '*.{ts,tsx,js,json}' -e 'officeZipWithinBudget' -e 'docx-preview' -e 'read-excel-file' -e 'zip' src package.json pnpm-lock.yaml 2>/dev/null || true
printf '%s\n' '--- package declarations ---'
rg -n -F --glob 'package.json' -e 'docx-preview' -e 'read-excel-file' -e 'fflate' -e 'jszip' -e 'unzip' .
printf '%s\n' '--- installed package sources ---'
if [ -d node_modules ]; then
  find node_modules -maxdepth 4 \( -path '*docx-preview*' -o -path '*read-excel-file*' -o -path '*fflate*' -o -path '*jszip*' \) -type f | sed -n '1,200p'
else
  printf '%s\n' 'node_modules unavailable'
fi

Repository: stablyai/orca

Length of output: 32373


🏁 Script executed:

set -eu
printf '%s\n' '--- OfficeDocumentViewer ---'
nl -ba src/renderer/src/components/editor/office/OfficeDocumentViewer.tsx
printf '%s\n' '--- DocxDocumentView ---'
nl -ba src/renderer/src/components/editor/office/DocxDocumentView.tsx
printf '%s\n' '--- XlsxDocumentView ---'
nl -ba src/renderer/src/components/editor/office/XlsxDocumentView.tsx
printf '%s\n' '--- PptxDocumentView ---'
nl -ba src/renderer/src/components/editor/office/PptxDocumentView.tsx
printf '%s\n' '--- related tests ---'
nl -ba src/renderer/src/components/editor/office/office-zip-budget.test.ts
printf '%s\n' '--- lockfile package records ---'
sed -n '4800,4825p;6910,6940p;5720,5740p' pnpm-lock.yaml

Repository: stablyai/orca

Length of output: 18867


🌐 Web query:

docx-preview 0.4.1 read-excel-file 9.3.12 ZIP inflation local header central directory source

💡 Result:

**Short answer:** they use different ZIP layers, and only `read-excel-file`’s package documentation explicitly identifies its decompression libraries.

- **`[email protected]`:** The package README says browser ZIP decompression uses **`fflate`**, while Node.js uses **`unzipper-esm`**. That establishes the libraries, but not their exact local-header/central-directory parsing path. ([npmjs.com](https://www.npmjs.com/package/read-excel-file?activeTab=readme&utm_source=openai))
- **`[email protected]`:** Its source repository is `VolodymyrBaydalka/docxjs`; the available source view shows ZIP access through a `JSZip` object (`this._zip.files` / `this._zip.file(...)`). This supports that the package delegates ZIP handling to JSZip, rather than implementing ZIP parsing itself. The fetched source is `master`, however—not a version-pinned 0.4.1 source file—so the exact 0.4.1 implementation remains unverified. ([github.com](https://github.com/VolodymyrBaydalka/docxjs/blob/master/dist/docx-preview.mjs?utm_source=openai))

For the specific mechanics: `fflate`’s source includes code to skip local headers and read ZIP headers; that illustrates its parser implementation, but the source retrieved is `master`, not a version-pinned dependency used by `[email protected]`. ([github.com](https://github.com/101arrowz/fflate/blob/master/src/index.ts?utm_source=openai))

**Bottom line:** the evidence points to **JSZip** for `docx-preview` and **fflate (browser) / unzipper-esm (Node)** for `read-excel-file`. I can’t confirm from the retrieved version-pinned sources exactly how either handles inflation and central-directory versus local-header fields in those precise releases.

Citations:

- 1: https://www.npmjs.com/package/read-excel-file?activeTab=readme&utm_source=openai
- 2: https://github.com/VolodymyrBaydalka/docxjs/blob/master/dist/docx-preview.mjs?utm_source=openai
- 3: https://github.com/101arrowz/fflate/blob/master/src/index.ts?utm_source=openai

🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

packages = [
    ('docx-preview', '0.4.1'),
    ('read-excel-file', '9.3.12'),
    ('jszip', '3.10.2'),
    ('fflate', '0.8.3'),
    ('unzipper-esm', '0.13.3'),
]

patterns = re.compile(
    r'local|central|uncompressed|compressedSize|compressedSize|inflate|decompress|readData|file\.'
    , re.I
)

for name, version in packages:
    url = f'https://registry.npmjs.org/{name}/-/{name}-{version}.tgz'
    print(f'--- {name}@{version} ---')
    try:
        data = urllib.request.urlopen(url, timeout=20).read()
        tf = tarfile.open(fileobj=io.BytesIO(data), mode='r:gz')
        shown = 0
        for member in tf.getmembers():
            if not member.isfile():
                continue
            text = tf.extractfile(member).read().decode('utf-8', 'replace')
            lines = text.splitlines()
            matches = [i for i, line in enumerate(lines) if patterns.search(line)]
            if not matches:
                continue
            print(f'FILE {member.name}')
            selected = []
            for i in matches:
                selected.extend(range(max(0, i - 2), min(len(lines), i + 3)))
            for i in sorted(set(selected)):
                print(f'{i + 1}:{lines[i]}')
            shown += 1
            if shown >= 12:
                break
        if shown == 0:
            print('no matching source excerpts')
    except Exception as exc:
        print(type(exc).__name__ + ': ' + str(exc))
PY
printf '%s\n' '--- read-excel-file dependency records ---'
rg -n -A12 -B3 -F '[email protected]' pnpm-lock.yaml
printf '%s\n' '--- browser dependency records ---'
rg -n -A8 -B3 -F 'fflate@' pnpm-lock.yaml

Repository: stablyai/orca

Length of output: 45667


🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

targets = [
    ('docx-preview', '0.4.1'),
    ('jszip', '3.10.2'),
    ('read-excel-file', '9.3.12'),
    ('fflate', '0.8.3'),
    ('unzipper-esm', '0.13.3'),
]
name_re = re.compile(r'(zip|unzip|inflate|decompress|xlsx)', re.I)
line_re = re.compile(
    r'(compressedSize|uncompressedSize|compressed size|uncompressed size|'
    r'local file|local header|central directory|inflateRaw|inflateSync|'
    r'unzipSync|decompressSync|readData|entry\.size|vars\.size)',
    re.I,
)

for name, version in targets:
    url = f'https://registry.npmjs.org/{name}/-/{name}-{version}.tgz'
    print(f'--- {name}@{version} ---')
    data = urllib.request.urlopen(url, timeout=20).read()
    tf = tarfile.open(fileobj=io.BytesIO(data), mode='r:gz')
    candidates = [
        m for m in tf.getmembers()
        if m.isfile()
        and name_re.search(m.name)
        and not m.name.endswith(('.map', '.min.js'))
    ]
    print('candidate files:', ', '.join(m.name for m in candidates[:40]))
    for member in candidates:
        text = tf.extractfile(member).read().decode('utf-8', 'replace')
        lines = text.splitlines()
        hits = [i for i, line in enumerate(lines) if line_re.search(line)]
        if not hits:
            continue
        print(f'FILE {member.name}')
        selected = set()
        for i in hits:
            selected.update(range(max(0, i - 2), min(len(lines), i + 3)))
        for i in sorted(selected):
            print(f'{i + 1}:{lines[i]}')
PY

Repository: stablyai/orca

Length of output: 32916


🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

def package(name, version):
    url = f'https://registry.npmjs.org/{name}/-/{name}-{version}.tgz'
    return tarfile.open(fileobj=io.BytesIO(urllib.request.urlopen(url, timeout=20).read()), mode='r:gz')

print('--- fflate files ---')
tf = package('fflate', '0.8.3')
for m in tf.getmembers():
    if m.isfile():
        print(m.name)

print('--- fflate unzip/inflate excerpts ---')
for m in tf.getmembers():
    if not m.isfile() or m.name.endswith('.map'):
        continue
    text = tf.extractfile(m).read().decode('utf-8', 'replace')
    lines = text.splitlines()
    hits = [
        i for i, line in enumerate(lines)
        if re.search(r'(unzipSync|function unzip|inflateSync|function inflate|csize|usize|uncompressed|compressed)', line, re.I)
    ]
    if not hits:
        continue
    print(f'FILE {m.name}')
    selected = set()
    for i in hits:
        selected.update(range(max(0, i - 2), min(len(lines), i + 3)))
    for i in sorted(selected):
        print(f'{i + 1}:{lines[i]}')

print('--- read-excel-file browser zip wrapper ---')
tf = package('read-excel-file', '9.3.12')
for m in tf.getmembers():
    if not m.isfile() or not re.search(r'zip/unzipFromArrayBuffer|export/readXlsxFileBrowser', m.name):
        continue
    text = tf.extractfile(m).read().decode('utf-8', 'replace')
    print(f'FILE {m.name}')
    for i, line in enumerate(text.splitlines(), 1):
        print(f'{i}:{line}')
PY

Repository: stablyai/orca

Length of output: 42410


🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

url = 'https://registry.npmjs.org/read-excel-file/-/read-excel-file-9.3.12.tgz'
tf = tarfile.open(fileobj=io.BytesIO(urllib.request.urlopen(url, timeout=20).read()), mode='r:gz')
for m in tf.getmembers():
    if not m.isfile() or m.name.endswith('.map'):
        continue
    text = tf.extractfile(m).read().decode('utf-8', 'replace')
    if not re.search(r'unzipFromArrayBuffer|readXlsxFileBrowser|readXlsxFileUniversal|unzipFromStream', text):
        continue
    print(f'FILE {m.name}')
    lines = text.splitlines()
    for i, line in enumerate(lines, 1):
        if re.search(r'unzipFromArrayBuffer|readXlsxFileBrowser|readXlsxFileUniversal|unzipFromStream|readXlsxFile\(', line):
            for j in range(max(1, i - 4), min(len(lines), i + 8) + 1):
                print(f'{j}:{lines[j-1]}')
            print('---')
PY

Repository: stablyai/orca

Length of output: 42086


🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

url = 'https://registry.npmjs.org/docx-preview/-/docx-preview-0.4.1.tgz'
tf = tarfile.open(fileobj=io.BytesIO(urllib.request.urlopen(url, timeout=20).read()), mode='r:gz')
for m in tf.getmembers():
    if not m.isfile() or m.name.endswith('.map'):
        continue
    text = tf.extractfile(m).read().decode('utf-8', 'replace')
    if not re.search(r'JSZip|loadAsync|\\.file\\(', text):
        continue
    print(f'FILE {m.name}')
    lines = text.splitlines()
    for i, line in enumerate(lines, 1):
        if re.search(r'JSZip|loadAsync|\\.file\\(', line):
            for j in range(max(1, i - 3), min(len(lines), i + 4) + 1):
                print(f'{j}:{lines[j-1]}')
            print('---')
print('--- package manifest ---')
for m in tf.getmembers():
    if m.name == 'package/package.json':
        print(tf.extractfile(m).read().decode('utf-8', 'replace'))
PY

Repository: stablyai/orca

Length of output: 974


🏁 Script executed:

python3 - <<'PY'
import io, re, tarfile, urllib.request

url = 'https://registry.npmjs.org/docx-preview/-/docx-preview-0.4.1.tgz'
tf = tarfile.open(fileobj=io.BytesIO(urllib.request.urlopen(url, timeout=20).read()), mode='r:gz')
for m in tf.getmembers():
    if not m.isfile() or m.name.endswith('.map'):
        continue
    text = tf.extractfile(m).read().decode('utf-8', 'replace')
    if not re.search(r'JSZip|loadAsync|\.file\(', text):
        continue
    print(f'FILE {m.name}')
    lines = text.splitlines()
    for i, line in enumerate(lines, 1):
        if re.search(r'JSZip|loadAsync|\.file\(', line):
            for j in range(max(1, i - 3), min(len(lines), i + 4) + 1):
                print(f'{j}:{lines[j-1]}')
            print('---')
print('--- package manifest ---')
for m in tf.getmembers():
    if m.name == 'package/package.json':
        print(tf.extractfile(m).read().decode('utf-8', 'replace'))
PY

Repository: stablyai/orca

Length of output: 41676


Reject short ZIP inputs and cap decompressed output.

findEndOfCentralDirectory can pass a negative offset to DataView.getUint32 for inputs shorter than 22 bytes. Return false before scanning, and validate the matching end record.

The main risk is not local-header size selection. docx-preview delegates to JSZip, which can inflate data before checking the actual output length. The browser path of read-excel-file uses fflate's asynchronous unzip path, which has no fixed output cap for highly compressed entries. A crafted entry can therefore declare less than 256 MiB in the central directory but make the renderer process much more data.

Enforce the 256 MiB limit during decompression, or use APIs with a hard output limit. Do not rely only on central-directory metadata.

🐛 Suggested fix
 function findEndOfCentralDirectory(view: DataView): number | null {
+  if (view.byteLength < END_RECORD_BYTES) {
+    return null
+  }
   const lowest = Math.max(0, view.byteLength - END_RECORD_BYTES - MAX_COMMENT_BYTES)
   for (let offset = view.byteLength - END_RECORD_BYTES; offset >= lowest; offset -= 1) {
     if (view.getUint32(offset, true) === END_OF_CENTRAL_DIRECTORY) {
+      const commentLength = view.getUint16(offset + 20, true)
+      if (offset + END_RECORD_BYTES + commentLength !== view.byteLength) {
+        continue
+      }
       return offset
     }
   }

nwparker added a commit to stablyai/orca-plugins that referenced this pull request Oct 27, 2026
Read-only viewer for .xlsx, .xlsm, .xlsb, .xls and .ods files, on Orca's
contentKind "bytes" custom editor point. Bundles SheetJS Community Edition
0.20.3 (Apache-2.0) as one offline HTML file: sheet tabs, a virtualized grid,
formulas and stored values in the cell bar, keyboard navigation, copy as TSV,
grid semantics for screen readers, and theme-aware styling.

The zip-bomb guard is adapted from stablyai/orca#29678.

Co-authored-by: nebourocket <[email protected]>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Support Office document formats (DOCX, PPTX, XLSX) as first-class file types

3 participants