pdf-oxide 0.3.24 → 0.3.29

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