pdfium-native 0.1.7 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@
3
3
  * Falls back to compiling from source if no prebuilt is available.
4
4
  *
5
5
  * Prebuilt tarball naming: pdfium-v{version}-{platform}-{arch}.tar.gz
6
+ * Musl (Alpine) naming: pdfium-v{version}-linux-musl-{arch}.tar.gz
6
7
  * Contents: build/Release/pdfium.node + build/Release/libpdfium.{dylib,so,dll}
7
8
  */
8
9
  import { existsSync, mkdirSync, createWriteStream, readFileSync, unlinkSync } from 'node:fs';
@@ -13,12 +14,38 @@ import { pipeline } from 'node:stream/promises';
13
14
  const root = join(import.meta.dirname, '..');
14
15
  const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
15
16
  const version = pkg.version;
16
- const repo = 'xonaman/nodejs-pdfium-native';
17
+
18
+ // validate version to prevent SSRF via malicious package.json
19
+ if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(version)) {
20
+ console.error(`Invalid version format: ${version}`);
21
+ process.exit(1);
22
+ }
23
+
24
+ // detect musl libc (Alpine, Void, etc.)
25
+ function isMusl() {
26
+ if (process.platform !== 'linux') return false;
27
+ try {
28
+ const ldd = execSync('ldd --version 2>&1 || true', { encoding: 'utf8' });
29
+ return ldd.toLowerCase().includes('musl');
30
+ } catch {
31
+ return (
32
+ existsSync('/lib/ld-musl-x86_64.so.1') ||
33
+ existsSync('/lib/ld-musl-aarch64.so.1') ||
34
+ existsSync('/lib/ld-musl-armhf.so.1')
35
+ );
36
+ }
37
+ }
17
38
 
18
39
  const platform = process.platform;
19
40
  const arch = process.arch;
20
- const tarName = `pdfium-v${version}-${platform}-${arch}.tar.gz`;
21
- const releaseUrl = `https://github.com/${repo}/releases/download/v${version}/${tarName}`;
41
+ const musl = isMusl();
42
+ const platformKey = musl ? `${platform}-musl` : platform;
43
+ const tarName = `pdfium-v${version}-${platformKey}-${arch}.tar.gz`;
44
+
45
+ // hardcoded origin ensures the URL can never point to an attacker-controlled host
46
+ const releaseOrigin = 'https://github.com';
47
+ const releasePath = `/xonaman/nodejs-pdfium-native/releases/download/v${version}/${tarName}`;
48
+ const releaseUrl = new URL(releasePath, releaseOrigin);
22
49
 
23
50
  const outDir = join(root, 'build', 'Release');
24
51
 
