@patrickdk77/pdf-defuse 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 +21 -0
- package/README.md +323 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +390 -0
- package/dist/crypto.d.ts +51 -0
- package/dist/crypto.js +404 -0
- package/dist/data-plugins.d.ts +28 -0
- package/dist/data-plugins.js +525 -0
- package/dist/document.d.ts +191 -0
- package/dist/document.js +1403 -0
- package/dist/engine.d.ts +16 -0
- package/dist/engine.js +392 -0
- package/dist/filters.d.ts +27 -0
- package/dist/filters.js +616 -0
- package/dist/findings.d.ts +24 -0
- package/dist/findings.js +183 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +42 -0
- package/dist/index.mjs +3 -0
- package/dist/io.d.ts +81 -0
- package/dist/io.js +414 -0
- package/dist/objects.d.ts +52 -0
- package/dist/objects.js +178 -0
- package/dist/parser.d.ts +70 -0
- package/dist/parser.js +534 -0
- package/dist/plugins.d.ts +13 -0
- package/dist/plugins.js +56 -0
- package/dist/score.d.ts +17 -0
- package/dist/score.js +63 -0
- package/dist/sniff.d.ts +15 -0
- package/dist/sniff.js +118 -0
- package/dist/types.d.ts +294 -0
- package/dist/types.js +143 -0
- package/dist/uri.d.ts +29 -0
- package/dist/uri.js +150 -0
- package/dist/walker.d.ts +302 -0
- package/dist/walker.js +2914 -0
- package/dist/writer.d.ts +6 -0
- package/dist/writer.js +112 -0
- package/package.json +86 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
|
+
if (k2 === undefined) k2 = k;
|
|
5
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
6
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
7
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
8
|
+
}
|
|
9
|
+
Object.defineProperty(o, k2, desc);
|
|
10
|
+
}) : (function(o, m, k, k2) {
|
|
11
|
+
if (k2 === undefined) k2 = k;
|
|
12
|
+
o[k2] = m[k];
|
|
13
|
+
}));
|
|
14
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
15
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
16
|
+
}) : function(o, v) {
|
|
17
|
+
o["default"] = v;
|
|
18
|
+
});
|
|
19
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
20
|
+
var ownKeys = function(o) {
|
|
21
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
22
|
+
var ar = [];
|
|
23
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
24
|
+
return ar;
|
|
25
|
+
};
|
|
26
|
+
return ownKeys(o);
|
|
27
|
+
};
|
|
28
|
+
return function (mod) {
|
|
29
|
+
if (mod && mod.__esModule) return mod;
|
|
30
|
+
var result = {};
|
|
31
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
32
|
+
__setModuleDefault(result, mod);
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
})();
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
exports.main = main;
|
|
38
|
+
const fs = __importStar(require("node:fs"));
|
|
39
|
+
const fsp = __importStar(require("node:fs/promises"));
|
|
40
|
+
const path = __importStar(require("node:path"));
|
|
41
|
+
const promises_1 = require("node:stream/promises");
|
|
42
|
+
const node_url_1 = require("node:url");
|
|
43
|
+
const data_plugins_1 = require("./data-plugins");
|
|
44
|
+
const document_1 = require("./document");
|
|
45
|
+
const engine_1 = require("./engine");
|
|
46
|
+
const io_1 = require("./io");
|
|
47
|
+
const plugins_1 = require("./plugins");
|
|
48
|
+
const USAGE = `Usage:
|
|
49
|
+
pdf-defuse inspect <file> [options]
|
|
50
|
+
pdf-defuse defuse <in> <out> [options]
|
|
51
|
+
|
|
52
|
+
Options:
|
|
53
|
+
--password-file <path> read the password from a file, or set PDF_DEFUSE_PASSWORD
|
|
54
|
+
--plugin <module> load plugins from a file or an installed package, repeatable
|
|
55
|
+
--config <module> load a whole options object, repeatable; the other options apply on top
|
|
56
|
+
--keep-type <type> keep contained files of this MIME type or file extension unchanged, repeatable
|
|
57
|
+
--defuse-attached-pdfs defuse PDFs attached inside the PDF
|
|
58
|
+
--scrub-attached-csv keep attached CSV files, escaping cells a spreadsheet would run as formulas
|
|
59
|
+
--scrub-attached-tsv the same for tab-separated files
|
|
60
|
+
--keep-attached-json keep attached JSON files that parse
|
|
61
|
+
--csv-formulas <mode> escape (default), keep or remove, for the CSV and TSV options
|
|
62
|
+
--strip-metadata
|
|
63
|
+
--limit <name>=<value> fileSize, objects, decompressedBytes, nestingDepth, timeMs; sizes accept kb, mb, gb
|
|
64
|
+
--json print the result as JSON
|
|
65
|
+
|
|
66
|
+
Use - for stdin or stdout.
|
|
67
|
+
Exit codes: 0 clean, 1 stripped or strippable, 2 rejected, 3 usage or I/O error.`;
|
|
68
|
+
class UsageError extends Error {
|
|
69
|
+
}
|
|
70
|
+
function parseSize(v) {
|
|
71
|
+
const m = /^(\d+(?:\.\d+)?)\s*(b|kb|k|mb|m|gb|g)?$/i.exec(v.trim());
|
|
72
|
+
if (!m)
|
|
73
|
+
throw new UsageError(`Bad size "${v}"`);
|
|
74
|
+
const mult = { b: 1, k: 1024, kb: 1024, m: 1024 ** 2, mb: 1024 ** 2, g: 1024 ** 3, gb: 1024 ** 3 };
|
|
75
|
+
return Math.round(Number(m[1]) * mult[(m[2] ?? 'b').toLowerCase()]);
|
|
76
|
+
}
|
|
77
|
+
// A real dynamic import. TypeScript would compile import() to require() for CommonJS output,
|
|
78
|
+
// and require() cannot load ES modules or file URLs.
|
|
79
|
+
const dynamicImport = new Function('specifier', 'return import(specifier)');
|
|
80
|
+
/** Reads `key` from `v` the way `v?.[key]` does, for a value whose shape is not known. */
|
|
81
|
+
function prop(v, key) {
|
|
82
|
+
return (typeof v === 'object' && v !== null) || typeof v === 'function' ? v[key] : undefined;
|
|
83
|
+
}
|
|
84
|
+
const isObject = (v) => typeof v === 'object' && v !== null;
|
|
85
|
+
async function loadModule(spec) {
|
|
86
|
+
// A bare name ending in .js can be a file in the working directory or a package with that name. The file wins.
|
|
87
|
+
const looksLikePath = spec.startsWith('.') || path.isAbsolute(spec) || (/\.(c|m)?js$/.test(spec) && fs.statSync(spec, { throwIfNoEntry: false })?.isFile() === true);
|
|
88
|
+
let resolved;
|
|
89
|
+
if (looksLikePath)
|
|
90
|
+
resolved = path.resolve(process.cwd(), spec);
|
|
91
|
+
else {
|
|
92
|
+
try {
|
|
93
|
+
resolved = require.resolve(spec, { paths: [process.cwd()] });
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
// require.resolve applies only the "require" condition, so a package that exports only "import" ends up here.
|
|
97
|
+
if (e.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED')
|
|
98
|
+
throw e;
|
|
99
|
+
const name = spec
|
|
100
|
+
.split('/')
|
|
101
|
+
.slice(0, spec.startsWith('@') ? 2 : 1)
|
|
102
|
+
.join('/');
|
|
103
|
+
const subpath = `.${spec.slice(name.length)}`;
|
|
104
|
+
for (let dir = process.cwd(); resolved === undefined; dir = path.dirname(dir)) {
|
|
105
|
+
const pkg = path.join(dir, 'node_modules', name);
|
|
106
|
+
if (fs.existsSync(path.join(pkg, 'package.json'))) {
|
|
107
|
+
const exp = JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf8')).exports;
|
|
108
|
+
const isMap = isObject(exp) && Object.keys(exp).some(k => k.startsWith('.'));
|
|
109
|
+
let target;
|
|
110
|
+
let match;
|
|
111
|
+
if (!isMap)
|
|
112
|
+
target = subpath === '.' ? exp : undefined;
|
|
113
|
+
else if (Object.hasOwn(exp, subpath) && !subpath.includes('*'))
|
|
114
|
+
target = exp[subpath];
|
|
115
|
+
else {
|
|
116
|
+
// A pattern key holds one "*". Node prefers the longest text before the "*", then the longest key, and puts
|
|
117
|
+
// what the "*" matched into the target.
|
|
118
|
+
let best = '';
|
|
119
|
+
for (const k of Object.keys(exp)) {
|
|
120
|
+
const star = k.indexOf('*');
|
|
121
|
+
const trailer = k.slice(star + 1);
|
|
122
|
+
if (star < 0 || trailer.includes('*') || !subpath.startsWith(k.slice(0, star)) || subpath.length === star)
|
|
123
|
+
continue;
|
|
124
|
+
if (trailer && (!subpath.endsWith(trailer) || subpath.length < k.length))
|
|
125
|
+
continue;
|
|
126
|
+
if (!best || star > best.indexOf('*') || (star === best.indexOf('*') && k.length > best.length))
|
|
127
|
+
best = k;
|
|
128
|
+
}
|
|
129
|
+
if (best) {
|
|
130
|
+
target = exp[best];
|
|
131
|
+
match = subpath.slice(best.indexOf('*'), subpath.length - (best.length - best.indexOf('*') - 1));
|
|
132
|
+
// Node refuses a match that would step outside the pattern's directory.
|
|
133
|
+
if (match.split(/[/\\]/).some(s => s === '' || s === '.' || s === '..' || s.toLowerCase() === 'node_modules'))
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// Node takes the first condition it supports, in the order the package lists them.
|
|
138
|
+
while (isObject(target) && !Array.isArray(target))
|
|
139
|
+
target = target[Object.keys(target).find(k => k === 'node' || k === 'import' || k === 'default') ?? ''];
|
|
140
|
+
if (typeof target !== 'string')
|
|
141
|
+
throw e;
|
|
142
|
+
resolved = path.resolve(pkg, match === undefined ? target : target.replaceAll('*', match));
|
|
143
|
+
}
|
|
144
|
+
else if (path.dirname(dir) === dir)
|
|
145
|
+
throw e;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return dynamicImport((0, node_url_1.pathToFileURL)(resolved).href);
|
|
150
|
+
}
|
|
151
|
+
function pluginsFrom(mod) {
|
|
152
|
+
// import() gives a CommonJS module a default export holding module.exports, so the named exports come first.
|
|
153
|
+
const value = prop(mod, 'plugins') ?? prop(prop(mod, 'default'), 'plugins') ?? prop(mod, 'plugin') ?? prop(prop(mod, 'default'), 'plugin') ?? prop(mod, 'default');
|
|
154
|
+
const list = Array.isArray(value) ? value : [value];
|
|
155
|
+
for (const p of list)
|
|
156
|
+
if (!p || (prop(p, 'kind') !== 'file' && prop(p, 'kind') !== 'script'))
|
|
157
|
+
throw new UsageError('A plugin module must export plugins with kind "file" or "script"');
|
|
158
|
+
// The loop above checked each entry's kind, which is as far as a plugin's shape can be checked here.
|
|
159
|
+
return list;
|
|
160
|
+
}
|
|
161
|
+
async function parse(argv) {
|
|
162
|
+
const [command, ...rest] = argv;
|
|
163
|
+
if (command !== 'inspect' && command !== 'defuse')
|
|
164
|
+
throw new UsageError(command ? `Unknown command "${command}"` : 'No command');
|
|
165
|
+
const positional = [];
|
|
166
|
+
// Every --config module goes in first and the flags apply on top, wherever they sit on the command line.
|
|
167
|
+
const options = {};
|
|
168
|
+
const ordered = [];
|
|
169
|
+
const limits = {};
|
|
170
|
+
let stripMetadata = false;
|
|
171
|
+
let json = false;
|
|
172
|
+
const delimited = {};
|
|
173
|
+
let password = process.env.PDF_DEFUSE_PASSWORD;
|
|
174
|
+
for (let i = 0; i < rest.length; i++) {
|
|
175
|
+
const a = rest[i];
|
|
176
|
+
const next = () => {
|
|
177
|
+
const v = rest[++i];
|
|
178
|
+
if (v === undefined)
|
|
179
|
+
throw new UsageError(`${a} needs a value`);
|
|
180
|
+
return v;
|
|
181
|
+
};
|
|
182
|
+
switch (a) {
|
|
183
|
+
case '--password-file':
|
|
184
|
+
password = (await fsp.readFile(next(), 'utf8')).replace(/\r?\n$/, '');
|
|
185
|
+
break;
|
|
186
|
+
case '--plugin':
|
|
187
|
+
ordered.push(...pluginsFrom(await loadModule(next())));
|
|
188
|
+
break;
|
|
189
|
+
case '--config': {
|
|
190
|
+
const mod = await loadModule(next());
|
|
191
|
+
// The module's shape is the caller's to get right, as PdfOptions documents it.
|
|
192
|
+
const cfg = (prop(mod, 'default') ?? mod);
|
|
193
|
+
// Modules combine: plugin lists join in order and limits merge. For any other option the later module wins.
|
|
194
|
+
Object.assign(options, cfg, {
|
|
195
|
+
filePlugins: [...(options.filePlugins ?? []), ...(cfg.filePlugins ?? [])],
|
|
196
|
+
scriptPlugins: [...(options.scriptPlugins ?? []), ...(cfg.scriptPlugins ?? [])],
|
|
197
|
+
limits: { ...options.limits, ...cfg.limits },
|
|
198
|
+
});
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
case '--keep-type':
|
|
202
|
+
ordered.push((0, plugins_1.passThrough)([next()]));
|
|
203
|
+
break;
|
|
204
|
+
case '--defuse-attached-pdfs':
|
|
205
|
+
ordered.push((0, plugins_1.pdfPlugin)());
|
|
206
|
+
break;
|
|
207
|
+
case '--scrub-attached-csv':
|
|
208
|
+
ordered.push((0, data_plugins_1.csvPlugin)(delimited));
|
|
209
|
+
break;
|
|
210
|
+
case '--scrub-attached-tsv':
|
|
211
|
+
ordered.push((0, data_plugins_1.tsvPlugin)(delimited));
|
|
212
|
+
break;
|
|
213
|
+
case '--keep-attached-json':
|
|
214
|
+
ordered.push((0, data_plugins_1.jsonPlugin)());
|
|
215
|
+
break;
|
|
216
|
+
case '--csv-formulas': {
|
|
217
|
+
const mode = next();
|
|
218
|
+
if (mode !== 'escape' && mode !== 'keep' && mode !== 'remove')
|
|
219
|
+
throw new UsageError(`--csv-formulas expects escape, keep or remove, not "${mode}"`);
|
|
220
|
+
delimited.formulas = mode;
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
case '--strip-metadata':
|
|
224
|
+
stripMetadata = true;
|
|
225
|
+
break;
|
|
226
|
+
case '--limit': {
|
|
227
|
+
const [name, value] = next().split('=');
|
|
228
|
+
if (value === undefined)
|
|
229
|
+
throw new UsageError('--limit expects name=value');
|
|
230
|
+
if (name === 'fileSize' || name === 'decompressedBytes')
|
|
231
|
+
limits[name] = parseSize(value);
|
|
232
|
+
else if (name === 'objects' || name === 'nestingDepth' || name === 'timeMs') {
|
|
233
|
+
// Number('abc') is NaN, and no comparison with NaN is true, so the limit would never apply.
|
|
234
|
+
if (!/^\d+$/.test(value.trim()))
|
|
235
|
+
throw new UsageError(`Bad value for ${name}: "${value}"`);
|
|
236
|
+
limits[name] = Number(value);
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
throw new UsageError(`Unknown limit "${name}"`);
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
case '--json':
|
|
243
|
+
json = true;
|
|
244
|
+
break;
|
|
245
|
+
default:
|
|
246
|
+
if (a === '--password' || a.startsWith('--password='))
|
|
247
|
+
throw new UsageError('Pass the password with --password-file or PDF_DEFUSE_PASSWORD, not on the command line');
|
|
248
|
+
// What follows "=" can be a secret typed in the wrong place, and stderr often ends up in a log.
|
|
249
|
+
if (a.startsWith('--'))
|
|
250
|
+
throw new UsageError(`Unknown option ${a.replace(/=.*/s, '=...')}`);
|
|
251
|
+
positional.push(a);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (stripMetadata)
|
|
255
|
+
options.stripMetadata = true;
|
|
256
|
+
for (const p of ordered) {
|
|
257
|
+
if (p.kind === 'file') {
|
|
258
|
+
options.filePlugins ??= [];
|
|
259
|
+
options.filePlugins.push(p);
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
options.scriptPlugins ??= [];
|
|
263
|
+
options.scriptPlugins.push(p);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (Object.keys(limits).length)
|
|
267
|
+
options.limits = { ...(options.limits ?? {}), ...limits };
|
|
268
|
+
if (password !== undefined)
|
|
269
|
+
options.password = password;
|
|
270
|
+
return { command, positional, options, json };
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The input as a source. stdin is copied to a temporary file first. The copy stops one byte past `fileSize`, so the
|
|
274
|
+
* engine rejects the upload as too large without the rest being read, and at the deadline, where the source then
|
|
275
|
+
* fails the run for time.
|
|
276
|
+
*/
|
|
277
|
+
async function inputSource(p, tempDir, fileSize, deadline) {
|
|
278
|
+
if (p !== '-') {
|
|
279
|
+
return {
|
|
280
|
+
source: (0, io_1.fileSource)(p),
|
|
281
|
+
cleanup: async () => {
|
|
282
|
+
// The caller's own file stays.
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
const temp = new io_1.TempDir(tempDir);
|
|
287
|
+
try {
|
|
288
|
+
const file = await temp.file('.pdf');
|
|
289
|
+
let room = (fileSize ?? Number.POSITIVE_INFINITY) + 1;
|
|
290
|
+
try {
|
|
291
|
+
await (0, promises_1.pipeline)(process.stdin, async function* (chunks) {
|
|
292
|
+
for await (const c of chunks) {
|
|
293
|
+
yield c.subarray(0, room);
|
|
294
|
+
room -= c.length;
|
|
295
|
+
if (room <= 0)
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
}, fs.createWriteStream(file), { signal: deadline === undefined ? undefined : AbortSignal.timeout(Math.max(0, deadline - Date.now())) });
|
|
299
|
+
}
|
|
300
|
+
catch (e) {
|
|
301
|
+
if (e.name !== 'AbortError')
|
|
302
|
+
throw e;
|
|
303
|
+
const late = () => Promise.reject(new document_1.TimeLimitError('Time limit exceeded'));
|
|
304
|
+
return { source: { size: late, read: late }, cleanup: () => temp.cleanup() };
|
|
305
|
+
}
|
|
306
|
+
return { source: (0, io_1.fileSource)(file), cleanup: () => temp.cleanup() };
|
|
307
|
+
}
|
|
308
|
+
catch (e) {
|
|
309
|
+
await temp.cleanup();
|
|
310
|
+
throw e;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/** Writes a control character as a JSON escape, since text from the PDF could otherwise drive the terminal. */
|
|
314
|
+
const escaped = (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
315
|
+
function report(label, i) {
|
|
316
|
+
const lines = [`${label}: ${i.status}, risk ${i.risk}${i.score === null ? '' : ` (score ${i.score})`}, PDF ${i.version || '?'}, ${i.pages ?? 0} pages`];
|
|
317
|
+
for (const f of i.findings)
|
|
318
|
+
lines.push(` ${f.action.padEnd(6)} ${f.category}/${f.detail}${f.location ? ` [${f.location}]` : ''}: ${f.description}`);
|
|
319
|
+
// A location can hold a field name or a title from the PDF. A line break in one would print a line of its own.
|
|
320
|
+
return lines.map(l => l.replace(/\p{Cc}/gu, escaped)).join('\n');
|
|
321
|
+
}
|
|
322
|
+
async function main(argv) {
|
|
323
|
+
let parsed;
|
|
324
|
+
try {
|
|
325
|
+
parsed = await parse(argv);
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
process.stderr.write(`${e.message}\n\n${USAGE}\n`);
|
|
329
|
+
return 3;
|
|
330
|
+
}
|
|
331
|
+
const { command, positional, options, json } = parsed;
|
|
332
|
+
try {
|
|
333
|
+
if (command === 'inspect' && positional.length !== 1)
|
|
334
|
+
throw new UsageError('inspect takes one file');
|
|
335
|
+
if (command === 'defuse' && positional.length !== 2)
|
|
336
|
+
throw new UsageError('defuse takes an input and an output');
|
|
337
|
+
const toStdout = command === 'defuse' && positional[1] === '-';
|
|
338
|
+
if (command === 'defuse' && positional[0] !== '-' && !toStdout) {
|
|
339
|
+
// A failed write deletes the partial output, which here would be the only copy of the input.
|
|
340
|
+
const [a, b] = await Promise.all([fsp.stat(positional[0]), fsp.stat(positional[1]).catch(() => undefined)]);
|
|
341
|
+
if (b && a.dev === b.dev && a.ino === b.ino)
|
|
342
|
+
throw new UsageError('The input and the output are the same file');
|
|
343
|
+
}
|
|
344
|
+
// Reading stdin counts toward the time limit, so the run gets what is left of it.
|
|
345
|
+
const deadline = options.limits?.timeMs === undefined ? undefined : Date.now() + options.limits.timeMs;
|
|
346
|
+
const input = await inputSource(positional[0], options.tempDir, options.limits?.fileSize, deadline);
|
|
347
|
+
const runOptions = deadline === undefined ? options : { ...options, limits: { ...options.limits, timeMs: deadline - Date.now() } };
|
|
348
|
+
let text;
|
|
349
|
+
let code;
|
|
350
|
+
try {
|
|
351
|
+
if (command === 'inspect') {
|
|
352
|
+
const r = await (0, engine_1.inspectPdfSource)(input.source, runOptions);
|
|
353
|
+
text = json ? JSON.stringify(r, null, 2) : report('inspection', r);
|
|
354
|
+
code = r.status === 'clean' ? 0 : r.status === 'strippable' ? 1 : 2;
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
const r = await (0, engine_1.disarmPdfSource)(input.source, toStdout ? (0, io_1.writableSink)(process.stdout) : (0, io_1.fileSink)(positional[1]), runOptions);
|
|
358
|
+
text = json ? JSON.stringify(r, null, 2) : [`result: ${r.status}`, report('before', r.before), ...(r.after && r.status === 'defused' ? [report('after', r.after)] : [])].join('\n');
|
|
359
|
+
code = r.status === 'clean' ? 0 : r.status === 'defused' ? 1 : 2;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
await input.source.close?.();
|
|
364
|
+
await input.cleanup();
|
|
365
|
+
}
|
|
366
|
+
// JSON.stringify escapes C0 controls but not DEL or the C1 range.
|
|
367
|
+
if (json)
|
|
368
|
+
text = text.replace(/[\u007f-\u009f]/g, escaped);
|
|
369
|
+
// The report shares stdout only when the PDF goes elsewhere. A report nobody can read is an I/O error.
|
|
370
|
+
const out = toStdout ? process.stderr : process.stdout;
|
|
371
|
+
await new Promise((resolve, reject) => out.write(`${text}\n`, e => (e ? reject(e) : resolve())));
|
|
372
|
+
return code;
|
|
373
|
+
}
|
|
374
|
+
catch (e) {
|
|
375
|
+
process.stderr.write(`${e instanceof UsageError ? `${e.message}\n\n${USAGE}` : `Error: ${e.message}`}\n`);
|
|
376
|
+
return 3;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (require.main === module) {
|
|
380
|
+
// main() learns of a failed write from its callback. Node emits the failure as an 'error' event as well, which
|
|
381
|
+
// with no listener would end the process with exit code 1.
|
|
382
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
383
|
+
stream.on('error', () => {
|
|
384
|
+
process.exitCode = 3;
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
main(process.argv.slice(2)).then(code => {
|
|
388
|
+
process.exitCode = code;
|
|
389
|
+
});
|
|
390
|
+
}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { PdfDict, type PdfStream } from './objects';
|
|
2
|
+
/** RC4 with state, so a stream can be decrypted in chunks. Node 24's OpenSSL 3 refuses RC4, so it is written here. */
|
|
3
|
+
export declare class Rc4 {
|
|
4
|
+
private readonly s;
|
|
5
|
+
private i;
|
|
6
|
+
private j;
|
|
7
|
+
constructor(key: Uint8Array);
|
|
8
|
+
update(data: Uint8Array): Buffer;
|
|
9
|
+
}
|
|
10
|
+
export declare const rc4: (key: Uint8Array, data: Uint8Array) => Buffer<ArrayBufferLike>;
|
|
11
|
+
type CryptMethod = 'RC4' | 'AES128' | 'AES256' | 'Identity';
|
|
12
|
+
export type OpenResult = {
|
|
13
|
+
status: 'ok';
|
|
14
|
+
handler: SecurityHandler;
|
|
15
|
+
password: 'empty' | 'user' | 'owner';
|
|
16
|
+
} | {
|
|
17
|
+
status: 'password-required' | 'certificate-handler' | 'unknown-handler' | 'unknown-filter';
|
|
18
|
+
detail?: string;
|
|
19
|
+
};
|
|
20
|
+
/** A stream decryptor that works chunk by chunk. */
|
|
21
|
+
export interface ChunkDecryptor {
|
|
22
|
+
update(chunk: Uint8Array): Buffer;
|
|
23
|
+
final(): Buffer;
|
|
24
|
+
}
|
|
25
|
+
export declare class SecurityHandler {
|
|
26
|
+
private readonly version;
|
|
27
|
+
readonly keyBits: number;
|
|
28
|
+
private readonly fileKey;
|
|
29
|
+
readonly streamMethod: CryptMethod;
|
|
30
|
+
readonly stringMethod: CryptMethod;
|
|
31
|
+
readonly embeddedFileMethod: CryptMethod;
|
|
32
|
+
readonly encryptMetadata: boolean;
|
|
33
|
+
private readonly cryptFilters;
|
|
34
|
+
/** Crypt filters with a /CFM this package cannot decrypt, mapped to that /CFM. Harmless until something selects one. */
|
|
35
|
+
private readonly unknownFilters;
|
|
36
|
+
private constructor();
|
|
37
|
+
static open(enc: PdfDict, id0: Uint8Array, password: string): OpenResult;
|
|
38
|
+
private readonly keyCache;
|
|
39
|
+
private objectKey;
|
|
40
|
+
decryptWith(method: CryptMethod, data: Uint8Array, num: number, gen: number): Uint8Array;
|
|
41
|
+
/** The crypt method for a stream, honoring a /Crypt filter in its own Filter array and the embedded-file default. */
|
|
42
|
+
methodForStream(stream: PdfStream): CryptMethod;
|
|
43
|
+
/**
|
|
44
|
+
* Plaintext length of a stream, read without decrypting the whole body. For AES the last two
|
|
45
|
+
* blocks are decrypted to learn the padding length.
|
|
46
|
+
*/
|
|
47
|
+
plainLength(stream: PdfStream, num: number, gen: number, readRaw: (offset: number, length: number) => Promise<Uint8Array>): Promise<number>;
|
|
48
|
+
/** A decryptor that emits exactly `plainLength` bytes across all chunks. */
|
|
49
|
+
chunkDecryptor(stream: PdfStream, num: number, gen: number, plainLength: number): ChunkDecryptor;
|
|
50
|
+
}
|
|
51
|
+
export {};
|