pdf-oxide-fips 0.3.47

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.
Files changed (127) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +25 -0
  3. package/README.md +218 -0
  4. package/lib/builders/annotation-builder.d.ts +198 -0
  5. package/lib/builders/annotation-builder.js +317 -0
  6. package/lib/builders/conversion-options-builder.d.ts +106 -0
  7. package/lib/builders/conversion-options-builder.js +214 -0
  8. package/lib/builders/document-builder.d.ts +381 -0
  9. package/lib/builders/document-builder.js +770 -0
  10. package/lib/builders/index.d.ts +13 -0
  11. package/lib/builders/index.js +13 -0
  12. package/lib/builders/metadata-builder.d.ts +201 -0
  13. package/lib/builders/metadata-builder.js +285 -0
  14. package/lib/builders/pdf-builder.d.ts +216 -0
  15. package/lib/builders/pdf-builder.js +350 -0
  16. package/lib/builders/search-options-builder.d.ts +73 -0
  17. package/lib/builders/search-options-builder.js +129 -0
  18. package/lib/builders/streaming-table.d.ts +64 -0
  19. package/lib/builders/streaming-table.js +140 -0
  20. package/lib/document-editor-manager.d.ts +139 -0
  21. package/lib/document-editor-manager.js +256 -0
  22. package/lib/document-editor.d.ts +124 -0
  23. package/lib/document-editor.js +318 -0
  24. package/lib/errors.d.ts +382 -0
  25. package/lib/errors.js +1115 -0
  26. package/lib/form-field-manager.d.ts +299 -0
  27. package/lib/form-field-manager.js +568 -0
  28. package/lib/hybrid-ml-manager.d.ts +142 -0
  29. package/lib/hybrid-ml-manager.js +208 -0
  30. package/lib/index.d.ts +205 -0
  31. package/lib/index.js +693 -0
  32. package/lib/managers/accessibility-manager.d.ts +148 -0
  33. package/lib/managers/accessibility-manager.js +234 -0
  34. package/lib/managers/annotation-manager.d.ts +219 -0
  35. package/lib/managers/annotation-manager.js +359 -0
  36. package/lib/managers/barcode-manager.d.ts +82 -0
  37. package/lib/managers/barcode-manager.js +263 -0
  38. package/lib/managers/batch-manager.d.ts +185 -0
  39. package/lib/managers/batch-manager.js +385 -0
  40. package/lib/managers/cache-manager.d.ts +181 -0
  41. package/lib/managers/cache-manager.js +384 -0
  42. package/lib/managers/compliance-manager.d.ts +103 -0
  43. package/lib/managers/compliance-manager.js +453 -0
  44. package/lib/managers/content-manager.d.ts +120 -0
  45. package/lib/managers/content-manager.js +294 -0
  46. package/lib/managers/document-utility-manager.d.ts +369 -0
  47. package/lib/managers/document-utility-manager.js +730 -0
  48. package/lib/managers/dom-pdf-creator.d.ts +104 -0
  49. package/lib/managers/dom-pdf-creator.js +299 -0
  50. package/lib/managers/editing-manager.d.ts +248 -0
  51. package/lib/managers/editing-manager.js +387 -0
  52. package/lib/managers/enterprise-manager.d.ts +192 -0
  53. package/lib/managers/enterprise-manager.js +307 -0
  54. package/lib/managers/extended-managers.d.ts +122 -0
  55. package/lib/managers/extended-managers.js +664 -0
  56. package/lib/managers/extraction-manager.d.ts +246 -0
  57. package/lib/managers/extraction-manager.js +482 -0
  58. package/lib/managers/final-utilities.d.ts +127 -0
  59. package/lib/managers/final-utilities.js +657 -0
  60. package/lib/managers/hybrid-ml-advanced.d.ts +136 -0
  61. package/lib/managers/hybrid-ml-advanced.js +722 -0
  62. package/lib/managers/index.d.ts +64 -0
  63. package/lib/managers/index.js +69 -0
  64. package/lib/managers/layer-manager.d.ts +203 -0
  65. package/lib/managers/layer-manager.js +401 -0
  66. package/lib/managers/metadata-manager.d.ts +148 -0
  67. package/lib/managers/metadata-manager.js +280 -0
  68. package/lib/managers/ocr-manager.d.ts +194 -0
  69. package/lib/managers/ocr-manager.js +582 -0
  70. package/lib/managers/optimization-manager.d.ts +102 -0
  71. package/lib/managers/optimization-manager.js +213 -0
  72. package/lib/managers/outline-manager.d.ts +101 -0
  73. package/lib/managers/outline-manager.js +169 -0
  74. package/lib/managers/page-manager.d.ts +142 -0
  75. package/lib/managers/page-manager.js +235 -0
  76. package/lib/managers/pattern-detection.d.ts +169 -0
  77. package/lib/managers/pattern-detection.js +322 -0
  78. package/lib/managers/rendering-manager.d.ts +353 -0
  79. package/lib/managers/rendering-manager.js +679 -0
  80. package/lib/managers/search-manager.d.ts +235 -0
  81. package/lib/managers/search-manager.js +329 -0
  82. package/lib/managers/security-manager.d.ts +161 -0
  83. package/lib/managers/security-manager.js +292 -0
  84. package/lib/managers/signature-manager.d.ts +738 -0
  85. package/lib/managers/signature-manager.js +1509 -0
  86. package/lib/managers/streams.d.ts +262 -0
  87. package/lib/managers/streams.js +477 -0
  88. package/lib/managers/xfa-manager.d.ts +227 -0
  89. package/lib/managers/xfa-manager.js +539 -0
  90. package/lib/native-loader.d.ts +7 -0
  91. package/lib/native-loader.js +62 -0
  92. package/lib/native.d.ts +16 -0
  93. package/lib/native.js +69 -0
  94. package/lib/pdf-creator-manager.d.ts +200 -0
  95. package/lib/pdf-creator-manager.js +381 -0
  96. package/lib/properties.d.ts +79 -0
  97. package/lib/properties.js +454 -0
  98. package/lib/result-accessors-manager.d.ts +346 -0
  99. package/lib/result-accessors-manager.js +706 -0
  100. package/lib/thumbnail-manager.d.ts +121 -0
  101. package/lib/thumbnail-manager.js +205 -0
  102. package/lib/timestamp.d.ts +54 -0
  103. package/lib/timestamp.js +115 -0
  104. package/lib/tsa-client.d.ts +44 -0
  105. package/lib/tsa-client.js +67 -0
  106. package/lib/types/common.d.ts +189 -0
  107. package/lib/types/common.js +17 -0
  108. package/lib/types/document-types.d.ts +352 -0
  109. package/lib/types/document-types.js +82 -0
  110. package/lib/types/index.d.ts +5 -0
  111. package/lib/types/index.js +5 -0
  112. package/lib/types/manager-types.d.ts +179 -0
  113. package/lib/types/manager-types.js +100 -0
  114. package/lib/types/native-bindings.d.ts +439 -0
  115. package/lib/types/native-bindings.js +7 -0
  116. package/lib/workers/index.d.ts +6 -0
  117. package/lib/workers/index.js +5 -0
  118. package/lib/workers/pool.d.ts +64 -0
  119. package/lib/workers/pool.js +192 -0
  120. package/lib/workers/worker.d.ts +5 -0
  121. package/lib/workers/worker.js +99 -0
  122. package/package.json +79 -0
  123. package/prebuilds/darwin-arm64/pdf_oxide.node +0 -0
  124. package/prebuilds/darwin-x64/pdf_oxide.node +0 -0
  125. package/prebuilds/linux-arm64/pdf_oxide.node +0 -0
  126. package/prebuilds/linux-x64/pdf_oxide.node +0 -0
  127. package/prebuilds/win32-x64/pdf_oxide.node +0 -0