@@ -26,6 +53,9 @@ async function tryDownload() {
26
53
  console.log(`Checking for prebuilt binary: ${tarName}`);
27
54
 
28
55
  try {
56
+ if (releaseUrl.origin !== releaseOrigin) {
57
+ throw new Error(`Unexpected URL origin: ${releaseUrl.origin}`);
58
+ }
29
59
  const res = await fetch(releaseUrl, { redirect: 'follow' });
30
60
  if (!res.ok) {
31
61
  console.log(`No prebuilt binary found (HTTP ${res.status}), will compile from source.`);
package/src/document.h CHANGED
@@ -15,7 +15,7 @@ public:
15
15
  return DefineClass(
16
16
  env, "PDFiumDocument",
17
17
  {
18
- InstanceMethod<&PDFiumDocument::GetPageAsync>("getPage"),
18
+ InstanceMethod<&PDFiumDocument::GetPage>("getPage"),
19
19
  InstanceMethod<&PDFiumDocument::GetBookmarks>("getBookmarks"),
20
20
  InstanceMethod<&PDFiumDocument::Destroy>("destroy"),
21
21
  });
@@ -59,10 +59,10 @@ private:
59
59
  /**
60
60
  * Gets a page by 0-based index (async). Returns a Promise<PDFiumPage>.
61
61
  */
62
- Napi::Value GetPageAsync(const Napi::CallbackInfo &info);
62
+ Napi::Value GetPage(const Napi::CallbackInfo &info);
63
63
 
64
64
  /**
65
- * Returns the bookmark tree as a nested array.
65
+ * Returns the bookmark tree as a nested array (async).
66
66
  */
67
67
  Napi::Value GetBookmarks(const Napi::CallbackInfo &info) {
68
68
  Napi::Env env = info.Env();
@@ -70,82 +70,36 @@ private:
70
70
  if (env.IsExceptionPending())
71
71
  return env.Null();
72
72
 
73
- std::lock_guard<std::mutex> lock(g_pdfium_mutex);
74
- return BuildBookmarkArray(env, nullptr, 0);
75
- }
76
-
77
- Napi::Array BuildBookmarkArray(Napi::Env env, FPDF_BOOKMARK parent,
78
- int depth) {
79
- Napi::Array arr = Napi::Array::New(env);
80
- if (depth >= MAX_BOOKMARK_DEPTH)
81
- return arr;
82
-
83
- uint32_t idx = 0;
84
- FPDF_BOOKMARK child = FPDFBookmark_GetFirstChild(doc_, parent);
85
-
86
- while (child) {
87
- Napi::Object obj = Napi::Object::New(env);
88
-
89
- // title
90
- unsigned long titleLen = FPDFBookmark_GetTitle(child, nullptr, 0);
91
- if (titleLen > 2) {
92
- std::vector<unsigned short> titleBuf(titleLen / sizeof(unsigned short));
93
- FPDFBookmark_GetTitle(child, titleBuf.data(), titleLen);
94
- size_t charCount = titleLen / sizeof(unsigned short) - 1;
95
- obj.Set("title",
96
- Napi::String::New(
97
- env, reinterpret_cast<const char16_t *>(titleBuf.data()),
98
- charCount));
99
- } else {
100
- obj.Set("title", Napi::String::New(env, ""));
101
- }
102
-
103
- // destination page index
104
- FPDF_DEST dest = FPDFBookmark_GetDest(doc_, child);
105
- if (dest) {
106
- int pageIndex = FPDFDest_GetDestPageIndex(doc_, dest);
107
- obj.Set("pageIndex", Napi::Number::New(env, pageIndex));
108
- } else {
109
- // try action → dest
110
- FPDF_ACTION action = FPDFBookmark_GetAction(child);
111
- if (action) {
112
- FPDF_DEST actionDest = FPDFAction_GetDest(doc_, action);
113
- if (actionDest) {
114
- int pageIndex = FPDFDest_GetDestPageIndex(doc_, actionDest);
115
- obj.Set("pageIndex", Napi::Number::New(env, pageIndex));
116
- }
117
- }
118
- }
119
-
120
- // children (recursive)
121
- Napi::Array children = BuildBookmarkArray(env, child, depth + 1);
122
- if (children.Length() > 0) {
123
- obj.Set("children", children);
124
- }
125
-
126
- arr.Set(idx++, obj);
127
- child = FPDFBookmark_GetNextSibling(doc_, child);
128
- }
129
- return arr;
73
+ auto *worker = new GetBookmarksWorker(env, doc_, docAlive_);
74
+ auto promise = worker->Promise();
75
+ worker->Queue();
76
+ return promise;
130
77
  }
131
78
 
132
79
  /**
133
80
  * Closes the document and releases all resources.
134
81
  */
135
82
  Napi::Value Destroy(const Napi::CallbackInfo &info) {
83
+ CleanUp();
84
+ return info.Env().Undefined();
85
+ }
86
+
87
+ /**
88
+ * GC destructor — releases the document if the user forgot to call
89
+ * destroy().
90
+ */
91
+ void Finalize(Napi::Env /*env*/) override { CleanUp(); }
92
+
93
+ void CleanUp() {
136
94
  if (doc_) {
137
- // invalidate all pages first so they can't use dangling pointers
138
- for (auto &flag : pageAliveFlags_) {
95
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
96
+ for (auto &flag : pageAliveFlags_)
139
97
  flag->store(false);
140
- }
141
98
  pageAliveFlags_.clear();
142
99
  docAlive_->store(false);
143
-
144
- std::lock_guard<std::mutex> lock(g_pdfium_mutex);
145
100
  FPDF_CloseDocument(doc_);
146
101
  doc_ = nullptr;
147
102
  }
148
- return info.Env().Undefined();
149
103
  }
150
104
  };
151
105
 
@@ -174,6 +128,13 @@ protected:
174
128
  return;
175
129
  }
176
130
 
131
+ // bounds check inside the worker (avoids blocking the main thread)
132
+ int numPages = FPDF_GetPageCount(doc_);
133
+ if (pageIndex_ < 0 || pageIndex_ >= numPages) {
134
+ SetError("Page index out of range");
135
+ return;
136
+ }
137
+
177
138
  page_ = FPDF_LoadPage(doc_, pageIndex_);
178
139
  if (!page_) {
179
140
  SetError("Failed to load page");
@@ -188,7 +149,7 @@ protected:
188
149
  Napi::Env env = Env();
189
150
  Napi::Object pageObj = PDFiumDocument::pageConstructor.New({});
190
151
  PDFiumPage *pageWrapper = PDFiumPage::Unwrap(pageObj);
191
- pageWrapper->SetPage(page_, doc_, pageIndex_);
152
+ pageWrapper->SetPage(page_, doc_, pageIndex_, width_, height_);
192
153
  pageWrapper->SetDocAlive(docAlive_);
193
154
 
194
155
  // register the page's alive flag with the document for invalidation
@@ -222,9 +183,8 @@ private:
222
183
  int objectCount_ = 0;
223
184
  };
224
185
 
225
- // deferred definition of GetPageAsync (needs GetPageWorker)
226
- inline Napi::Value
227
- PDFiumDocument::GetPageAsync(const Napi::CallbackInfo &info) {
186
+ // deferred definition of GetPage (needs GetPageWorker)
187
+ inline Napi::Value PDFiumDocument::GetPage(const Napi::CallbackInfo &info) {
228
188
  Napi::Env env = info.Env();
229
189
  EnsureOpen(env);
230
190
  if (env.IsExceptionPending())
@@ -238,15 +198,6 @@ PDFiumDocument::GetPageAsync(const Napi::CallbackInfo &info) {
238
198
 
239
199
  int pageIndex = info[0].As<Napi::Number>().Int32Value();
240
200
 
241
- // FPDF_GetPageCount is not thread-safe — acquire mutex
242
- std::lock_guard<std::mutex> lock(g_pdfium_mutex);
243
- int numPages = FPDF_GetPageCount(doc_);
244
- if (pageIndex < 0 || pageIndex >= numPages) {
245
- Napi::RangeError::New(env, "Page index out of range")
246
- .ThrowAsJavaScriptException();
247
- return env.Null();
248
- }
249
-
250
201
  auto *worker = new GetPageWorker(env, doc_, pageIndex, this, docAlive_);
251
202
  auto promise = worker->Promise();
252
203
  worker->Queue();
@@ -1,11 +1,12 @@
1
1
  #pragma once
2
2
 
3
+ #include <atomic>
3
4
  #include <mutex>
4
5
  #include <napi.h>
5
6
 
6
7
  #include "fpdfview.h"
7
8
 
8
- inline bool g_initialized = false;
9
+ inline std::atomic<bool> g_initialized{false};
9
10
 
10
11
  // PDFium is not thread-safe — serialize all calls through a global mutex.
11
12
  // This unblocks the Node.js event loop while waiting for the lock.