pdf-probe 0.0.0-stage → 0.1.0
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.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +22 -0
- package/README.md +61 -2
- package/dist/index.d.ts +58 -0
- package/dist/index.js +231 -0
- package/dist/pdf_probe.wasm +0 -0
- package/package.json +44 -4
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The pdf-probe authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pdf-probe
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
How many pages does an untrusted PDF have, and how big is each page? A small reader that answers only those two questions, and **fails closed**: a file it cannot read with confidence is reported as a failure, never guessed at. It does not render, extract text or decode images.
|
|
4
|
+
|
|
5
|
+
> **Status: version 0.1, pre-1.0.** The parser matches pdf.js on pdf.js's own 987 test PDFs (983 identical, 4 intended differences that are all refusals, 0 different answers), but it is young, has not been independently audited, and the API may change. See the [project README](https://github.com/polybot-platform/pdf-probe#readme) for the evidence and what is not done.
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import { createProbe } from 'pdf-probe'
|
|
9
|
+
|
|
10
|
+
const probe = await createProbe() // once: loading is the expensive part
|
|
11
|
+
const result = probe.check(bytes, { maxPages: 200 }) // bytes: a Uint8Array or Buffer
|
|
12
|
+
|
|
13
|
+
switch (result.status) {
|
|
14
|
+
case 'ok': // result.pages, result.sizes: [[width, height], ...] in points (1/72 inch)
|
|
15
|
+
case 'tooManyPages': // result.pages
|
|
16
|
+
case 'empty': // well-formed, no pages
|
|
17
|
+
case 'unparseable': // result.reason: damaged, unsupported or password-protected
|
|
18
|
+
case 'limitExceeded': // result.limit: 'inputBytes', 'work', 'objects', 'xrefSections' or 'decompressed'
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
A damaged or password-protected PDF is a **result**, not an exception, and so is a limit. `check` throws only for a bad call (a wrong argument type, an option out of range, a closed probe).
|
|
23
|
+
|
|
24
|
+
## Engines
|
|
25
|
+
|
|
26
|
+
Two engines give the same answers, byte for byte, on the whole test corpus.
|
|
27
|
+
|
|
28
|
+
| | Where | Memory in Bun (measured locally) |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `native` | Bun only, through `bun:ffi` | about +3 MB at idle |
|
|
31
|
+
| `wasm` | Bun, Node 20+, Deno, browsers, workers (no browser run yet) | about +15 MB at idle in Bun |
|
|
32
|
+
|
|
33
|
+
`createProbe()` uses `engine: 'auto'`: the native library under Bun when one is found, WebAssembly otherwise. **This package ships WebAssembly only**; the native library is built from the [repository](https://github.com/polybot-platform/pdf-probe) and passed in by path. Ask for one with `{ engine: 'native' }` or `{ engine: 'wasm' }`; `native` throws a clear error if it cannot be loaded.
|
|
34
|
+
|
|
35
|
+
**No native library is included.** Build one with `cargo build --release -p pdf-probe-ffi` and give its path with the `nativeLibrary` option or `PDF_PROBE_NATIVE_LIBRARY`; the package also looks in `native/<platform>-<arch>/` next to itself. Anywhere without one, `auto` uses WebAssembly.
|
|
36
|
+
|
|
37
|
+
## `bun build --compile`
|
|
38
|
+
|
|
39
|
+
A compiled binary has no `node_modules` on disk, so embed the engine files and pass their paths:
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
import { createProbe } from 'pdf-probe'
|
|
43
|
+
import wasmFile from 'pdf-probe/pdf_probe.wasm' with { type: 'file' }
|
|
44
|
+
const probe = await createProbe({ wasm: wasmFile })
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
This was tried with a binary built from the installed package and run from another directory. A native library you built yourself can be embedded the same way and passed as `nativeLibrary`.
|
|
48
|
+
|
|
49
|
+
## Things to know
|
|
50
|
+
|
|
51
|
+
- **Passwords.** Only an empty user password is tried (RC4, AES-128, AES-256). A file that needs a password is `unparseable`.
|
|
52
|
+
- **Page cap.** `maxPages` (default 10,000, at most 1,000,000) bounds the work and the answer. More pages than that is `tooManyPages`.
|
|
53
|
+
- **Input size.** `maxInputBytes` (default 10 MiB, at most 4,294,967,295) is checked first: a larger input is `limitExceeded` (`inputBytes`) before anything is parsed.
|
|
54
|
+
- **Work budget.** `maxWork` (default about 1.07 billion units, roughly a second) bounds the total work of one call; running out is `limitExceeded` (`work`). A unit is about a nanosecond of work, but the count is deterministic: the same input costs the same everywhere. It catches work that is large only in total, such as one object re-parsed for every page (a 1 MB file can cost minutes without it). It is rounded up to a multiple of one million.
|
|
55
|
+
- **Other limits.** Object count, cross-reference chain length and decompressed size are bounded inside the library with fixed defaults; hitting one is `limitExceeded` naming it. They are not options.
|
|
56
|
+
- **A panic** cannot take the host down: the native library catches it at its boundary and reports `panic`; the WebAssembly engine sees a trap, discards the instance and reports `panic`. None has been found by fuzzing so far.
|
|
57
|
+
- **WebAssembly memory only grows.** The WebAssembly engine replaces its instance when its memory passes `recycleAboveBytes` (default 32 MiB).
|
|
58
|
+
- **Page sizes** are the effective size: MediaBox intersected with CropBox, with `/Rotate` and `/UserUnit` applied. A size limit is your policy, not the library's.
|
|
59
|
+
|
|
60
|
+
## Licence
|
|
61
|
+
|
|
62
|
+
MIT OR Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export type PageSize = [width: number, height: number]
|
|
2
|
+
|
|
3
|
+
export type ProbeResult =
|
|
4
|
+
| { status: 'ok'; pages: number; sizes: PageSize[] }
|
|
5
|
+
| { status: 'unparseable'; reason: string }
|
|
6
|
+
| { status: 'empty' }
|
|
7
|
+
| { status: 'tooManyPages'; pages: number }
|
|
8
|
+
| { status: 'limitExceeded'; limit: LimitName }
|
|
9
|
+
| { status: 'panic'; reason: string }
|
|
10
|
+
|
|
11
|
+
/** Which limit was hit. */
|
|
12
|
+
export type LimitName = 'inputBytes' | 'work' | 'objects' | 'xrefSections' | 'decompressed'
|
|
13
|
+
|
|
14
|
+
/** `auto` uses the native library under Bun when one is found for this platform, and WebAssembly otherwise. */
|
|
15
|
+
export type Engine = 'auto' | 'native' | 'wasm'
|
|
16
|
+
|
|
17
|
+
export interface CreateOptions {
|
|
18
|
+
engine?: Engine
|
|
19
|
+
/** A path to the native shared library. Default: `PDF_PROBE_NATIVE_LIBRARY`, then the package's own `native/`. */
|
|
20
|
+
nativeLibrary?: string
|
|
21
|
+
/** The WebAssembly module: bytes, a compiled module, a URL or a path. Default: the file shipped in the package. */
|
|
22
|
+
wasm?: BufferSource | WebAssembly.Module | URL | string
|
|
23
|
+
/** WebAssembly memory only grows; above this many bytes the instance is replaced. Default 32 MiB. */
|
|
24
|
+
recycleAboveBytes?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CheckOptions {
|
|
28
|
+
/** More pages than this is reported as `tooManyPages`. At most 1,000,000. Default 10,000. */
|
|
29
|
+
maxPages?: number
|
|
30
|
+
/**
|
|
31
|
+
* The largest input accepted, in bytes. A larger one is `limitExceeded` (`inputBytes`) before anything is
|
|
32
|
+
* parsed. At most 4,294,967,295. Default 10 MiB.
|
|
33
|
+
*/
|
|
34
|
+
maxInputBytes?: number
|
|
35
|
+
/**
|
|
36
|
+
* A budget of work units for the call; running out is `limitExceeded` (`work`). A unit is roughly a
|
|
37
|
+
* nanosecond of work on a modern core, and the count is the same on every machine, so the same input always
|
|
38
|
+
* costs the same. Rounded up to a multiple of one million. Default about 1.07 billion (roughly a second).
|
|
39
|
+
* It catches work that is large only in total, such as one object re-parsed for every page.
|
|
40
|
+
*/
|
|
41
|
+
maxWork?: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface Probe {
|
|
45
|
+
/** The engine in use. */
|
|
46
|
+
readonly engine: 'native' | 'wasm'
|
|
47
|
+
/**
|
|
48
|
+
* Reads the page count and each page's size, in points. A damaged, encrypted or otherwise unreadable PDF is
|
|
49
|
+
* a result (`unparseable`, `empty`, `tooManyPages`, `limitExceeded`), not an exception. It throws only for
|
|
50
|
+
* a bad call.
|
|
51
|
+
*/
|
|
52
|
+
check(pdf: Uint8Array | ArrayBuffer, options?: CheckOptions): ProbeResult
|
|
53
|
+
/** Releases the native library. A probe cannot be used afterwards. */
|
|
54
|
+
close(): void
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Creates a probe. Do it once and reuse it: loading is the expensive part, and checks are fast. */
|
|
58
|
+
export function createProbe(options?: CreateOptions): Promise<Probe>
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
|
|
4
|
+
// ../bindings/result.ts
|
|
5
|
+
var ABI_VERSION = 2;
|
|
6
|
+
var HEADER = 16;
|
|
7
|
+
var STATUS = ["ok", "unparseable", "empty", "tooManyPages", "panic", "limitExceeded"];
|
|
8
|
+
function bufferSizeFor(maxPages) {
|
|
9
|
+
return HEADER + 16 * Math.min(maxPages, 1e4) + 256;
|
|
10
|
+
}
|
|
11
|
+
function decodeResult(buf, length) {
|
|
12
|
+
const view = new DataView(buf.buffer, buf.byteOffset, length);
|
|
13
|
+
const code = view.getUint32(0, true);
|
|
14
|
+
const status = STATUS[code];
|
|
15
|
+
const pages = view.getUint32(4, true);
|
|
16
|
+
const count = view.getUint32(8, true);
|
|
17
|
+
const reasonLength = view.getUint32(12, true);
|
|
18
|
+
const reason = () => new TextDecoder().decode(buf.subarray(HEADER + 16 * count, HEADER + 16 * count + reasonLength));
|
|
19
|
+
switch (status) {
|
|
20
|
+
case "ok": {
|
|
21
|
+
const sizes = [];
|
|
22
|
+
for (let i = 0;i < count; i++) {
|
|
23
|
+
sizes.push([view.getFloat64(HEADER + 16 * i, true), view.getFloat64(HEADER + 16 * i + 8, true)]);
|
|
24
|
+
}
|
|
25
|
+
return { status, pages, sizes };
|
|
26
|
+
}
|
|
27
|
+
case "unparseable":
|
|
28
|
+
case "panic":
|
|
29
|
+
return { status, reason: reason() };
|
|
30
|
+
case "tooManyPages":
|
|
31
|
+
return { status, pages };
|
|
32
|
+
case "limitExceeded":
|
|
33
|
+
return { status, limit: reason() };
|
|
34
|
+
case "empty":
|
|
35
|
+
return { status };
|
|
36
|
+
default:
|
|
37
|
+
throw new Error(`unknown status ${code}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ../bindings/bun.ts
|
|
42
|
+
async function libraryFileName() {
|
|
43
|
+
const { suffix } = await import("bun:ffi");
|
|
44
|
+
return `${suffix === "dll" ? "" : "lib"}pdf_probe_ffi.${suffix}`;
|
|
45
|
+
}
|
|
46
|
+
async function defaultLibraryPath() {
|
|
47
|
+
return new URL(`../target/release/${await libraryFileName()}`, import.meta.url).pathname;
|
|
48
|
+
}
|
|
49
|
+
async function loadPdfProbe(path) {
|
|
50
|
+
const { dlopen, FFIType, ptr } = await import("bun:ffi");
|
|
51
|
+
const lib = dlopen(path ?? await defaultLibraryPath(), {
|
|
52
|
+
pdf_probe_abi_version: { args: [], returns: FFIType.u32 },
|
|
53
|
+
pdf_probe_check: {
|
|
54
|
+
args: [FFIType.ptr, FFIType.u64, FFIType.u32, FFIType.u32, FFIType.u32, FFIType.ptr, FFIType.u64],
|
|
55
|
+
returns: FFIType.i32
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
const version = lib.symbols.pdf_probe_abi_version();
|
|
59
|
+
if (version !== ABI_VERSION)
|
|
60
|
+
throw new Error(`pdf-probe ABI ${version}, expected ${ABI_VERSION}`);
|
|
61
|
+
let out = new Uint8Array(HEADER + 256);
|
|
62
|
+
function check(bytes, maxPages, maxInputBytes = 0, maxWorkMillions = 0) {
|
|
63
|
+
const want = bufferSizeFor(maxPages);
|
|
64
|
+
if (out.length < want)
|
|
65
|
+
out = new Uint8Array(want);
|
|
66
|
+
const call = () => lib.symbols.pdf_probe_check(bytes.length ? ptr(bytes) : null, bytes.length, maxPages, maxInputBytes, maxWorkMillions, ptr(out), out.length);
|
|
67
|
+
let needed = call();
|
|
68
|
+
if (needed > out.length) {
|
|
69
|
+
out = new Uint8Array(needed);
|
|
70
|
+
needed = call();
|
|
71
|
+
}
|
|
72
|
+
if (needed < 0)
|
|
73
|
+
throw new Error(`pdf_probe_check failed with ${needed}`);
|
|
74
|
+
return decodeResult(out, needed);
|
|
75
|
+
}
|
|
76
|
+
return { check, close: () => lib.close() };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ../bindings/wasm.ts
|
|
80
|
+
function loadPdfProbeWasm(wasm, options = {}) {
|
|
81
|
+
const recycleAboveBytes = options.recycleAboveBytes ?? 32 * 1024 * 1024;
|
|
82
|
+
const module = wasm instanceof WebAssembly.Module ? wasm : new WebAssembly.Module(wasm);
|
|
83
|
+
const instantiate = () => {
|
|
84
|
+
const x = new WebAssembly.Instance(module, {}).exports;
|
|
85
|
+
if (x.pdf_probe_abi_version() !== ABI_VERSION)
|
|
86
|
+
throw new Error("pdf-probe wasm ABI mismatch");
|
|
87
|
+
return x;
|
|
88
|
+
};
|
|
89
|
+
let x = instantiate();
|
|
90
|
+
let recycles = 0;
|
|
91
|
+
function check(bytes, maxPages, maxInputBytes = 0, maxWorkMillions = 0) {
|
|
92
|
+
let outCap = bufferSizeFor(maxPages);
|
|
93
|
+
let inPtr = 0;
|
|
94
|
+
let outPtr = 0;
|
|
95
|
+
try {
|
|
96
|
+
inPtr = x.pdf_probe_alloc(bytes.length);
|
|
97
|
+
new Uint8Array(x.memory.buffer, inPtr, bytes.length).set(bytes);
|
|
98
|
+
outPtr = x.pdf_probe_alloc(outCap);
|
|
99
|
+
let needed = x.pdf_probe_check(inPtr, bytes.length, maxPages, maxInputBytes, maxWorkMillions, outPtr, outCap);
|
|
100
|
+
if (needed > outCap) {
|
|
101
|
+
x.pdf_probe_free(outPtr, outCap);
|
|
102
|
+
outCap = needed;
|
|
103
|
+
outPtr = x.pdf_probe_alloc(outCap);
|
|
104
|
+
needed = x.pdf_probe_check(inPtr, bytes.length, maxPages, maxInputBytes, maxWorkMillions, outPtr, outCap);
|
|
105
|
+
}
|
|
106
|
+
if (needed < 0)
|
|
107
|
+
throw new Error(`pdf_probe_check failed with ${needed}`);
|
|
108
|
+
const result = decodeResult(new Uint8Array(x.memory.buffer, outPtr, needed).slice(), needed);
|
|
109
|
+
x.pdf_probe_free(outPtr, outCap);
|
|
110
|
+
x.pdf_probe_free(inPtr, bytes.length);
|
|
111
|
+
if (x.memory.buffer.byteLength > recycleAboveBytes) {
|
|
112
|
+
x = instantiate();
|
|
113
|
+
recycles++;
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (error instanceof WebAssembly.RuntimeError) {
|
|
118
|
+
x = instantiate();
|
|
119
|
+
return { status: "panic", reason: error.message };
|
|
120
|
+
}
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
check,
|
|
126
|
+
memoryBytes: () => x.memory.buffer.byteLength,
|
|
127
|
+
recycleCount: () => recycles,
|
|
128
|
+
exports: () => x
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/index.ts
|
|
133
|
+
var DEFAULT_MAX_PAGES = 1e4;
|
|
134
|
+
var MAX_PAGES_CEILING = 1e6;
|
|
135
|
+
var U32_MAX = 4294967295;
|
|
136
|
+
var isBun = () => typeof globalThis.Bun !== "undefined";
|
|
137
|
+
var isNodeLike = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
138
|
+
function prepare(pdf, options) {
|
|
139
|
+
const bytes = pdf instanceof Uint8Array ? pdf : pdf instanceof ArrayBuffer ? new Uint8Array(pdf) : undefined;
|
|
140
|
+
if (!bytes)
|
|
141
|
+
throw new TypeError("pdf must be a Uint8Array (a Buffer is one) or an ArrayBuffer");
|
|
142
|
+
const maxPages = options?.maxPages ?? DEFAULT_MAX_PAGES;
|
|
143
|
+
if (!Number.isInteger(maxPages) || maxPages < 0 || maxPages > MAX_PAGES_CEILING) {
|
|
144
|
+
throw new RangeError(`maxPages must be an integer from 0 to ${MAX_PAGES_CEILING}`);
|
|
145
|
+
}
|
|
146
|
+
const maxInputBytes = options?.maxInputBytes ?? 0;
|
|
147
|
+
if (!Number.isInteger(maxInputBytes) || maxInputBytes < 0 || maxInputBytes > U32_MAX || options?.maxInputBytes !== undefined && maxInputBytes < 1) {
|
|
148
|
+
throw new RangeError(`maxInputBytes must be an integer from 1 to ${U32_MAX}`);
|
|
149
|
+
}
|
|
150
|
+
const maxWork = options?.maxWork;
|
|
151
|
+
if (maxWork !== undefined && (!Number.isInteger(maxWork) || maxWork < 1 || Math.ceil(maxWork / 1e6) > U32_MAX)) {
|
|
152
|
+
throw new RangeError("maxWork must be an integer of at least 1 (and at most about 4.29e15)");
|
|
153
|
+
}
|
|
154
|
+
return [bytes, maxPages, maxInputBytes, maxWork === undefined ? 0 : Math.ceil(maxWork / 1e6)];
|
|
155
|
+
}
|
|
156
|
+
function wrap(engine, run, release) {
|
|
157
|
+
let closed = false;
|
|
158
|
+
return {
|
|
159
|
+
engine,
|
|
160
|
+
check(pdf, options) {
|
|
161
|
+
if (closed)
|
|
162
|
+
throw new Error("this probe is closed");
|
|
163
|
+
return run(...prepare(pdf, options));
|
|
164
|
+
},
|
|
165
|
+
close() {
|
|
166
|
+
if (!closed)
|
|
167
|
+
release();
|
|
168
|
+
closed = true;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
async function findNativeLibrary(explicit) {
|
|
173
|
+
const bun = globalThis.Bun;
|
|
174
|
+
const candidates = [
|
|
175
|
+
explicit,
|
|
176
|
+
process.env.PDF_PROBE_NATIVE_LIBRARY,
|
|
177
|
+
fileURLToPath(new URL(`../native/${process.platform}-${process.arch}/${await libraryFileName()}`, import.meta.url))
|
|
178
|
+
];
|
|
179
|
+
for (const path of candidates) {
|
|
180
|
+
if (path && await bun?.file(path).exists())
|
|
181
|
+
return path;
|
|
182
|
+
if (path && path === explicit)
|
|
183
|
+
return path;
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
async function wasmSource(source) {
|
|
188
|
+
if (source instanceof WebAssembly.Module)
|
|
189
|
+
return source;
|
|
190
|
+
if (source && typeof source === "object" && !(source instanceof URL))
|
|
191
|
+
return source;
|
|
192
|
+
const url = source instanceof URL ? source : typeof source === "string" ? /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^[a-z]:[\\/]/i.test(source) ? new URL(source) : undefined : new URL("./pdf_probe.wasm", import.meta.url);
|
|
193
|
+
if (isNodeLike() && (url === undefined || url.protocol === "file:")) {
|
|
194
|
+
const { readFile } = await import("node:fs/promises");
|
|
195
|
+
return await readFile(url ? fileURLToPath(url) : source);
|
|
196
|
+
}
|
|
197
|
+
const response = await fetch(url);
|
|
198
|
+
if (!response.ok)
|
|
199
|
+
throw new Error(`could not load the WebAssembly module: ${response.status} ${response.statusText}`);
|
|
200
|
+
return await response.arrayBuffer();
|
|
201
|
+
}
|
|
202
|
+
async function createProbe(options = {}) {
|
|
203
|
+
const engine = options.engine ?? "auto";
|
|
204
|
+
if (engine !== "auto" && engine !== "native" && engine !== "wasm") {
|
|
205
|
+
throw new TypeError(`engine must be 'auto', 'native' or 'wasm', not ${String(engine)}`);
|
|
206
|
+
}
|
|
207
|
+
if (engine !== "wasm") {
|
|
208
|
+
if (!isBun()) {
|
|
209
|
+
if (engine === "native")
|
|
210
|
+
throw new Error("the 'native' engine needs Bun (it loads the library with bun:ffi)");
|
|
211
|
+
} else {
|
|
212
|
+
const path = await findNativeLibrary(options.nativeLibrary);
|
|
213
|
+
if (path) {
|
|
214
|
+
try {
|
|
215
|
+
const lib = await loadPdfProbe(path);
|
|
216
|
+
return wrap("native", lib.check, lib.close);
|
|
217
|
+
} catch (cause) {
|
|
218
|
+
if (engine === "native")
|
|
219
|
+
throw new Error(`could not load the native library at ${path}`, { cause });
|
|
220
|
+
}
|
|
221
|
+
} else if (engine === "native") {
|
|
222
|
+
throw new Error(`no native library for ${process.platform}-${process.arch}: set nativeLibrary or PDF_PROBE_NATIVE_LIBRARY`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const wasm = loadPdfProbeWasm(await wasmSource(options.wasm), { recycleAboveBytes: options.recycleAboveBytes });
|
|
227
|
+
return wrap("wasm", wasm.check, () => {});
|
|
228
|
+
}
|
|
229
|
+
export {
|
|
230
|
+
createProbe
|
|
231
|
+
};
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pdf-probe",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A small, fail-closed reader that answers two questions about an untrusted PDF: how many pages, and how big is each page? WebAssembly, for Node, Bun and browsers.",
|
|
5
|
+
"license": "MIT OR Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/polybot-platform/pdf-probe.git"
|
|
9
|
+
},
|
|
10
|
+
"keywords": [
|
|
11
|
+
"pdf",
|
|
12
|
+
"page-count",
|
|
13
|
+
"page-size",
|
|
14
|
+
"wasm",
|
|
15
|
+
"ffi",
|
|
16
|
+
"untrusted-input"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./pdf_probe.wasm": "./dist/pdf_probe.wasm",
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE-MIT",
|
|
34
|
+
"LICENSE-APACHE"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "bun run build.ts"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/polybot-platform/pdf-probe#readme",
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/polybot-platform/pdf-probe/issues"
|
|
45
|
+
}
|
|
46
|
+
}
|