@@ -0,0 +1,1509 @@
1
+ /**
2
+ * SignatureManager - Canonical Signature Manager (merged from 3 implementations)
3
+ *
4
+ * Consolidates:
5
+ * - src/signature-manager.ts SignatureManager (verification + basic field management)
6
+ * - src/managers/barcode-signature-rendering.ts SignaturesManager (certificate loading + signing + detail info)
7
+ * - src/managers/signature-creation-manager.ts SignatureCreationManager (complete signing workflow + LTV + timestamps)
8
+ *
9
+ * Provides comprehensive digital signature operations with full type safety
10
+ * and FFI integration.
11
+ */
12
+ import { EventEmitter } from 'events';
13
+ import { promises as fs } from 'fs';
14
+ import { mapFfiErrorCode, SignatureException } from '../errors.js';
15
+ // =============================================================================
16
+ // Type Definitions (merged from all 3 sources)
17
+ // =============================================================================
18
+ /**
19
+ * Signature algorithms
20
+ */
21
+ export var SignatureAlgorithm;
22
+ (function (SignatureAlgorithm) {
23
+ SignatureAlgorithm["RSA2048"] = "RSA2048";
24
+ SignatureAlgorithm["RSA3072"] = "RSA3072";
25
+ SignatureAlgorithm["RSA4096"] = "RSA4096";
26
+ SignatureAlgorithm["ECDSAP256"] = "ECDSA_P256";
27
+ SignatureAlgorithm["ECDSAP384"] = "ECDSA_P384";
28
+ SignatureAlgorithm["ECDSAP521"] = "ECDSA_P521";
29
+ SignatureAlgorithm["RSA_SHA256"] = "RSA_SHA256";
30
+ SignatureAlgorithm["RSA_SHA384"] = "RSA_SHA384";
31
+ SignatureAlgorithm["RSA_SHA512"] = "RSA_SHA512";
32
+ SignatureAlgorithm["ECDSA_SHA256"] = "ECDSA_SHA256";
33
+ SignatureAlgorithm["ECDSA_SHA384"] = "ECDSA_SHA384";
34
+ SignatureAlgorithm["ECDSA_SHA512"] = "ECDSA_SHA512";
35
+ SignatureAlgorithm["ED25519"] = "ED25519";
36
+ })(SignatureAlgorithm || (SignatureAlgorithm = {}));
37
+ /**
38
+ * Digest algorithms for signature
39
+ */
40
+ export var DigestAlgorithm;
41
+ (function (DigestAlgorithm) {
42
+ DigestAlgorithm["SHA256"] = "SHA256";
43
+ DigestAlgorithm["SHA384"] = "SHA384";
44
+ DigestAlgorithm["SHA512"] = "SHA512";
45
+ DigestAlgorithm["SHA512_256"] = "SHA512_256";
46
+ })(DigestAlgorithm || (DigestAlgorithm = {}));
47
+ /**
48
+ * Signature type enumeration
49
+ */
50
+ export var SignatureType;
51
+ (function (SignatureType) {
52
+ SignatureType["APPROVAL"] = "approval";
53
+ SignatureType["CERTIFICATION"] = "certification";
54
+ SignatureType["USAGE_RIGHTS"] = "usage_rights";
55
+ })(SignatureType || (SignatureType = {}));
56
+ /**
57
+ * Certification permission level
58
+ */
59
+ export var CertificationPermission;
60
+ (function (CertificationPermission) {
61
+ CertificationPermission[CertificationPermission["NO_CHANGES"] = 1] = "NO_CHANGES";
62
+ CertificationPermission[CertificationPermission["FORM_FILLING"] = 2] = "FORM_FILLING";
63
+ CertificationPermission[CertificationPermission["FORM_FILLING_ANNOTATIONS"] = 3] = "FORM_FILLING_ANNOTATIONS";
64
+ })(CertificationPermission || (CertificationPermission = {}));
65
+ /**
66
+ * Certificate format enumeration
67
+ */
68
+ export var CertificateFormat;
69
+ (function (CertificateFormat) {
70
+ CertificateFormat["PFX"] = "pfx";
71
+ CertificateFormat["PEM"] = "pem";
72
+ CertificateFormat["DER"] = "der";
73
+ CertificateFormat["P12"] = "p12";
74
+ CertificateFormat["CER"] = "cer";
75
+ })(CertificateFormat || (CertificateFormat = {}));
76
+ /**
77
+ * Timestamp response status
78
+ */
79
+ export var TimestampStatus;
80
+ (function (TimestampStatus) {
81
+ TimestampStatus["SUCCESS"] = "success";
82
+ TimestampStatus["FAILED"] = "failed";
83
+ TimestampStatus["TIMEOUT"] = "timeout";
84
+ TimestampStatus["INVALID_RESPONSE"] = "invalid_response";
85
+ })(TimestampStatus || (TimestampStatus = {}));
86
+ /**
87
+ * FFI digest algorithm constants for use with SignOptions.algorithm
88
+ */
89
+ export var FfiDigestAlgorithm;
90
+ (function (FfiDigestAlgorithm) {
91
+ FfiDigestAlgorithm[FfiDigestAlgorithm["SHA1"] = 0] = "SHA1";
92
+ FfiDigestAlgorithm[FfiDigestAlgorithm["SHA256"] = 1] = "SHA256";
93
+ FfiDigestAlgorithm[FfiDigestAlgorithm["SHA384"] = 2] = "SHA384";
94
+ FfiDigestAlgorithm[FfiDigestAlgorithm["SHA512"] = 3] = "SHA512";
95
+ })(FfiDigestAlgorithm || (FfiDigestAlgorithm = {}));
96
+ /**
97
+ * FFI signature subfilter constants for use with SignOptions.subfilter
98
+ */
99
+ export var FfiSignatureSubFilter;
100
+ (function (FfiSignatureSubFilter) {
101
+ FfiSignatureSubFilter[FfiSignatureSubFilter["PKCS7_DETACHED"] = 0] = "PKCS7_DETACHED";
102
+ FfiSignatureSubFilter[FfiSignatureSubFilter["PKCS7_SHA1"] = 1] = "PKCS7_SHA1";
103
+ FfiSignatureSubFilter[FfiSignatureSubFilter["CADES_DETACHED"] = 2] = "CADES_DETACHED";
104
+ })(FfiSignatureSubFilter || (FfiSignatureSubFilter = {}));
105
+ // =============================================================================
106
+ // Canonical SignatureManager
107
+ // =============================================================================
108
+ /**
109
+ * Canonical Signature Manager - all signature operations in one class.
110
+ *
111
+ * Provides:
112
+ * - Verification (from root SignatureManager)
113
+ * - Certificate loading (from SignatureCreationManager)
114
+ * - Document signing with timestamps and LTV (from SignatureCreationManager)
115
+ * - Detailed signature info (from SignaturesManager)
116
+ */
117
+ export class SignatureManager extends EventEmitter {
118
+ constructor(document) {
119
+ super();
120
+ this.resultCache = new Map();
121
+ this.maxCacheSize = 100;
122
+ this.loadedCertificates = new Map();
123
+ this.createdFields = new Map();
124
+ if (!document) {
125
+ throw new Error('Document cannot be null or undefined');
126
+ }
127
+ this.document = document;
128
+ try {
129
+ this.native = require('../../index.node');
130
+ }
131
+ catch {
132
+ this.native = null;
133
+ }
134
+ }
135
+ // ===========================================================================
136
+ // Verification (from root SignatureManager)
137
+ // ===========================================================================
138
+ async getSignatures() {
139
+ const cacheKey = 'signatures:all';
140
+ if (this.resultCache.has(cacheKey))
141
+ return this.resultCache.get(cacheKey);
142
+ let signatures = [];
143
+ if (this.native?.get_signatures) {
144
+ try {
145
+ const signaturesJson = this.native.get_signatures() ?? [];
146
+ signatures = signaturesJson.length > 0 ? JSON.parse(signaturesJson[0] || '[]') : [];
147
+ }
148
+ catch {
149
+ signatures = [];
150
+ }
151
+ }
152
+ this.setCached(cacheKey, signatures);
153
+ this.emit('signaturesRetrieved', { count: signatures.length });
154
+ return signatures;
155
+ }
156
+ async getSignatureFields() {
157
+ const cacheKey = 'signatures:fields';
158
+ if (this.resultCache.has(cacheKey))
159
+ return this.resultCache.get(cacheKey);
160
+ let fields = [];
161
+ if (this.native?.get_signature_fields) {
162
+ try {
163
+ const fieldsJson = this.native.get_signature_fields() ?? [];
164
+ fields = fieldsJson.length > 0 ? JSON.parse(fieldsJson[0] || '[]') : [];
165
+ }
166
+ catch {
167
+ fields = [];
168
+ }
169
+ }
170
+ this.setCached(cacheKey, fields);
171
+ return fields;
172
+ }
173
+ async verifySignatures() {
174
+ const cacheKey = 'signatures:verification';
175
+ if (this.resultCache.has(cacheKey))
176
+ return this.resultCache.get(cacheKey);
177
+ let result = { isValid: true, signatures: [], issues: [] };
178
+ if (this.native?.verify_signatures) {
179
+ try {
180
+ result = JSON.parse(this.native.verify_signatures());
181
+ }
182
+ catch {
183
+ /* defaults */
184
+ }
185
+ }
186
+ this.setCached(cacheKey, result);
187
+ this.emit('signaturesVerified', { isValid: result.isValid, issueCount: result.issues.length });
188
+ return result;
189
+ }
190
+ async verifySignature(signatureName) {
191
+ const cacheKey = `signatures:verify:${signatureName}`;
192
+ if (this.resultCache.has(cacheKey))
193
+ return this.resultCache.get(cacheKey);
194
+ let result = { isValid: true, signatures: [], issues: [] };
195
+ if (this.native?.verify_signature) {
196
+ try {
197
+ result = JSON.parse(this.native.verify_signature(signatureName));
198
+ }
199
+ catch {
200
+ /* defaults */
201
+ }
202
+ }
203
+ this.setCached(cacheKey, result);
204
+ return result;
205
+ }
206
+ async isCertified() {
207
+ const cacheKey = 'signatures:is_certified';
208
+ if (this.resultCache.has(cacheKey))
209
+ return this.resultCache.get(cacheKey);
210
+ const result = this.document?.isCertified?.() ?? this.native?.is_certified?.() ?? false;
211
+ this.setCached(cacheKey, result);
212
+ return result;
213
+ }
214
+ async getSignatureCount() {
215
+ const cacheKey = 'signatures:count';
216
+ if (this.resultCache.has(cacheKey))
217
+ return this.resultCache.get(cacheKey);
218
+ const count = this.document?.getSignatureCount?.() ?? this.native?.get_signature_count?.() ?? 0;
219
+ this.setCached(cacheKey, count);
220
+ return count;
221
+ }
222
+ async isSigned() {
223
+ return (await this.getSignatureCount()) > 0;
224
+ }
225
+ // ===========================================================================
226
+ // Certificate Loading (from SignatureCreationManager)
227
+ // ===========================================================================
228
+ async loadCertificateFromFile(filePath, password, format) {
229
+ try {
230
+ const certData = await fs.readFile(filePath);
231
+ return this.loadCertificateFromBytes(certData, password, format);
232
+ }
233
+ catch (error) {
234
+ this.emit('error', error);
235
+ return null;
236
+ }
237
+ }
238
+ async loadCertificateFromBytes(certData, password, format) {
239
+ try {
240
+ const certId = `cert_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
241
+ const nativeResult = await this.document?.loadCertificate?.(certData, password, format);
242
+ const info = nativeResult?.info ?? {
243
+ subject: nativeResult?.subject ?? 'Unknown',
244
+ issuer: nativeResult?.issuer ?? 'Unknown',
245
+ serialNumber: nativeResult?.serialNumber ?? '',
246
+ validFrom: new Date(nativeResult?.validFrom ?? Date.now()),
247
+ validTo: new Date(nativeResult?.validTo ?? Date.now() + 365 * 24 * 60 * 60 * 1000),
248
+ isValid: nativeResult?.isValid ?? false,
249
+ isSelfSigned: nativeResult?.isSelfSigned ?? false,
250
+ };
251
+ const loadedCert = {
252
+ certificateId: certId,
253
+ info,
254
+ hasPrivateKey: nativeResult?.hasPrivateKey ?? true,
255
+ chain: nativeResult?.chain,
256
+ };
257
+ this.loadedCertificates.set(certId, loadedCert);
258
+ this.emit('certificate-loaded', { certificateId: certId, subject: info.subject });
259
+ return loadedCert;
260
+ }
261
+ catch (error) {
262
+ this.emit('error', error);
263
+ return null;
264
+ }
265
+ }
266
+ async loadCertificateFromPem(certificatePem, privateKeyPem, privateKeyPassword) {
267
+ try {
268
+ const certId = `cert_pem_${Date.now()}`;
269
+ const nativeResult = await this.document?.loadCertificateFromPem?.(certificatePem, privateKeyPem, privateKeyPassword);
270
+ if (!nativeResult)
271
+ throw new Error('Failed to load PEM certificate');
272
+ const info = {
273
+ subject: nativeResult.subject ?? 'Unknown',
274
+ issuer: nativeResult.issuer ?? 'Unknown',
275
+ serialNumber: nativeResult.serialNumber ?? '',
276
+ validFrom: new Date(nativeResult.validFrom ?? Date.now()),
277
+ validTo: new Date(nativeResult.validTo ?? Date.now() + 365 * 24 * 60 * 60 * 1000),
278
+ isValid: nativeResult.isValid ?? false,
279
+ isSelfSigned: nativeResult.isSelfSigned ?? false,
280
+ };
281
+ const loadedCert = {
282
+ certificateId: certId,
283
+ info,
284
+ hasPrivateKey: !!privateKeyPem,
285
+ };
286
+ this.loadedCertificates.set(certId, loadedCert);
287
+ this.emit('certificate-loaded', { certificateId: certId, subject: info.subject });
288
+ return loadedCert;
289
+ }
290
+ catch (error) {
291
+ this.emit('error', error);
292
+ return null;
293
+ }
294
+ }
295
+ async getCertificateInfo(certificateId) {
296
+ return this.loadedCertificates.get(certificateId)?.info ?? null;
297
+ }
298
+ async getCertificateChain(certificateId) {
299
+ try {
300
+ const cert = this.loadedCertificates.get(certificateId);
301
+ if (!cert)
302
+ return null;
303
+ if (cert.chain)
304
+ return cert.chain;
305
+ return (await this.document?.getCertificateChain?.(certificateId)) ?? null;
306
+ }
307
+ catch (error) {
308
+ this.emit('error', error);
309
+ return null;
310
+ }
311
+ }
312
+ async validateCertificate(certificateId) {
313
+ try {
314
+ const cert = this.loadedCertificates.get(certificateId);
315
+ if (!cert)
316
+ return { valid: false, errors: ['Certificate not found'], warnings: [] };
317
+ const result = await this.document?.validateCertificate?.(certificateId);
318
+ return (result ?? {
319
+ valid: cert.info.isValid,
320
+ errors: cert.info.isValid ? [] : ['Certificate validation failed'],
321
+ warnings: [],
322
+ });
323
+ }
324
+ catch (error) {
325
+ this.emit('error', error);
326
+ return {
327
+ valid: false,
328
+ errors: [error instanceof Error ? error.message : 'Unknown error'],
329
+ warnings: [],
330
+ };
331
+ }
332
+ }
333
+ getLoadedCertificates() {
334
+ return Array.from(this.loadedCertificates.values());
335
+ }
336
+ unloadCertificate(certificateId) {
337
+ const deleted = this.loadedCertificates.delete(certificateId);
338
+ if (deleted)
339
+ this.emit('certificate-unloaded', { certificateId });
340
+ return deleted;
341
+ }
342
+ // ===========================================================================
343
+ // Signature Field Management (from SignatureCreationManager)
344
+ // ===========================================================================
345
+ async addSignatureField(config) {
346
+ try {
347
+ const result = await this.document?.addSignatureField?.(config.fieldName, config.pageIndex, config.x, config.y, config.width, config.height, {
348
+ appearance: config.appearance,
349
+ tooltip: config.tooltip,
350
+ isRequired: config.isRequired,
351
+ isReadOnly: config.isReadOnly,
352
+ });
353
+ if (result !== false) {
354
+ this.createdFields.set(config.fieldName, config);
355
+ this.clearCachePattern('signatures:');
356
+ this.emit('field-added', { fieldName: config.fieldName });
357
+ }
358
+ return result !== false;
359
+ }
360
+ catch (error) {
361
+ this.emit('error', error);
362
+ return false;
363
+ }
364
+ }
365
+ async removeSignatureField(fieldName) {
366
+ try {
367
+ const result = await this.document?.removeSignatureField?.(fieldName);
368
+ if (result) {
369
+ this.createdFields.delete(fieldName);
370
+ this.clearCachePattern('signatures:');
371
+ this.emit('field-removed', { fieldName });
372
+ }
373
+ return !!result;
374
+ }
375
+ catch (error) {
376
+ this.emit('error', error);
377
+ return false;
378
+ }
379
+ }
380
+ async getSignatureFieldNames() {
381
+ try {
382
+ return (await this.document?.getSignatureFields?.()) ?? [];
383
+ }
384
+ catch (error) {
385
+ this.emit('error', error);
386
+ return [];
387
+ }
388
+ }
389
+ async hasSignatureField(fieldName) {
390
+ try {
391
+ const fields = await this.getSignatureFieldNames();
392
+ return fields.includes(fieldName);
393
+ }
394
+ catch (error) {
395
+ this.emit('error', error);
396
+ return false;
397
+ }
398
+ }
399
+ async updateSignatureFieldAppearance(fieldName, appearance) {
400
+ try {
401
+ const result = await this.document?.updateSignatureFieldAppearance?.(fieldName, appearance);
402
+ this.emit('appearance-updated', { fieldName });
403
+ return !!result;
404
+ }
405
+ catch (error) {
406
+ this.emit('error', error);
407
+ return false;
408
+ }
409
+ }
410
+ // ===========================================================================
411
+ // Document Signing (from SignatureCreationManager)
412
+ // ===========================================================================
413
+ async signDocument(fieldName, certificate, options) {
414
+ try {
415
+ const certId = typeof certificate === 'string' ? certificate : certificate.certificateId;
416
+ const cert = this.loadedCertificates.get(certId);
417
+ if (!cert)
418
+ return { success: false, error: 'Certificate not found' };
419
+ if (!cert.hasPrivateKey)
420
+ return { success: false, error: 'Certificate does not have private key' };
421
+ const nativeResult = await this.document?.signDocument?.(fieldName, certId, {
422
+ reason: options?.reason,
423
+ location: options?.location,
424
+ contactInfo: options?.contactInfo,
425
+ signatureType: options?.signatureType ?? SignatureType.APPROVAL,
426
+ certificationPermission: options?.certificationPermission,
427
+ algorithm: options?.algorithm ?? SignatureAlgorithm.RSA_SHA256,
428
+ digestAlgorithm: options?.digestAlgorithm ?? DigestAlgorithm.SHA256,
429
+ appearance: options?.appearance,
430
+ });
431
+ const signingTime = new Date();
432
+ let timestampTime;
433
+ if (options?.embedTimestamp && options?.timestampServerUrl) {
434
+ const tsResult = await this.embedTimestamp(fieldName, {
435
+ serverUrl: options.timestampServerUrl,
436
+ hashAlgorithm: options.digestAlgorithm,
437
+ });
438
+ if (tsResult.status === TimestampStatus.SUCCESS)
439
+ timestampTime = tsResult.timestamp;
440
+ }
441
+ if (options?.enableLtv)
442
+ await this.enableLtvForSignature(fieldName, {
443
+ ocspResponderUrl: options.ocspResponderUrl,
444
+ crlDistributionPoints: options.crlDistributionPoints,
445
+ });
446
+ const signatureId = `sig_${fieldName}_${Date.now()}`;
447
+ this.clearCachePattern('signatures:');
448
+ this.emit('document-signed', { signatureId, fieldName, signingTime, timestampTime });
449
+ return {
450
+ success: true,
451
+ signatureId,
452
+ signingTime,
453
+ timestampTime,
454
+ warnings: nativeResult?.warnings,
455
+ };
456
+ }
457
+ catch (error) {
458
+ this.emit('error', error);
459
+ return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
460
+ }
461
+ }
462
+ async certifyDocument(fieldName, certificate, permission, options) {
463
+ return this.signDocument(fieldName, certificate, {
464
+ ...options,
465
+ signatureType: SignatureType.CERTIFICATION,
466
+ certificationPermission: permission,
467
+ });
468
+ }
469
+ async signInvisibly(certificate, options) {
470
+ try {
471
+ const fieldName = `InvisibleSig_${Date.now()}`;
472
+ await this.addSignatureField({ fieldName, pageIndex: 0, x: 0, y: 0, width: 0, height: 0 });
473
+ return this.signDocument(fieldName, certificate, options);
474
+ }
475
+ catch (error) {
476
+ this.emit('error', error);
477
+ return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
478
+ }
479
+ }
480
+ async counterSign(certificate, options) {
481
+ try {
482
+ const fieldName = `CounterSig_${Date.now()}`;
483
+ await this.addSignatureField({
484
+ fieldName,
485
+ pageIndex: 0,
486
+ x: 100,
487
+ y: 100,
488
+ width: 200,
489
+ height: 50,
490
+ appearance: options?.appearance,
491
+ });
492
+ return this.signDocument(fieldName, certificate, options);
493
+ }
494
+ catch (error) {
495
+ this.emit('error', error);
496
+ return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
497
+ }
498
+ }
499
+ async signMultipleFields(signings) {
500
+ const results = [];
501
+ for (const signing of signings) {
502
+ const result = await this.signDocument(signing.fieldName, signing.certificate, signing.options);
503
+ results.push(result);
504
+ if (!result.success)
505
+ break;
506
+ }
507
+ return results;
508
+ }
509
+ async prepareForExternalSigning(fieldName, options) {
510
+ try {
511
+ const result = await this.document?.prepareForExternalSigning?.(fieldName, {
512
+ estimatedSize: options?.estimatedSize ?? 8192,
513
+ digestAlgorithm: options?.digestAlgorithm ?? DigestAlgorithm.SHA256,
514
+ });
515
+ this.emit('prepared-for-external-signing', { fieldName });
516
+ return result ?? null;
517
+ }
518
+ catch (error) {
519
+ this.emit('error', error);
520
+ return null;
521
+ }
522
+ }
523
+ // ===========================================================================
524
+ // Timestamp Operations (from SignatureCreationManager)
525
+ // ===========================================================================
526
+ async embedTimestamp(fieldName, config) {
527
+ try {
528
+ const result = await this.document?.embedTimestamp?.(fieldName, {
529
+ serverUrl: config.serverUrl,
530
+ username: config.username,
531
+ password: config.password,
532
+ hashAlgorithm: config.hashAlgorithm ?? DigestAlgorithm.SHA256,
533
+ timeout: config.timeout ?? 30000,
534
+ policy: config.policy,
535
+ nonce: config.nonce ?? true,
536
+ certReq: config.certReq ?? true,
537
+ });
538
+ if (result?.success) {
539
+ this.emit('timestamp-embedded', { fieldName, timestamp: result.timestamp });
540
+ return {
541
+ status: TimestampStatus.SUCCESS,
542
+ timestamp: new Date(result.timestamp),
543
+ serialNumber: result.serialNumber,
544
+ tsaName: result.tsaName,
545
+ };
546
+ }
547
+ return {
548
+ status: TimestampStatus.FAILED,
549
+ error: result?.error ?? 'Timestamp embedding failed',
550
+ };
551
+ }
552
+ catch (error) {
553
+ this.emit('error', error);
554
+ return {
555
+ status: TimestampStatus.FAILED,
556
+ error: error instanceof Error ? error.message : 'Unknown error',
557
+ };
558
+ }
559
+ }
560
+ async addDocumentTimestamp(config) {
561
+ try {
562
+ const fieldName = `DocTimestamp_${Date.now()}`;
563
+ await this.addSignatureField({ fieldName, pageIndex: 0, x: 0, y: 0, width: 0, height: 0 });
564
+ const result = await this.document?.addDocumentTimestamp?.(fieldName, config);
565
+ if (result?.success) {
566
+ this.emit('document-timestamp-added', { timestamp: result.timestamp });
567
+ return {
568
+ status: TimestampStatus.SUCCESS,
569
+ timestamp: new Date(result.timestamp),
570
+ serialNumber: result.serialNumber,
571
+ tsaName: result.tsaName,
572
+ };
573
+ }
574
+ return {
575
+ status: TimestampStatus.FAILED,
576
+ error: result?.error ?? 'Document timestamp failed',
577
+ };
578
+ }
579
+ catch (error) {
580
+ this.emit('error', error);
581
+ return {
582
+ status: TimestampStatus.FAILED,
583
+ error: error instanceof Error ? error.message : 'Unknown error',
584
+ };
585
+ }
586
+ }
587
+ async validateTimestamp(fieldName) {
588
+ try {
589
+ return ((await this.document?.validateTimestamp?.(fieldName)) ?? {
590
+ valid: false,
591
+ errors: ['Timestamp validation not available'],
592
+ });
593
+ }
594
+ catch (error) {
595
+ this.emit('error', error);
596
+ return { valid: false, errors: [error instanceof Error ? error.message : 'Unknown error'] };
597
+ }
598
+ }
599
+ async getTimestampInfo(fieldName) {
600
+ try {
601
+ return (await this.document?.getTimestampInfo?.(fieldName)) ?? null;
602
+ }
603
+ catch (error) {
604
+ this.emit('error', error);
605
+ return null;
606
+ }
607
+ }
608
+ // ===========================================================================
609
+ // LTV Operations (from SignatureCreationManager)
610
+ // ===========================================================================
611
+ async enableLtvForSignature(fieldName, options) {
612
+ try {
613
+ const result = await this.document?.enableLtvForSignature?.(fieldName, {
614
+ ocspResponderUrl: options?.ocspResponderUrl,
615
+ crlDistributionPoints: options?.crlDistributionPoints,
616
+ });
617
+ if (result)
618
+ this.emit('ltv-enabled', { fieldName });
619
+ return !!result;
620
+ }
621
+ catch (error) {
622
+ this.emit('error', error);
623
+ return false;
624
+ }
625
+ }
626
+ async enableLtvForAllSignatures(options) {
627
+ try {
628
+ const fields = await this.getSignatureFieldNames();
629
+ let count = 0;
630
+ for (const field of fields) {
631
+ if (await this.enableLtvForSignature(field, options))
632
+ count++;
633
+ }
634
+ return count;
635
+ }
636
+ catch (error) {
637
+ this.emit('error', error);
638
+ return 0;
639
+ }
640
+ }
641
+ async addValidationInfo(fieldName, info) {
642
+ try {
643
+ const result = await this.document?.addValidationInfo?.(fieldName, info);
644
+ if (result)
645
+ this.emit('validation-info-added', { fieldName });
646
+ return !!result;
647
+ }
648
+ catch (error) {
649
+ this.emit('error', error);
650
+ return false;
651
+ }
652
+ }
653
+ async hasLtvEnabled(fieldName) {
654
+ try {
655
+ return (await this.document?.hasLtvEnabled?.(fieldName)) ?? false;
656
+ }
657
+ catch (error) {
658
+ this.emit('error', error);
659
+ return false;
660
+ }
661
+ }
662
+ // ===========================================================================
663
+ // Signature Details (from SignaturesManager)
664
+ // ===========================================================================
665
+ async getSignerName(index) {
666
+ try {
667
+ return (await this.document?.getSignerName?.(index)) || '';
668
+ }
669
+ catch {
670
+ return '';
671
+ }
672
+ }
673
+ async getSigningTime(index) {
674
+ try {
675
+ return (await this.document?.getSigningTime?.(index)) || 0;
676
+ }
677
+ catch {
678
+ return 0;
679
+ }
680
+ }
681
+ async getSigningReason(index) {
682
+ try {
683
+ return (await this.document?.getSigningReason?.(index)) || null;
684
+ }
685
+ catch {
686
+ return null;
687
+ }
688
+ }
689
+ async getSigningLocation(index) {
690
+ try {
691
+ return (await this.document?.getSigningLocation?.(index)) || null;
692
+ }
693
+ catch {
694
+ return null;
695
+ }
696
+ }
697
+ async getCertificateSubject(index) {
698
+ try {
699
+ return (await this.document?.getCertificateSubject?.(index)) || '';
700
+ }
701
+ catch {
702
+ return '';
703
+ }
704
+ }
705
+ async getCertificateIssuer(index) {
706
+ try {
707
+ return (await this.document?.getCertificateIssuer?.(index)) || '';
708
+ }
709
+ catch {
710
+ return '';
711
+ }
712
+ }
713
+ async getCertificateSerial(index) {
714
+ try {
715
+ return (await this.document?.getCertificateSerial?.(index)) || '';
716
+ }
717
+ catch {
718
+ return '';
719
+ }
720
+ }
721
+ async getCertificateValidity(index) {
722
+ try {
723
+ return (await this.document?.getCertificateValidity?.(index)) || [0, 0];
724
+ }
725
+ catch {
726
+ return [0, 0];
727
+ }
728
+ }
729
+ async getSignatureDetails(index) {
730
+ try {
731
+ const [notBefore, notAfter] = await this.getCertificateValidity(index);
732
+ const certificate = {
733
+ subject: await this.getCertificateSubject(index),
734
+ issuer: await this.getCertificateIssuer(index),
735
+ serial: await this.getCertificateSerial(index),
736
+ notBefore,
737
+ notAfter,
738
+ isValid: await this.isCertificateValidByIndex(index),
739
+ };
740
+ return {
741
+ signerName: await this.getSignerName(index),
742
+ signingTime: await this.getSigningTime(index),
743
+ reason: (await this.getSigningReason(index)) || undefined,
744
+ location: (await this.getSigningLocation(index)) || undefined,
745
+ certificate,
746
+ isValid: true,
747
+ };
748
+ }
749
+ catch (error) {
750
+ this.emit('error', error);
751
+ return null;
752
+ }
753
+ }
754
+ async isCertificateValidByIndex(index) {
755
+ try {
756
+ return (await this.document?.isCertificateValid?.(index)) || false;
757
+ }
758
+ catch {
759
+ return false;
760
+ }
761
+ }
762
+ // ===========================================================================
763
+ // FFI-Based Document Signing (Phase 1)
764
+ // ===========================================================================
765
+ /**
766
+ * Load signing credentials from a PKCS#12 (.p12/.pfx) file.
767
+ *
768
+ * Calls the native `pdf_credentials_from_pkcs12` FFI function to load
769
+ * a certificate and private key from a PKCS#12 container.
770
+ *
771
+ * @param filePath - Path to the .p12 or .pfx file
772
+ * @param password - Password to decrypt the PKCS#12 file
773
+ * @returns SigningCredentials handle for use with signing methods
774
+ * @throws SignatureException if the file cannot be loaded or the password is incorrect
775
+ *
776
+ * @example
777
+ * ```typescript
778
+ * const credentials = await sigManager.loadCredentialsPkcs12('/path/to/cert.p12', 'password');
779
+ * const signed = await sigManager.signWithPkcs12(pdfData, '/path/to/cert.p12', 'password');
780
+ * ```
781
+ */
782
+ async loadCredentialsPkcs12(filePath, password) {
783
+ if (!this.native?.pdf_credentials_from_pkcs12) {
784
+ throw new SignatureException('Native signing not available: pdf_credentials_from_pkcs12 not found');
785
+ }
786
+ const errorCode = Buffer.alloc(4);
787
+ const handle = this.native.pdf_credentials_from_pkcs12(filePath, password, errorCode);
788
+ const code = errorCode.readInt32LE(0);
789
+ if (code !== 0 || !handle) {
790
+ throw mapFfiErrorCode(code, `Failed to load PKCS#12 credentials from ${filePath}`);
791
+ }
792
+ this.emit('credentials-loaded', { sourceType: 'pkcs12', filePath });
793
+ return { _handle: handle, sourceType: 'pkcs12' };
794
+ }
795
+ /**
796
+ * Load signing credentials from PEM certificate and key files.
797
+ *
798
+ * Calls the native `pdf_credentials_from_pem` FFI function to load
799
+ * credentials from separate PEM-encoded certificate and private key files.
800
+ *
801
+ * @param certFile - Path to the PEM certificate file
802
+ * @param keyFile - Path to the PEM private key file
803
+ * @param keyPassword - Optional password for an encrypted private key
804
+ * @returns SigningCredentials handle for use with signing methods
805
+ * @throws SignatureException if the files cannot be loaded
806
+ *
807
+ * @example
808
+ * ```typescript
809
+ * const credentials = await sigManager.loadCredentialsPem('/path/to/cert.pem', '/path/to/key.pem');
810
+ * ```
811
+ */
812
+ async loadCredentialsPem(certFile, keyFile, keyPassword) {
813
+ if (!this.native?.pdf_credentials_from_pem) {
814
+ throw new SignatureException('Native signing not available: pdf_credentials_from_pem not found');
815
+ }
816
+ const errorCode = Buffer.alloc(4);
817
+ const handle = this.native.pdf_credentials_from_pem(certFile, keyFile, keyPassword ?? null, errorCode);
818
+ const code = errorCode.readInt32LE(0);
819
+ if (code !== 0 || !handle) {
820
+ throw mapFfiErrorCode(code, `Failed to load PEM credentials from ${certFile} and ${keyFile}`);
821
+ }
822
+ this.emit('credentials-loaded', { sourceType: 'pem', certFile, keyFile });
823
+ return { _handle: handle, sourceType: 'pem' };
824
+ }
825
+ /**
826
+ * Free signing credentials when they are no longer needed.
827
+ *
828
+ * Calls the native `pdf_credentials_free` FFI function to release
829
+ * memory associated with the credentials handle.
830
+ *
831
+ * @param credentials - The credentials handle to free
832
+ *
833
+ * @example
834
+ * ```typescript
835
+ * const credentials = await sigManager.loadCredentialsPkcs12(path, password);
836
+ * // ... use credentials for signing ...
837
+ * sigManager.freeCredentials(credentials);
838
+ * ```
839
+ */
840
+ freeCredentials(credentials) {
841
+ if (credentials._handle && this.native?.pdf_credentials_free) {
842
+ this.native.pdf_credentials_free(credentials._handle);
843
+ this.emit('credentials-freed', { sourceType: credentials.sourceType });
844
+ }
845
+ }
846
+ /**
847
+ * Sign a PDF document in memory using PKCS#12 credentials.
848
+ *
849
+ * Loads credentials from a PKCS#12 file, signs the PDF data, and returns
850
+ * the signed PDF bytes. Credentials are automatically freed after signing.
851
+ *
852
+ * @param pdfData - Buffer containing the PDF document bytes
853
+ * @param filePath - Path to the .p12 or .pfx certificate file
854
+ * @param password - Password for the PKCS#12 file
855
+ * @param options - Optional signing parameters (reason, location, contact, algorithm, subfilter)
856
+ * @returns Buffer containing the signed PDF document
857
+ * @throws SignatureException if credential loading or signing fails
858
+ *
859
+ * @example
860
+ * ```typescript
861
+ * const pdfData = await fs.readFile('document.pdf');
862
+ * const signed = await sigManager.signWithPkcs12(pdfData, 'cert.p12', 'password', {
863
+ * reason: 'Approval',
864
+ * location: 'New York',
865
+ * contact: 'signer@example.com',
866
+ * });
867
+ * await fs.writeFile('signed.pdf', signed);
868
+ * ```
869
+ */
870
+ async signWithPkcs12(pdfData, filePath, password, options) {
871
+ const credentials = await this.loadCredentialsPkcs12(filePath, password);
872
+ try {
873
+ return await this.signWithCredentials(pdfData, credentials, options);
874
+ }
875
+ finally {
876
+ this.freeCredentials(credentials);
877
+ }
878
+ }
879
+ /**
880
+ * Sign a PDF document in memory using PEM credentials.
881
+ *
882
+ * Loads credentials from PEM files, signs the PDF data, and returns
883
+ * the signed PDF bytes. Credentials are automatically freed after signing.
884
+ *
885
+ * @param pdfData - Buffer containing the PDF document bytes
886
+ * @param certFile - Path to the PEM certificate file
887
+ * @param keyFile - Path to the PEM private key file
888
+ * @param options - Optional signing parameters (reason, location, contact, algorithm, subfilter)
889
+ * @returns Buffer containing the signed PDF document
890
+ * @throws SignatureException if credential loading or signing fails
891
+ *
892
+ * @example
893
+ * ```typescript
894
+ * const pdfData = await fs.readFile('document.pdf');
895
+ * const signed = await sigManager.signWithPem(pdfData, 'cert.pem', 'key.pem', {
896
+ * reason: 'Review complete',
897
+ * location: 'London',
898
+ * });
899
+ * await fs.writeFile('signed.pdf', signed);
900
+ * ```
901
+ */
902
+ async signWithPem(pdfData, certFile, keyFile, options) {
903
+ const credentials = await this.loadCredentialsPem(certFile, keyFile);
904
+ try {
905
+ return await this.signWithCredentials(pdfData, credentials, options);
906
+ }
907
+ finally {
908
+ this.freeCredentials(credentials);
909
+ }
910
+ }
911
+ /**
912
+ * Sign a PDF document in memory using pre-loaded credentials.
913
+ *
914
+ * Calls the native `pdf_document_sign` FFI function to apply a digital
915
+ * signature to the PDF data using the provided credentials handle.
916
+ *
917
+ * @param pdfData - Buffer containing the PDF document bytes
918
+ * @param credentials - Pre-loaded signing credentials handle
919
+ * @param options - Optional signing parameters
920
+ * @returns Buffer containing the signed PDF document
921
+ * @throws SignatureException if signing fails
922
+ *
923
+ * @example
924
+ * ```typescript
925
+ * const credentials = await sigManager.loadCredentialsPkcs12(path, password);
926
+ * const signed = await sigManager.signWithCredentials(pdfData, credentials, {
927
+ * reason: 'Approved',
928
+ * algorithm: FfiDigestAlgorithm.SHA256,
929
+ * subfilter: FfiSignatureSubFilter.PKCS7_DETACHED,
930
+ * });
931
+ * sigManager.freeCredentials(credentials);
932
+ * ```
933
+ */
934
+ async signWithCredentials(pdfData, credentials, options) {
935
+ if (!this.native?.pdf_document_sign) {
936
+ throw new SignatureException('Native signing not available: pdf_document_sign not found');
937
+ }
938
+ if (!credentials._handle) {
939
+ throw new SignatureException('Invalid credentials: handle is null');
940
+ }
941
+ const errorCode = Buffer.alloc(4);
942
+ const outDataPtr = Buffer.alloc(8); // pointer to output data
943
+ const outLen = Buffer.alloc(8); // output length (size_t)
944
+ const algorithm = options?.algorithm ?? FfiDigestAlgorithm.SHA256;
945
+ const subfilter = options?.subfilter ?? FfiSignatureSubFilter.PKCS7_DETACHED;
946
+ const success = this.native.pdf_document_sign(pdfData, pdfData.length, credentials._handle, options?.reason ?? null, options?.location ?? null, options?.contact ?? null, algorithm, subfilter, outDataPtr, outLen, errorCode);
947
+ const code = errorCode.readInt32LE(0);
948
+ if (!success || code !== 0) {
949
+ throw mapFfiErrorCode(code, 'Failed to sign PDF document');
950
+ }
951
+ // Read the output buffer from the native pointer
952
+ const resultLen = Number(outLen.readBigUInt64LE(0));
953
+ const resultData = this.native.pdf_read_signed_bytes(outDataPtr, resultLen);
954
+ // Free the native signed bytes buffer
955
+ if (this.native.pdf_signed_bytes_free) {
956
+ this.native.pdf_signed_bytes_free(outDataPtr, resultLen);
957
+ }
958
+ this.clearCachePattern('signatures:');
959
+ this.emit('document-signed-ffi', {
960
+ reason: options?.reason,
961
+ location: options?.location,
962
+ algorithm,
963
+ subfilter,
964
+ });
965
+ return Buffer.from(resultData);
966
+ }
967
+ /**
968
+ * Sign a PDF file on disk and write the signed output to another file.
969
+ *
970
+ * Calls the native `pdf_document_sign_file` FFI function, which reads
971
+ * the input file, applies a digital signature, and writes the result
972
+ * to the output path.
973
+ *
974
+ * @param inputPath - Path to the input PDF file
975
+ * @param outputPath - Path to write the signed PDF file
976
+ * @param credentials - Pre-loaded signing credentials handle
977
+ * @param options - Optional signing parameters
978
+ * @throws SignatureException if file signing fails
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * const credentials = await sigManager.loadCredentialsPkcs12('cert.p12', 'pass');
983
+ * await sigManager.signFile('input.pdf', 'signed.pdf', credentials, {
984
+ * reason: 'Final approval',
985
+ * location: 'Berlin',
986
+ * });
987
+ * sigManager.freeCredentials(credentials);
988
+ * ```
989
+ */
990
+ async signFile(inputPath, outputPath, credentials, options) {
991
+ if (!this.native?.pdf_document_sign_file) {
992
+ throw new SignatureException('Native signing not available: pdf_document_sign_file not found');
993
+ }
994
+ if (!credentials._handle) {
995
+ throw new SignatureException('Invalid credentials: handle is null');
996
+ }
997
+ const errorCode = Buffer.alloc(4);
998
+ const algorithm = options?.algorithm ?? FfiDigestAlgorithm.SHA256;
999
+ const subfilter = options?.subfilter ?? FfiSignatureSubFilter.PKCS7_DETACHED;
1000
+ const success = this.native.pdf_document_sign_file(inputPath, outputPath, credentials._handle, options?.reason ?? null, options?.location ?? null, options?.contact ?? null, algorithm, subfilter, errorCode);
1001
+ const code = errorCode.readInt32LE(0);
1002
+ if (!success || code !== 0) {
1003
+ throw mapFfiErrorCode(code, `Failed to sign PDF file ${inputPath}`);
1004
+ }
1005
+ this.clearCachePattern('signatures:');
1006
+ this.emit('file-signed', { inputPath, outputPath });
1007
+ }
1008
+ /**
1009
+ * Embed Long-Term Validation (LTV) data into a signed PDF.
1010
+ *
1011
+ * Calls the native `pdf_embed_ltv_data` FFI function to add OCSP responses
1012
+ * and/or CRL data to the document's DSS (Document Security Store), enabling
1013
+ * long-term signature validation even after certificates expire.
1014
+ *
1015
+ * @param pdfData - Buffer containing the signed PDF document bytes
1016
+ * @param ocspData - Optional OCSP response data to embed
1017
+ * @param crlData - Optional CRL data to embed
1018
+ * @returns Buffer containing the PDF with embedded LTV data
1019
+ * @throws SignatureException if LTV embedding fails
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * const signedPdf = await sigManager.signWithPkcs12(pdfData, 'cert.p12', 'pass');
1024
+ * const ocspResponse = await fetch('http://ocsp.example.com/...').then(r => r.buffer());
1025
+ * const ltvPdf = await sigManager.embedLtv(signedPdf, ocspResponse);
1026
+ * await fs.writeFile('signed-ltv.pdf', ltvPdf);
1027
+ * ```
1028
+ */
1029
+ async embedLtv(pdfData, ocspData, crlData) {
1030
+ if (!this.native?.pdf_embed_ltv_data) {
1031
+ throw new SignatureException('Native LTV embedding not available: pdf_embed_ltv_data not found');
1032
+ }
1033
+ const errorCode = Buffer.alloc(4);
1034
+ const outDataPtr = Buffer.alloc(8);
1035
+ const outLen = Buffer.alloc(8);
1036
+ const success = this.native.pdf_embed_ltv_data(pdfData, pdfData.length, ocspData ?? null, ocspData?.length ?? 0, crlData ?? null, crlData?.length ?? 0, outDataPtr, outLen, errorCode);
1037
+ const code = errorCode.readInt32LE(0);
1038
+ if (!success || code !== 0) {
1039
+ throw mapFfiErrorCode(code, 'Failed to embed LTV data into PDF');
1040
+ }
1041
+ const resultLen = Number(outLen.readBigUInt64LE(0));
1042
+ const resultData = this.native.pdf_read_signed_bytes(outDataPtr, resultLen);
1043
+ if (this.native.pdf_signed_bytes_free) {
1044
+ this.native.pdf_signed_bytes_free(outDataPtr, resultLen);
1045
+ }
1046
+ this.emit('ltv-embedded-ffi', {
1047
+ hasOcsp: !!ocspData,
1048
+ hasCrl: !!crlData,
1049
+ });
1050
+ return Buffer.from(resultData);
1051
+ }
1052
+ /**
1053
+ * Save signed PDF bytes to a file.
1054
+ *
1055
+ * Calls the native `pdf_document_save_signed` FFI function to write
1056
+ * signed PDF data to disk.
1057
+ *
1058
+ * @param pdfData - Buffer containing the signed PDF bytes
1059
+ * @param outputPath - Path to write the signed PDF file
1060
+ * @throws SignatureException or IoException if saving fails
1061
+ *
1062
+ * @example
1063
+ * ```typescript
1064
+ * const signed = await sigManager.signWithPkcs12(pdfData, 'cert.p12', 'pass');
1065
+ * await sigManager.saveSigned(signed, '/output/signed.pdf');
1066
+ * ```
1067
+ */
1068
+ async saveSigned(pdfData, outputPath) {
1069
+ if (!this.native?.pdf_document_save_signed) {
1070
+ // Fallback to Node.js file I/O if native function is not available
1071
+ await fs.writeFile(outputPath, pdfData);
1072
+ this.emit('signed-saved', { outputPath, method: 'node-fs' });
1073
+ return;
1074
+ }
1075
+ const errorCode = Buffer.alloc(4);
1076
+ const success = this.native.pdf_document_save_signed(pdfData, pdfData.length, outputPath, errorCode);
1077
+ const code = errorCode.readInt32LE(0);
1078
+ if (!success || code !== 0) {
1079
+ throw mapFfiErrorCode(code, `Failed to save signed PDF to ${outputPath}`);
1080
+ }
1081
+ this.emit('signed-saved', { outputPath, method: 'native-ffi' });
1082
+ }
1083
+ // ===========================================================================
1084
+ // FFI-Based DER Credential Loading
1085
+ // ===========================================================================
1086
+ /**
1087
+ * Load signing credentials from raw DER-encoded certificate and key bytes.
1088
+ *
1089
+ * Calls the native `pdf_credentials_from_der` FFI function to create
1090
+ * credentials from in-memory DER-encoded certificate data and an optional
1091
+ * private key.
1092
+ *
1093
+ * @param certData - Buffer containing DER-encoded certificate bytes
1094
+ * @param keyData - Optional Buffer containing DER-encoded private key bytes
1095
+ * @returns SigningCredentials handle for use with signing methods
1096
+ * @throws SignatureException if credential loading fails
1097
+ *
1098
+ * @example
1099
+ * ```typescript
1100
+ * const certDer = await fs.readFile('cert.der');
1101
+ * const keyDer = await fs.readFile('key.der');
1102
+ * const credentials = await sigManager.loadCredentialsFromDer(certDer, keyDer);
1103
+ * const signed = await sigManager.signWithCredentials(pdfData, credentials);
1104
+ * sigManager.freeCredentials(credentials);
1105
+ * ```
1106
+ */
1107
+ async loadCredentialsFromDer(certData, keyData) {
1108
+ if (!this.native?.pdf_credentials_from_der) {
1109
+ throw new SignatureException('Native signing not available: pdf_credentials_from_der not found');
1110
+ }
1111
+ if (!certData || certData.length === 0) {
1112
+ throw new SignatureException('Certificate data cannot be null or empty');
1113
+ }
1114
+ const errorCode = Buffer.alloc(4);
1115
+ const handle = this.native.pdf_credentials_from_der(certData, certData.length, keyData ?? null, keyData?.length ?? 0, errorCode);
1116
+ const code = errorCode.readInt32LE(0);
1117
+ if (code !== 0 || !handle) {
1118
+ throw mapFfiErrorCode(code, 'Failed to load DER credentials');
1119
+ }
1120
+ this.emit('credentials-loaded', { sourceType: 'der' });
1121
+ return { _handle: handle, sourceType: 'pkcs12' }; // DER is treated as raw cert/key
1122
+ }
1123
+ /**
1124
+ * Add a certificate chain entry to existing signing credentials.
1125
+ *
1126
+ * Calls the native `pdf_credentials_add_chain_cert` FFI function to append
1127
+ * an intermediate or root CA certificate to the credential's certificate chain.
1128
+ * This is used to build a complete certification chain for signature validation.
1129
+ *
1130
+ * @param credentials - The signing credentials handle to modify
1131
+ * @param certData - Buffer containing DER-encoded certificate bytes
1132
+ * @throws SignatureException if the chain certificate cannot be added
1133
+ *
1134
+ * @example
1135
+ * ```typescript
1136
+ * const credentials = await sigManager.loadCredentialsFromDer(certDer, keyDer);
1137
+ * const intermediateCa = await fs.readFile('intermediate-ca.der');
1138
+ * await sigManager.addChainCert(credentials, intermediateCa);
1139
+ * ```
1140
+ */
1141
+ async addChainCert(credentials, certData) {
1142
+ if (!this.native?.pdf_credentials_add_chain_cert) {
1143
+ throw new SignatureException('Native signing not available: pdf_credentials_add_chain_cert not found');
1144
+ }
1145
+ if (!credentials._handle) {
1146
+ throw new SignatureException('Invalid credentials: handle is null');
1147
+ }
1148
+ if (!certData || certData.length === 0) {
1149
+ throw new SignatureException('Certificate data cannot be null or empty');
1150
+ }
1151
+ const errorCode = Buffer.alloc(4);
1152
+ const success = this.native.pdf_credentials_add_chain_cert(credentials._handle, certData, certData.length, errorCode);
1153
+ const code = errorCode.readInt32LE(0);
1154
+ if (!success || code !== 0) {
1155
+ throw mapFfiErrorCode(code, 'Failed to add chain certificate');
1156
+ }
1157
+ this.emit('chain-cert-added', { sourceType: credentials.sourceType });
1158
+ }
1159
+ /**
1160
+ * Get the certificate handle from signing credentials.
1161
+ *
1162
+ * Calls the native `pdf_credentials_get_certificate` FFI function to extract
1163
+ * the certificate handle from a credentials object. The returned handle can be
1164
+ * used with certificate inspection methods like getCertificateCn, getCertificateIssuer,
1165
+ * and getCertificateSize.
1166
+ *
1167
+ * @param credentials - The signing credentials handle
1168
+ * @returns An opaque certificate handle for use with certificate inspection methods
1169
+ * @throws SignatureException if the certificate cannot be retrieved
1170
+ *
1171
+ * @example
1172
+ * ```typescript
1173
+ * const credentials = await sigManager.loadCredentialsPkcs12('cert.p12', 'pass');
1174
+ * const certHandle = await sigManager.getCertificate(credentials);
1175
+ * const cn = await sigManager.getCertificateCn(certHandle);
1176
+ * console.log(`Certificate CN: ${cn}`);
1177
+ * sigManager.freeCredentials(credentials);
1178
+ * ```
1179
+ */
1180
+ async getCertificate(credentials) {
1181
+ if (!this.native?.pdf_credentials_get_certificate) {
1182
+ throw new SignatureException('Native signing not available: pdf_credentials_get_certificate not found');
1183
+ }
1184
+ if (!credentials._handle) {
1185
+ throw new SignatureException('Invalid credentials: handle is null');
1186
+ }
1187
+ const errorCode = Buffer.alloc(4);
1188
+ const certHandle = this.native.pdf_credentials_get_certificate(credentials._handle, errorCode);
1189
+ const code = errorCode.readInt32LE(0);
1190
+ if (code !== 0 || !certHandle) {
1191
+ throw mapFfiErrorCode(code, 'Failed to get certificate from credentials');
1192
+ }
1193
+ return certHandle;
1194
+ }
1195
+ /**
1196
+ * Load a certificate from raw DER bytes for inspection.
1197
+ *
1198
+ * Calls the native `pdf_certificate_load_from_bytes` FFI function to create
1199
+ * a certificate handle from DER-encoded bytes. This is useful for inspecting
1200
+ * certificate properties without creating full signing credentials.
1201
+ *
1202
+ * @param certData - Buffer containing DER-encoded certificate bytes
1203
+ * @returns An opaque certificate handle for use with certificate inspection methods
1204
+ * @throws SignatureException if the certificate cannot be loaded
1205
+ *
1206
+ * @example
1207
+ * ```typescript
1208
+ * const certDer = await fs.readFile('cert.der');
1209
+ * const certHandle = await sigManager.loadCertificateFromDerBytes(certDer);
1210
+ * const cn = await sigManager.getCertificateCn(certHandle);
1211
+ * const issuer = await sigManager.getCertificateIssuerFromHandle(certHandle);
1212
+ * const size = await sigManager.getCertificateSize(certHandle);
1213
+ * ```
1214
+ */
1215
+ async loadCertificateFromDerBytes(certData) {
1216
+ if (!this.native?.pdf_certificate_load_from_bytes) {
1217
+ throw new SignatureException('Native signing not available: pdf_certificate_load_from_bytes not found');
1218
+ }
1219
+ if (!certData || certData.length === 0) {
1220
+ throw new SignatureException('Certificate data cannot be null or empty');
1221
+ }
1222
+ const errorCode = Buffer.alloc(4);
1223
+ const certHandle = this.native.pdf_certificate_load_from_bytes(certData, certData.length, errorCode);
1224
+ const code = errorCode.readInt32LE(0);
1225
+ if (code !== 0 || !certHandle) {
1226
+ throw mapFfiErrorCode(code, 'Failed to load certificate from bytes');
1227
+ }
1228
+ return certHandle;
1229
+ }
1230
+ /**
1231
+ * Get the common name (CN) from a certificate handle.
1232
+ *
1233
+ * Calls the native `pdf_certificate_get_cn` FFI function to extract
1234
+ * the subject common name from a certificate.
1235
+ *
1236
+ * @param certHandle - An opaque certificate handle obtained from getCertificate or loadCertificateFromDerBytes
1237
+ * @returns The certificate common name string
1238
+ * @throws SignatureException if the CN cannot be retrieved
1239
+ *
1240
+ * @example
1241
+ * ```typescript
1242
+ * const credentials = await sigManager.loadCredentialsPkcs12('cert.p12', 'pass');
1243
+ * const certHandle = await sigManager.getCertificate(credentials);
1244
+ * const cn = await sigManager.getCertificateCn(certHandle);
1245
+ * console.log(`Signer: ${cn}`);
1246
+ * ```
1247
+ */
1248
+ async getCertificateCn(certHandle) {
1249
+ if (!this.native?.pdf_certificate_get_cn) {
1250
+ throw new SignatureException('Native signing not available: pdf_certificate_get_cn not found');
1251
+ }
1252
+ if (!certHandle) {
1253
+ throw new SignatureException('Invalid certificate handle: handle is null');
1254
+ }
1255
+ const errorCode = Buffer.alloc(4);
1256
+ const resultPtr = this.native.pdf_certificate_get_cn(certHandle, errorCode);
1257
+ const code = errorCode.readInt32LE(0);
1258
+ if (code !== 0 || !resultPtr) {
1259
+ throw mapFfiErrorCode(code, 'Failed to get certificate CN');
1260
+ }
1261
+ const cn = typeof resultPtr === 'string' ? resultPtr : resultPtr.toString();
1262
+ return cn;
1263
+ }
1264
+ /**
1265
+ * Get the issuer name from a certificate handle.
1266
+ *
1267
+ * Calls the native `pdf_certificate_get_issuer` FFI function to extract
1268
+ * the issuer distinguished name from a certificate.
1269
+ *
1270
+ * @param certHandle - An opaque certificate handle obtained from getCertificate or loadCertificateFromDerBytes
1271
+ * @returns The certificate issuer name string
1272
+ * @throws SignatureException if the issuer cannot be retrieved
1273
+ *
1274
+ * @example
1275
+ * ```typescript
1276
+ * const certHandle = await sigManager.loadCertificateFromDerBytes(certDer);
1277
+ * const issuer = await sigManager.getCertificateIssuerFromHandle(certHandle);
1278
+ * console.log(`Issued by: ${issuer}`);
1279
+ * ```
1280
+ */
1281
+ async getCertificateIssuerFromHandle(certHandle) {
1282
+ if (!this.native?.pdf_certificate_get_issuer) {
1283
+ throw new SignatureException('Native signing not available: pdf_certificate_get_issuer not found');
1284
+ }
1285
+ if (!certHandle) {
1286
+ throw new SignatureException('Invalid certificate handle: handle is null');
1287
+ }
1288
+ const errorCode = Buffer.alloc(4);
1289
+ const resultPtr = this.native.pdf_certificate_get_issuer(certHandle, errorCode);
1290
+ const code = errorCode.readInt32LE(0);
1291
+ if (code !== 0 || !resultPtr) {
1292
+ throw mapFfiErrorCode(code, 'Failed to get certificate issuer');
1293
+ }
1294
+ const issuer = typeof resultPtr === 'string' ? resultPtr : resultPtr.toString();
1295
+ return issuer;
1296
+ }
1297
+ /**
1298
+ * Get the size in bytes of a certificate.
1299
+ *
1300
+ * Calls the native `pdf_certificate_get_size` FFI function to get the
1301
+ * size of the DER-encoded certificate data.
1302
+ *
1303
+ * @param certHandle - An opaque certificate handle obtained from getCertificate or loadCertificateFromDerBytes
1304
+ * @returns The certificate size in bytes
1305
+ * @throws SignatureException if the size cannot be retrieved
1306
+ *
1307
+ * @example
1308
+ * ```typescript
1309
+ * const certHandle = await sigManager.loadCertificateFromDerBytes(certDer);
1310
+ * const size = await sigManager.getCertificateSize(certHandle);
1311
+ * console.log(`Certificate size: ${size} bytes`);
1312
+ * ```
1313
+ */
1314
+ async getCertificateSize(certHandle) {
1315
+ if (!this.native?.pdf_certificate_get_size) {
1316
+ throw new SignatureException('Native signing not available: pdf_certificate_get_size not found');
1317
+ }
1318
+ if (!certHandle) {
1319
+ throw new SignatureException('Invalid certificate handle: handle is null');
1320
+ }
1321
+ const errorCode = Buffer.alloc(4);
1322
+ const size = this.native.pdf_certificate_get_size(certHandle, errorCode);
1323
+ const code = errorCode.readInt32LE(0);
1324
+ if (code !== 0) {
1325
+ throw mapFfiErrorCode(code, 'Failed to get certificate size');
1326
+ }
1327
+ return typeof size === 'number' ? size : Number(size);
1328
+ }
1329
+ /**
1330
+ * Free a certificate handle when it is no longer needed.
1331
+ *
1332
+ * Calls the native `pdf_certificate_free` FFI function to release
1333
+ * memory associated with the certificate handle.
1334
+ *
1335
+ * @param certHandle - The certificate handle to free
1336
+ *
1337
+ * @example
1338
+ * ```typescript
1339
+ * const certHandle = await sigManager.loadCertificateFromDerBytes(certDer);
1340
+ * const cn = await sigManager.getCertificateCn(certHandle);
1341
+ * sigManager.freeCertificate(certHandle);
1342
+ * ```
1343
+ */
1344
+ freeCertificate(certHandle) {
1345
+ if (certHandle && this.native?.pdf_certificate_free) {
1346
+ this.native.pdf_certificate_free(certHandle);
1347
+ }
1348
+ }
1349
+ /**
1350
+ * Add an RFC 3161 timestamp to an existing signature via a Time Stamp Authority.
1351
+ *
1352
+ * Calls the native `pdf_add_timestamp` FFI function.
1353
+ *
1354
+ * @param pdfData - Buffer containing the signed PDF document bytes
1355
+ * @param signatureIndex - Index of the signature to timestamp (0-based)
1356
+ * @param tsaUrl - URL of the Time Stamp Authority server
1357
+ * @returns Buffer containing the timestamped PDF bytes
1358
+ * @throws SignatureException if timestamping fails
1359
+ */
1360
+ async addTimestamp(pdfData, signatureIndex, tsaUrl) {
1361
+ if (!this.native?.pdf_add_timestamp) {
1362
+ throw new SignatureException('Native timestamping not available: pdf_add_timestamp not found');
1363
+ }
1364
+ if (!pdfData || pdfData.length === 0) {
1365
+ throw new SignatureException('Invalid pdfData: buffer is empty or null');
1366
+ }
1367
+ if (!tsaUrl || tsaUrl.length === 0) {
1368
+ throw new SignatureException('Invalid tsaUrl: URL is empty or null');
1369
+ }
1370
+ const errorCode = Buffer.alloc(4);
1371
+ const outDataPtr = Buffer.alloc(8);
1372
+ const outLen = Buffer.alloc(8);
1373
+ const success = this.native.pdf_add_timestamp(pdfData, pdfData.length, signatureIndex, tsaUrl, outDataPtr, outLen, errorCode);
1374
+ const code = errorCode.readInt32LE(0);
1375
+ if (!success || code !== 0) {
1376
+ throw mapFfiErrorCode(code, 'Failed to add timestamp to PDF signature');
1377
+ }
1378
+ const resultLen = Number(outLen.readBigUInt64LE(0));
1379
+ const resultData = this.native.pdf_read_signed_bytes(outDataPtr, resultLen);
1380
+ if (this.native.pdf_signed_bytes_free) {
1381
+ this.native.pdf_signed_bytes_free(outDataPtr, resultLen);
1382
+ }
1383
+ this.emit('timestamp-added', {
1384
+ signatureIndex,
1385
+ tsaUrl,
1386
+ });
1387
+ return Buffer.from(resultData);
1388
+ }
1389
+ /**
1390
+ * Sign PDF data with a visible signature appearance on a specific page.
1391
+ *
1392
+ * @param pdfData - Buffer containing PDF bytes to sign
1393
+ * @param credentials - Pre-loaded signing credentials
1394
+ * @param pageNum - Page number for appearance (0-based)
1395
+ * @param x - X coordinate of appearance box
1396
+ * @param y - Y coordinate of appearance box
1397
+ * @param width - Width of appearance box
1398
+ * @param height - Height of appearance box
1399
+ * @param options - Optional signing parameters
1400
+ * @returns Buffer containing signed PDF bytes
1401
+ * @throws SignatureException if signing fails
1402
+ */
1403
+ async signWithAppearance(pdfData, credentials, pageNum, x, y, width, height, options) {
1404
+ if (!this.native?.pdf_document_sign_with_appearance) {
1405
+ throw new SignatureException('Native signing not available: pdf_document_sign_with_appearance not found');
1406
+ }
1407
+ if (!credentials._handle) {
1408
+ throw new SignatureException('Invalid credentials: handle is null');
1409
+ }
1410
+ const errorCode = Buffer.alloc(4);
1411
+ const outDataPtr = Buffer.alloc(8);
1412
+ const outLen = Buffer.alloc(8);
1413
+ const algorithm = options?.algorithm ?? FfiDigestAlgorithm.SHA256;
1414
+ const success = this.native.pdf_document_sign_with_appearance(pdfData, pdfData.length, credentials._handle, pageNum, x, y, width, height, options?.reason ?? null, options?.location ?? null, options?.contact ?? null, algorithm, outDataPtr, outLen, errorCode);
1415
+ const code = errorCode.readInt32LE(0);
1416
+ if (!success || code !== 0) {
1417
+ throw mapFfiErrorCode(code, 'Failed to sign PDF with appearance');
1418
+ }
1419
+ const resultLen = Number(outLen.readBigUInt64LE(0));
1420
+ const resultData = this.native.pdf_read_signed_bytes(outDataPtr, resultLen);
1421
+ if (this.native.pdf_signed_bytes_free) {
1422
+ this.native.pdf_signed_bytes_free(outDataPtr, resultLen);
1423
+ }
1424
+ this.clearCachePattern('signatures:');
1425
+ this.emit('signed-with-appearance', {
1426
+ pageNum,
1427
+ x,
1428
+ y,
1429
+ width,
1430
+ height,
1431
+ reason: options?.reason,
1432
+ location: options?.location,
1433
+ algorithm,
1434
+ });
1435
+ return Buffer.from(resultData);
1436
+ }
1437
+ // ===========================================================================
1438
+ // Cache
1439
+ // ===========================================================================
1440
+ clearCache() {
1441
+ this.resultCache.clear();
1442
+ this.emit('cacheCleared');
1443
+ }
1444
+ getCacheStats() {
1445
+ return {
1446
+ cacheSize: this.resultCache.size,
1447
+ maxCacheSize: this.maxCacheSize,
1448
+ entries: Array.from(this.resultCache.keys()),
1449
+ };
1450
+ }
1451
+ destroy() {
1452
+ this.loadedCertificates.clear();
1453
+ this.createdFields.clear();
1454
+ this.resultCache.clear();
1455
+ this.removeAllListeners();
1456
+ }
1457
+ /**
1458
+ * Sign a PDF from raw bytes using PEM credentials.
1459
+ *
1460
+ * Calls the native `signPdfBytes` FFI function (two-pass ByteRange writer).
1461
+ * Credentials are loaded and freed within this call.
1462
+ *
1463
+ * @param pdfData - Buffer containing the PDF document bytes
1464
+ * @param certPem - PEM-encoded certificate string
1465
+ * @param keyPem - PEM-encoded private key string
1466
+ * @param reason - Optional signature reason
1467
+ * @param location - Optional signature location
1468
+ * @returns Buffer containing the signed PDF
1469
+ */
1470
+ async signPdfData(pdfData, certPem, keyPem, reason, location) {
1471
+ if (!this.native?.certificateLoadFromPem) {
1472
+ throw new SignatureException('Native signing not available: certificateLoadFromPem not found');
1473
+ }
1474
+ if (!this.native?.signPdfBytes) {
1475
+ throw new SignatureException('Native signing not available: signPdfBytes not found');
1476
+ }
1477
+ const certHandle = this.native.certificateLoadFromPem(certPem, keyPem);
1478
+ if (!certHandle) {
1479
+ throw new SignatureException('Failed to load PEM certificate');
1480
+ }
1481
+ try {
1482
+ const result = this.native.signPdfBytes(pdfData, certHandle, reason ?? null, location ?? null);
1483
+ if (!result)
1484
+ throw new SignatureException('signPdfBytes returned null');
1485
+ return Buffer.from(result);
1486
+ }
1487
+ finally {
1488
+ if (this.native?.pdf_certificate_free) {
1489
+ this.native.pdf_certificate_free(certHandle);
1490
+ }
1491
+ }
1492
+ }
1493
+ // Private helpers
1494
+ setCached(key, value) {
1495
+ this.resultCache.set(key, value);
1496
+ if (this.resultCache.size > this.maxCacheSize) {
1497
+ const firstKey = this.resultCache.keys().next().value;
1498
+ if (firstKey !== undefined)
1499
+ this.resultCache.delete(firstKey);
1500
+ }
1501
+ }
1502
+ clearCachePattern(prefix) {
1503
+ const keysToDelete = Array.from(this.resultCache.keys()).filter((key) => key.startsWith(prefix));
1504
+ keysToDelete.forEach((key) => {
1505
+ this.resultCache.delete(key);
1506
+ });
1507
+ }
1508
+ }
1509
+ export default SignatureManager;