@file-viewer/renderer-pdf 3.3.4 → 3.3.5

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/README.en.md CHANGED
@@ -9,6 +9,12 @@ use asynchronous resource fetching instead of synchronous binary XHR.
9
9
 
10
10
  Standalone PDF renderer package for Flyfish File Viewer. It is powered by PDF.js and provides page rendering, navigation, outline, search, zoom, print, and HTML export support.
11
11
 
12
+ ## Optional signature metadata
13
+
14
+ With the optional signatureRenderer, PDF keeps its normal preview and can show metadata-only signature details. For lightweight packages, install the existing optional pdf-lib@1.17.1 peer and call enableFileViewerPdfSignatureInspection() from @file-viewer/renderer-pdf/signature-inspection; Full already registers the reader through its existing PDF capability. The normal PDF entry does not import this parser. Supply an original File/buffer or pdf.streaming:false. A streaming URL without original bytes preserves preview and reports unavailable without an extra fetch. This reads original-source dictionaries/CMS without checking signatures, digests, revision coverage or trust.
15
+
16
+ See the Vanilla example and boundaries in [renderer-signature](https://github.com/flyfish-dev/file-viewer/blob/main/packages/renderers/signature/README.md)。
17
+
12
18
  ## Usage
13
19
 
14
20
  ```ts
package/README.md CHANGED
@@ -9,6 +9,12 @@ use asynchronous resource fetching instead of synchronous binary XHR.
9
9
 
10
10
  Standalone PDF renderer package for Flyfish File Viewer. It is powered by PDF.js and provides page rendering, navigation, outline, search, zoom, print, and HTML export support.
11
11
 
12
+ ## Optional signature metadata
13
+
14
+ With the optional signatureRenderer, PDF keeps its normal preview and can show metadata-only signature details. For lightweight packages, install the existing optional pdf-lib@1.17.1 peer and call enableFileViewerPdfSignatureInspection() from @file-viewer/renderer-pdf/signature-inspection; Full already registers the reader through its existing PDF capability. The normal PDF entry does not import this parser. Supply an original File/buffer or pdf.streaming:false. A streaming URL without original bytes preserves preview and reports unavailable without an extra fetch. This reads original-source dictionaries/CMS without checking signatures, digests, revision coverage or trust.
15
+
16
+ See the Vanilla example and boundaries in [renderer-signature](https://github.com/flyfish-dev/file-viewer/blob/main/packages/renderers/signature/README.md)。
17
+
12
18
  ## Usage
13
19
 
14
20
  ```ts
package/README.zh-CN.md CHANGED
@@ -4,6 +4,12 @@
4
4
 
5
5
  Flyfish File Viewer 的独立 PDF renderer 包,基于 PDF.js,提供 PDF 页面渲染、导航、目录、搜索、缩放、打印和 HTML 导出能力。
6
6
 
7
+ ## 可选签名元数据
8
+
9
+ 注册可选 signatureRenderer 后,PDF 原预览旁可显示只读签名元数据。轻量包需安装现有可选 peer pdf-lib@1.17.1 并调用 enableFileViewerPdfSignatureInspection()(来自 @file-viewer/renderer-pdf/signature-inspection);Full 原有 PDF 能力已注册该 reader。普通 PDF 入口不引入此解析器。使用原始 File/buffer 或 pdf.streaming:false;仅流式 URL 缺原字节时保留预览并报告不可检查,不额外请求。只解析原始字节字典/CMS,不验证签名、摘要、修订覆盖或信任。
10
+
11
+ 完整 Vanilla 示例及限制见 [renderer-signature](https://github.com/flyfish-dev/file-viewer/blob/main/packages/renderers/signature/README.zh-CN.md)。
12
+
7
13
  ## 用法
8
14
 
9
15
  ```ts
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
1
+ import { DEFAULT_RENDERER_DEFINITIONS, renderWithFileViewerDocumentInspection, } from '@file-viewer/core';
2
2
  export { getFileViewerPdfIdentityFontRepair, registerFileViewerPdfIdentityFontRepair, } from './optionalCapabilities.js';
3
3
  const pdfDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'pdf');
4
4
  if (!pdfDefinition) {
@@ -8,7 +8,7 @@ export const pdfRendererDefinition = {
8
8
  ...pdfDefinition,
9
9
  sourceAccess: 'stream-preferred',
10
10
  };
11
- export const renderFileViewerPdf = (buffer, target, _type, context) => import('./pdf.js').then(({ default: renderPdf }) => renderPdf(buffer, target, context));
11
+ export const renderFileViewerPdf = (buffer, target, _type, context) => renderWithFileViewerDocumentInspection(buffer, target, 'pdf', context, () => import('./pdf.js').then(({ default: renderPdf }) => renderPdf(buffer, target, context)));
12
12
  export const pdfRenderer = {
13
13
  id: 'file-viewer-renderer-pdf',
14
14
  label: 'Flyfish File Viewer PDF renderer',
@@ -0,0 +1,6 @@
1
+ import { type FileViewerPdfSignatureDictionary } from '@file-viewer/core';
2
+ export declare const enableFileViewerPdfSignatureInspection: () => () => void;
3
+ export declare const readPdfSignatureDictionaries: (bytes: Uint8Array, signal: AbortSignal) => Promise<{
4
+ signatures: FileViewerPdfSignatureDictionary[];
5
+ warnings: string[];
6
+ }>;
@@ -0,0 +1,228 @@
1
+ import { registerFileViewerPdfSignatureReader } from '@file-viewer/core';
2
+ import { PDFArray, PDFContext, PDFDict, PDFHexString, PDFName, PDFNumber, PDFObjectParser, PDFParser, PDFRawStream, PDFRef, PDFString, decodePDFRawStream } from 'pdf-lib';
3
+ const MAX_INPUT = 64 * 1024 * 1024;
4
+ const MAX_STREAM = 4 * 1024 * 1024;
5
+ const MAX_DECODED = 16 * 1024 * 1024;
6
+ const MAX_OBJECTS = 50000;
7
+ const MAX_NODES = 200000;
8
+ const MAX_DEPTH = 64;
9
+ const MAX_SIGNATURES = 64;
10
+ const name = (key) => PDFName.of(key);
11
+ const cursor = (parser) => parser.bytes.offset();
12
+ export const enableFileViewerPdfSignatureInspection = () => registerFileViewerPdfSignatureReader(readPdfSignatureDictionaries);
13
+ export const readPdfSignatureDictionaries = async (bytes, signal) => {
14
+ if (!bytes.length || bytes.length > MAX_INPUT)
15
+ throw new Error('PDF signature inspection input exceeds its boundary.');
16
+ const deadline = Date.now() + 20000;
17
+ let objects = 0, nodes = 0, decodedBytes = 0;
18
+ const guard = () => {
19
+ if (signal.aborted)
20
+ throw signal.reason || new Error('PDF metadata inspection cancelled.');
21
+ if (Date.now() > deadline)
22
+ throw new Error('PDF metadata inspection timed out.');
23
+ if (objects > MAX_OBJECTS || nodes > MAX_NODES)
24
+ throw new Error('PDF metadata object/node limit exceeded.');
25
+ };
26
+ const candidates = [];
27
+ const captured = new WeakMap();
28
+ const capture = (dictionary, ref) => {
29
+ if (!dictionary.has(name('ByteRange')) && dictionary.get(name('Type')) !== name('Sig'))
30
+ return;
31
+ const previous = captured.get(dictionary);
32
+ if (previous) {
33
+ if (ref)
34
+ previous.ref = ref.toString();
35
+ return;
36
+ }
37
+ if (candidates.length >= MAX_SIGNATURES)
38
+ throw new Error('PDF signature dictionary count exceeds its limit.');
39
+ const candidate = { ref: (ref === null || ref === void 0 ? void 0 : ref.toString()) || 'direct dictionary', dictionary, sequence: candidates.length + 1 };
40
+ captured.set(dictionary, candidate);
41
+ candidates.push(candidate);
42
+ };
43
+ const parser = PDFParser.forBytesWithOptions(bytes, 25, true);
44
+ const context = parser.context;
45
+ const assign = context.assign.bind(context);
46
+ context.assign = (ref, object) => {
47
+ objects++;
48
+ guard();
49
+ if (object instanceof PDFDict)
50
+ capture(object, ref);
51
+ assign(ref, object);
52
+ };
53
+ const number = (object, max) => {
54
+ if (!(object instanceof PDFNumber))
55
+ throw new Error('Unsupported indirect or non-numeric PDF metadata parameter.');
56
+ const value = object.asNumber();
57
+ if (!Number.isSafeInteger(value) || value < 0 || value > max)
58
+ throw new Error('PDF metadata numeric parameter exceeds its boundary.');
59
+ return value;
60
+ };
61
+ const trailingWhitespace = (source, offset) => {
62
+ while (offset < source.length) {
63
+ const value = source[offset++];
64
+ if ([0, 9, 10, 12, 13, 32].includes(value))
65
+ continue;
66
+ if (value === 37) {
67
+ while (offset < source.length && source[offset] !== 10 && source[offset] !== 13)
68
+ offset++;
69
+ continue;
70
+ }
71
+ throw new Error('Unsupported trailing tokens in a PDF object stream.');
72
+ }
73
+ };
74
+ const decodedStream = (stream) => {
75
+ const filter = stream.dict.get(name('Filter'));
76
+ if (filter && (!(filter instanceof PDFName) || !['FlateDecode', 'Fl'].includes(filter.decodeText())))
77
+ throw new Error('PDF metadata supports only a single bounded FlateDecode structural stream filter.');
78
+ const decoded = decodePDFRawStream(stream);
79
+ if (decoded.ensureBuffer) {
80
+ const ensure = decoded.ensureBuffer.bind(decoded);
81
+ decoded.ensureBuffer = length => {
82
+ guard();
83
+ if (length > MAX_STREAM + 1)
84
+ throw new Error('Decoded PDF structural stream exceeds its limit.');
85
+ return ensure(length);
86
+ };
87
+ }
88
+ const output = decoded.getBytes(MAX_STREAM + 1);
89
+ decodedBytes += output.length;
90
+ if (output.length > MAX_STREAM || decodedBytes > MAX_DECODED || output.length > Math.max(1, stream.contents.length) * 200)
91
+ throw new Error('PDF structural stream expansion exceeds its boundary.');
92
+ return new Uint8Array(output.buffer, output.byteOffset, output.byteLength);
93
+ };
94
+ const boundedParser = (reader, allowStreams) => {
95
+ const parse = reader.parseObject.bind(reader);
96
+ let depth = 0;
97
+ reader.parseObject = () => {
98
+ var _a, _b;
99
+ nodes++;
100
+ guard();
101
+ if (++depth > MAX_DEPTH) {
102
+ depth--;
103
+ throw new Error('PDF metadata nesting limit exceeded.');
104
+ }
105
+ try {
106
+ const object = parse();
107
+ if (object instanceof PDFDict)
108
+ capture(object);
109
+ if (!(object instanceof PDFRawStream))
110
+ return object;
111
+ if (!allowStreams)
112
+ throw new Error('Nested streams in a PDF object stream are unsupported.');
113
+ const type = object.dict.get(name('Type'));
114
+ if (type instanceof PDFRef)
115
+ throw new Error('Indirect PDF stream Type is unsupported for bounded metadata inspection.');
116
+ if (type !== name('ObjStm') && type !== name('XRef'))
117
+ return object;
118
+ if (type === name('XRef')) {
119
+ for (const key of ['Root', 'Encrypt', 'Info', 'ID']) {
120
+ const value = object.dict.get(name(key));
121
+ if (value)
122
+ context.trailerInfo[key] = value;
123
+ }
124
+ return object.dict;
125
+ }
126
+ const decoded = decodedStream(object);
127
+ if (type === name('ObjStm')) {
128
+ const count = number(object.dict.get(name('N')), 1024);
129
+ const first = number(object.dict.get(name('First')), decoded.length);
130
+ const header = boundedParser(PDFObjectParser.forBytes(decoded.subarray(0, first), context), false);
131
+ const entries = [];
132
+ const seen = new Set();
133
+ for (let index = 0; index < count; index++) {
134
+ const objectNumber = number(header.parseObject(), 0x7fffffff);
135
+ const offset = number(header.parseObject(), decoded.length - first);
136
+ if (!objectNumber || seen.has(objectNumber) || (index && offset < entries[index - 1].offset))
137
+ throw new Error('Unsupported duplicate or unordered PDF object-stream entries.');
138
+ seen.add(objectNumber);
139
+ entries.push({ number: objectNumber, offset });
140
+ }
141
+ trailingWhitespace(decoded.subarray(0, first), cursor(header));
142
+ for (let index = 0; index < entries.length; index++) {
143
+ guard();
144
+ const entry = entries[index];
145
+ const part = decoded.subarray(first + entry.offset, first + ((_b = (_a = entries[index + 1]) === null || _a === void 0 ? void 0 : _a.offset) !== null && _b !== void 0 ? _b : decoded.length - first));
146
+ const nested = boundedParser(PDFObjectParser.forBytes(part, context), false);
147
+ const value = nested.parseObject();
148
+ trailingWhitespace(part, cursor(nested));
149
+ context.assign(PDFRef.of(entry.number, 0), value);
150
+ }
151
+ return object.dict;
152
+ }
153
+ return object.dict;
154
+ }
155
+ finally {
156
+ depth--;
157
+ }
158
+ };
159
+ return reader;
160
+ };
161
+ boundedParser(parser, true);
162
+ try {
163
+ await parser.parseDocument();
164
+ }
165
+ catch (error) {
166
+ if (signal.aborted)
167
+ throw signal.reason || new Error('PDF metadata inspection cancelled.');
168
+ throw error;
169
+ }
170
+ guard();
171
+ if (context.trailerInfo.Encrypt)
172
+ throw new Error('Encrypted PDF metadata is unsupported; no decryption was performed.');
173
+ const signatures = [];
174
+ const text = (object) => {
175
+ if (object instanceof PDFName)
176
+ return object.decodeText();
177
+ if (object instanceof PDFString || object instanceof PDFHexString) {
178
+ if (object.asBytes().length > 32768)
179
+ throw new Error('PDF signature text field exceeds its limit.');
180
+ return object.decodeText();
181
+ }
182
+ return undefined;
183
+ };
184
+ for (const candidate of candidates) {
185
+ guard();
186
+ const dictionary = candidate.dictionary;
187
+ const contentsObject = dictionary.get(name('Contents'));
188
+ const contents = contentsObject instanceof PDFString || contentsObject instanceof PDFHexString ? contentsObject.asBytes() : undefined;
189
+ const rangeObject = dictionary.get(name('ByteRange'));
190
+ if ((!(contents === null || contents === void 0 ? void 0 : contents.length) || contents.every(value => value === 0)) && (!rangeObject || (rangeObject instanceof PDFArray && rangeObject.asArray().every(value => value instanceof PDFNumber && value.asNumber() === 0))))
191
+ continue;
192
+ if (!contentsObject && !rangeObject)
193
+ continue;
194
+ if (contents && contents.length > 8 * 1024 * 1024)
195
+ throw new Error('PDF CMS contents exceed the metadata limit.');
196
+ const warnings = [];
197
+ let byteRange;
198
+ if (rangeObject instanceof PDFArray && rangeObject.size() >= 4 && rangeObject.size() <= 16 && rangeObject.size() % 2 === 0) {
199
+ try {
200
+ const ranges = rangeObject.asArray().map(value => number(value, bytes.length));
201
+ let end = 0;
202
+ if (ranges[0] !== 0)
203
+ throw new Error('ByteRange does not start at the original source.');
204
+ for (let index = 0; index < ranges.length; index += 2) {
205
+ const start = ranges[index], length = ranges[index + 1];
206
+ if (start < end || start + length > bytes.length)
207
+ throw new Error('ByteRange is outside the source or overlaps.');
208
+ end = start + length;
209
+ }
210
+ byteRange = ranges;
211
+ }
212
+ catch {
213
+ warnings.push('ByteRange is unsupported or incomplete; signature validity is not checked.');
214
+ }
215
+ }
216
+ else
217
+ warnings.push('ByteRange is missing or unsupported; signature validity is not checked.');
218
+ if (!contents)
219
+ warnings.push('Direct CMS contents are missing or unsupported.');
220
+ const revisionEnd = byteRange ? byteRange[byteRange.length - 2] + byteRange[byteRange.length - 1] : undefined;
221
+ signatures.push({
222
+ id: `${candidate.ref} / source definition ${candidate.sequence}`, contents, byteRange, revisionEnd,
223
+ fields: Object.fromEntries(['Filter', 'SubFilter', 'Name', 'M', 'Reason', 'Location', 'ContactInfo'].map(key => [key, text(dictionary.get(name(key)))])),
224
+ warnings: [...warnings, 'Original-source dictionary metadata only; active-field ownership, signed revision coverage and integrity were not verified.', ...(revisionEnd !== undefined && revisionEnd < bytes.length ? ['Bytes follow the declared ByteRange; later changes were not checked.'] : [])],
225
+ });
226
+ }
227
+ return { signatures, warnings: [] };
228
+ };