@certysign/sdk 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@certysign/sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Official Node.js SDK for CertySign — hash-based digital signing, X.509 certificates, and PKI services. Documents never leave your system.",
5
5
  "main": "src/index.js",
6
6
  "types": "src/index.d.ts",
@@ -34,6 +34,7 @@
34
34
  "dependencies": {
35
35
  "axios": "^1.6.0",
36
36
  "form-data": "^4.0.0",
37
+ "node-forge": "^1.3.3",
37
38
  "pdf-lib": "^1.17.1"
38
39
  },
39
40
  "devDependencies": {
@@ -5,7 +5,7 @@
5
5
  * Documents NEVER leave the subscriber's infrastructure.
6
6
  *
7
7
  * Supports:
8
- * - PDF (PAdES-style with pdf-lib) — single or multi-recipient visual stamps
8
+ * - PDF (PAdES-style with cryptographic PKCS#7 embedding) — single or multi-recipient visual stamps
9
9
  * - XML (XMLDSig enveloped signature)
10
10
  * - JSON (JWS-like detached signature)
11
11
  *
@@ -29,23 +29,26 @@ const STAMP_PADDING_X = 8;
29
29
  const STAMP_PADDING_Y = 8;
30
30
  const STAMP_WIDTH = 260;
31
31
  const STAMP_MARGIN = 6; // gap between multiple stamps
32
+ // Placeholder size for PKCS#7 signature content (8192 bytes = 16384 hex chars)
33
+ const SIG_PLACEHOLDER_LENGTH = 16384;
32
34
 
33
35
  class SignatureEmbedder {
34
36
  /**
35
- * Embed one or more digital signatures into a PDF document.
37
+ * Embed one or more digital signatures into a PDF document with
38
+ * proper PKCS#7/CMS cryptographic embedding (PAdES compliant).
36
39
  *
37
- * Supports two call patterns:
38
- * 1. Single signature — pass options with a single `signature` field
39
- * 2. Multiple signer — pass options with a `signatures[]` array
40
+ * Creates a PDF /Sig dictionary with /ByteRange and /Contents
41
+ * that Adobe Reader, Foxit, and other PDF readers recognise as
42
+ * a valid digital signature.
40
43
  *
41
- * Each signature gets its own visual stamp matching the CertySign platform:
42
- * Digitally signed by: <email>
43
- * Date: <ISO 8601>
44
- * Certificate: <serial>
45
- * Standard: PAdES Baseline B-B
44
+ * **Recommended:** Pass a `signCallback` function — the embedder will:
45
+ * 1. Prepare the PDF with visual stamps and an empty /Sig placeholder
46
+ * 2. Compute the SHA-256 hash of the ByteRange regions
47
+ * 3. Call your `signCallback(hash)` to get the HSM signature
48
+ * 4. Build a valid PKCS#7 and patch it into /Contents
46
49
  *
47
- * Multiple stamps are stacked from the bottom of the page upward,
48
- * or positioned explicitly via `signaturePosition`.
50
+ * This produces a cryptographically valid PAdES signature that
51
+ * Adobe Reader, Foxit, and other PDF readers can verify.
49
52
  *
50
53
  * @param {Buffer} pdfBuffer - Original unsigned PDF
51
54
  * @param {EmbedPdfOptions} options
@@ -54,13 +57,16 @@ class SignatureEmbedder {
54
57
  async embedInPdf(pdfBuffer, options) {
55
58
  if (!pdfBuffer) throw new Error('embedInPdf: pdfBuffer is required');
56
59
 
57
- let PDFDocument, PDFName, PDFHexString, PDFDict, rgb, StandardFonts;
60
+ let PDFDocument, PDFName, PDFHexString, PDFString, PDFDict, PDFArray, PDFNumber, rgb, StandardFonts;
58
61
  try {
59
62
  const pdfLib = require('pdf-lib');
60
63
  PDFDocument = pdfLib.PDFDocument;
61
64
  PDFName = pdfLib.PDFName;
62
65
  PDFHexString = pdfLib.PDFHexString;
66
+ PDFString = pdfLib.PDFString;
63
67
  PDFDict = pdfLib.PDFDict;
68
+ PDFArray = pdfLib.PDFArray;
69
+ PDFNumber = pdfLib.PDFNumber;
64
70
  rgb = pdfLib.rgb;
65
71
  StandardFonts = pdfLib.StandardFonts;
66
72
  } catch {
@@ -69,134 +75,223 @@ class SignatureEmbedder {
69
75
  );
70
76
  }
71
77
 
78
+ let forge;
79
+ try {
80
+ forge = require('node-forge');
81
+ } catch {
82
+ throw new Error(
83
+ 'node-forge is required for cryptographic PDF signing. Install it: npm install node-forge'
84
+ );
85
+ }
86
+
72
87
  const pdfDoc = await PDFDocument.load(pdfBuffer, { ignoreEncryption: true });
73
88
  const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
74
89
  const pages = pdfDoc.getPages();
75
90
 
76
- // ── Normalise to an array of signature entries ──
77
- const sigEntries = options.signatures
78
- ? options.signatures
79
- : [options];
91
+ // ── Normalise to a single signature entry ──
92
+ // For PAdES we process one signature at a time (each needs its own ByteRange)
93
+ const entry = options.signatures ? options.signatures[0] : options;
94
+ if (!entry) throw new Error('embedInPdf: at least one signature entry is required');
95
+
96
+ const signerEmail = entry.signerEmail || entry.recipientEmail || entry.signerName || 'CertySign';
97
+ const certSerial = entry.certSerialNumber || '';
98
+ const signDate = entry.timestamp ? new Date(entry.timestamp) :
99
+ entry.signedAt ? new Date(entry.signedAt) : new Date();
100
+ const reason = entry.reason || 'Digital signature';
101
+ const location = entry.location || '';
102
+ const standard = entry.standard || 'PAdES Baseline B-B';
103
+ const certPem = entry.certificate || null;
104
+ const chainPem = entry.chain || null;
105
+ const signCallback = entry.signCallback || options.signCallback || null;
106
+ const precomputedSig = entry.signature || null;
107
+
108
+ if (!signCallback && !precomputedSig) {
109
+ throw new Error('embedInPdf: either signCallback or signature is required');
110
+ }
111
+
112
+ // ── Determine target page ──
113
+ const pos = entry.signaturePosition || {};
114
+ const pageIdx = pos.page
115
+ ? Math.min(pos.page - 1, pages.length - 1)
116
+ : pages.length - 1;
117
+ const sigPage = pages[pageIdx];
118
+
119
+ // 4 text lines = height
120
+ const stampHeight = (4 * STAMP_LINE_HEIGHT) + (2 * STAMP_PADDING_Y);
121
+ const stampWidth = pos.width || STAMP_WIDTH;
122
+ const x = pos.x != null ? pos.x : 20;
123
+ const y = pos.y != null ? pos.y : 20;
124
+
125
+ // ── Draw stamp box ──
126
+ sigPage.drawRectangle({
127
+ x, y,
128
+ width: stampWidth,
129
+ height: stampHeight,
130
+ borderColor: rgb(0.4, 0.4, 0.4),
131
+ borderWidth: 0.75,
132
+ color: rgb(0.97, 0.97, 0.97),
133
+ opacity: 0.95
134
+ });
80
135
 
81
- if (sigEntries.length === 0) {
82
- throw new Error('embedInPdf: at least one signature is required');
136
+ // ── Draw text lines matching CertySign platform format ──
137
+ const textLines = [
138
+ `Digitally signed by: ${signerEmail}`,
139
+ `Date: ${signDate.toISOString()}`,
140
+ `Certificate: ${certSerial}`,
141
+ `Standard: ${standard}`
142
+ ];
143
+
144
+ let textY = y + stampHeight - STAMP_PADDING_Y - STAMP_FONT_SIZE;
145
+ for (const line of textLines) {
146
+ sigPage.drawText(line, {
147
+ x: x + STAMP_PADDING_X,
148
+ y: textY,
149
+ size: STAMP_FONT_SIZE,
150
+ font,
151
+ color: rgb(0.4, 0.4, 0.4),
152
+ maxWidth: stampWidth - (2 * STAMP_PADDING_X)
153
+ });
154
+ textY -= STAMP_LINE_HEIGHT;
83
155
  }
84
156
 
85
- // Track how many stamps we've drawn per page for auto-stacking
86
- const pageStampCounts = {};
157
+ // ── Create the /Sig dictionary with empty placeholder ──
158
+ const sigDict = pdfDoc.context.obj({
159
+ Type: 'Sig',
160
+ Filter: 'Adobe.PPKLite',
161
+ SubFilter: 'adbe.pkcs7.detached',
162
+ // Large placeholder numbers ensure enough bytes for patching
163
+ ByteRange: [0, 9999999999, 9999999999, 9999999999],
164
+ Contents: PDFHexString.of('0'.repeat(SIG_PLACEHOLDER_LENGTH)),
165
+ Reason: PDFString.of(reason),
166
+ M: PDFString.of(_pdfDate(signDate)),
167
+ Name: PDFString.of(signerEmail),
168
+ Location: location ? PDFString.of(location) : undefined,
169
+ ContactInfo: PDFString.of(signerEmail)
170
+ });
87
171
 
88
- for (let idx = 0; idx < sigEntries.length; idx++) {
89
- const entry = sigEntries[idx];
90
- const sig = entry.signature;
91
- if (!sig) throw new Error(`embedInPdf: signature is required (entry ${idx})`);
92
-
93
- const signerEmail = entry.signerEmail || entry.recipientEmail || entry.signerName || 'CertySign';
94
- const certSerial = entry.certSerialNumber || '';
95
- const signDate = entry.timestamp ? new Date(entry.timestamp) :
96
- entry.signedAt ? new Date(entry.signedAt) : new Date();
97
- const reason = entry.reason || 'Digital signature';
98
- const location = entry.location || '';
99
- const standard = entry.standard || 'PAdES Baseline B-B';
100
-
101
- // ── Determine target page ──
102
- const pos = entry.signaturePosition || {};
103
- const pageIdx = pos.page
104
- ? Math.min(pos.page - 1, pages.length - 1)
105
- : pages.length - 1;
106
- const sigPage = pages[pageIdx];
107
-
108
- // ── Auto-stacking: each stamp stacks above the previous one ──
109
- const stampKey = pageIdx;
110
- if (!(stampKey in pageStampCounts)) pageStampCounts[stampKey] = 0;
111
- const stampIndex = pageStampCounts[stampKey];
112
- pageStampCounts[stampKey]++;
113
-
114
- // 4 text lines = height
115
- const stampHeight = (4 * STAMP_LINE_HEIGHT) + (2 * STAMP_PADDING_Y);
116
- const stampWidth = pos.width || STAMP_WIDTH;
117
-
118
- // Position: explicit position or auto-stack from bottom-left
119
- const x = pos.x != null ? pos.x : 20;
120
- const baseY = pos.y != null ? pos.y : 20;
121
- const y = baseY + stampIndex * (stampHeight + STAMP_MARGIN);
122
-
123
- // ── Draw stamp box ──
124
- sigPage.drawRectangle({
125
- x, y,
126
- width: stampWidth,
127
- height: stampHeight,
128
- borderColor: rgb(0.4, 0.4, 0.4),
129
- borderWidth: 0.75,
130
- color: rgb(0.97, 0.97, 0.97),
131
- opacity: 0.95
172
+ const sigDictRef = pdfDoc.context.register(sigDict);
173
+
174
+ // ── Create widget annotation for the visual stamp ──
175
+ const widgetDict = pdfDoc.context.obj({
176
+ Type: 'Annot',
177
+ Subtype: 'Widget',
178
+ FT: 'Sig',
179
+ Rect: [x, y, x + stampWidth, y + stampHeight],
180
+ V: sigDictRef,
181
+ T: PDFString.of('CertySign-Sig-0'),
182
+ F: 4, // Print flag
183
+ P: pages[pageIdx].ref,
184
+ });
185
+
186
+ const widgetRef = pdfDoc.context.register(widgetDict);
187
+
188
+ // Add widget to page Annots array
189
+ const pageDict = pages[pageIdx].node;
190
+ let annots = pageDict.lookup(PDFName.of('Annots'));
191
+ if (!annots || !(annots instanceof PDFArray)) {
192
+ annots = pdfDoc.context.obj([]);
193
+ pageDict.set(PDFName.of('Annots'), annots);
194
+ }
195
+ annots.push(widgetRef);
196
+
197
+ // Add to AcroForm
198
+ let acroForm = pdfDoc.catalog.lookup(PDFName.of('AcroForm'));
199
+ if (!acroForm || !(acroForm instanceof PDFDict)) {
200
+ acroForm = pdfDoc.context.obj({
201
+ Fields: [],
202
+ SigFlags: 3 // SignaturesExist | AppendOnly
132
203
  });
204
+ pdfDoc.catalog.set(PDFName.of('AcroForm'), acroForm);
205
+ } else {
206
+ acroForm.set(PDFName.of('SigFlags'), PDFNumber.of(3));
207
+ }
133
208
 
134
- // ── Draw text lines matching CertySign platform format ──
135
- const textLines = [
136
- `Digitally signed by: ${signerEmail}`,
137
- `Date: ${signDate.toISOString()}`,
138
- `Certificate: ${certSerial}`,
139
- `Standard: ${standard}`
140
- ];
141
-
142
- let textY = y + stampHeight - STAMP_PADDING_Y - STAMP_FONT_SIZE;
143
- for (const line of textLines) {
144
- sigPage.drawText(line, {
145
- x: x + STAMP_PADDING_X,
146
- y: textY,
147
- size: STAMP_FONT_SIZE,
148
- font,
149
- color: rgb(0.4, 0.4, 0.4),
150
- maxWidth: stampWidth - (2 * STAMP_PADDING_X)
151
- });
152
- textY -= STAMP_LINE_HEIGHT;
153
- }
209
+ let fields = acroForm.lookup(PDFName.of('Fields'));
210
+ if (!fields || !(fields instanceof PDFArray)) {
211
+ fields = pdfDoc.context.obj([]);
212
+ acroForm.set(PDFName.of('Fields'), fields);
154
213
  }
214
+ fields.push(widgetRef);
155
215
 
156
- // ── Embed signature metadata as document properties ──
157
- // Store the last (or primary) signature's CMS data for programmatic verification
158
- const primary = sigEntries[0];
159
- const sigMetadata = {
160
- 'CertySign-SignatureCount': String(sigEntries.length),
161
- 'CertySign-Algorithm': primary.algorithm || 'SHA256withRSA',
162
- 'CertySign-CertSerial': primary.certSerialNumber || '',
163
- 'CertySign-Timestamp': (primary.timestamp ? new Date(primary.timestamp) : new Date()).toISOString(),
164
- 'CertySign-Signer': primary.signerEmail || primary.recipientEmail || primary.signerName || 'CertySign',
165
- 'CertySign-DocumentHash': primary.documentHash || '',
166
- 'CertySign-HashAlgorithm': primary.hashAlgorithm || 'sha256',
167
- 'CertySign-Standard': primary.standard || 'PAdES Baseline B-B'
168
- };
216
+ pdfDoc.setProducer('CertySign Trust Services');
217
+ pdfDoc.setModificationDate(new Date());
169
218
 
170
- // Store each signature in metadata
171
- for (let i = 0; i < sigEntries.length; i++) {
172
- const entry = sigEntries[i];
173
- sigMetadata[`CertySign-Signature-${i}`] = entry.signature;
174
- if (entry.certSerialNumber) {
175
- sigMetadata[`CertySign-CertSerial-${i}`] = entry.certSerialNumber;
176
- }
177
- const signer = entry.signerEmail || entry.recipientEmail || entry.signerName || '';
178
- if (signer) sigMetadata[`CertySign-Signer-${i}`] = signer;
219
+ // ── Phase 1: Save PDF with empty signature placeholder ──
220
+ let pdfBytes = Buffer.from(await pdfDoc.save({ useObjectStreams: false }));
221
+
222
+ // ── Phase 2: Patch ByteRange and compute hash of signed regions ──
223
+ const pdfStr = pdfBytes.toString('latin1');
224
+ const placeholderHex = '0'.repeat(SIG_PLACEHOLDER_LENGTH);
225
+ const placeholderIdx = pdfStr.indexOf(placeholderHex);
226
+ if (placeholderIdx === -1) {
227
+ throw new Error('embedInPdf: could not find signature placeholder in saved PDF');
179
228
  }
180
229
 
181
- if (primary.certificate) {
182
- sigMetadata['CertySign-Certificate'] = primary.certificate.replace(/\n/g, '\\n');
230
+ const contentsStart = placeholderIdx - 1; // byte offset of '<'
231
+ const contentsEnd = placeholderIdx + SIG_PLACEHOLDER_LENGTH + 1; // byte after '>'
232
+ const totalLen = pdfBytes.length;
233
+
234
+ const br0 = 0;
235
+ const br1 = contentsStart;
236
+ const br2 = contentsEnd;
237
+ const br3 = totalLen - contentsEnd;
238
+
239
+ // Patch ByteRange values in-place
240
+ const searchStart = Math.max(0, placeholderIdx - 500);
241
+ const searchRegion = pdfStr.substring(searchStart, placeholderIdx);
242
+ const brRelIdx = searchRegion.lastIndexOf('/ByteRange');
243
+ if (brRelIdx !== -1) {
244
+ const absIdx = searchStart + brRelIdx;
245
+ const closeBracket = pdfStr.indexOf(']', absIdx);
246
+ if (closeBracket !== -1) {
247
+ const oldBrLen = closeBracket + 1 - absIdx;
248
+ const newBrValue = `/ByteRange [${br0} ${br1} ${br2} ${br3}]`;
249
+ const newBr = newBrValue.padEnd(oldBrLen, ' ');
250
+ pdfBytes.write(newBr, absIdx, oldBrLen, 'latin1');
251
+ }
183
252
  }
184
- if (primary.chain) {
185
- sigMetadata['CertySign-Chain'] = primary.chain.replace(/\n/g, '\\n');
253
+
254
+ // ── Phase 3: Compute hash of the ByteRange regions (everything except /Contents hex) ──
255
+ const byteRangeHash = crypto.createHash('sha256');
256
+ byteRangeHash.update(pdfBytes.subarray(br0, br0 + br1)); // before <Contents>
257
+ byteRangeHash.update(pdfBytes.subarray(br2, br2 + br3)); // after <Contents>
258
+ const hashHex = byteRangeHash.digest('hex');
259
+
260
+ // ── Phase 4: Get the signature ──
261
+ let rawSigBase64;
262
+ let sigCertPem = certPem;
263
+ let sigChainPem = chainPem;
264
+
265
+ if (signCallback) {
266
+ // Call the HSM to sign the ByteRange hash — produces a valid PAdES signature
267
+ const signResult = await signCallback(hashHex);
268
+ rawSigBase64 = signResult.data?.signature || signResult.signature;
269
+ sigCertPem = sigCertPem || signResult.data?.certificate || signResult.certificate;
270
+ sigChainPem = sigChainPem || signResult.data?.chain || signResult.chain;
271
+ } else {
272
+ // Legacy: use pre-computed signature (won't validate against ByteRange)
273
+ rawSigBase64 = precomputedSig;
186
274
  }
187
275
 
188
- const infoDict = pdfDoc.context.lookup(pdfDoc.context.trailerInfo.Info);
189
- if (infoDict instanceof PDFDict) {
190
- for (const [key, value] of Object.entries(sigMetadata)) {
191
- infoDict.set(PDFName.of(key), PDFHexString.fromText(value));
192
- }
276
+ // ── Phase 5: Build PKCS#7 and patch into /Contents ──
277
+ const p7 = _buildPkcs7(forge, rawSigBase64, sigCertPem, sigChainPem, signDate, {
278
+ signerEmail, reason, location, certSerial
279
+ });
280
+ const p7Der = forge.asn1.toDer(p7).getBytes();
281
+ const p7Hex = Buffer.from(p7Der, 'binary').toString('hex');
282
+
283
+ if (p7Hex.length > SIG_PLACEHOLDER_LENGTH) {
284
+ throw new Error(
285
+ `PKCS#7 signature too large (${p7Hex.length} hex chars > ${SIG_PLACEHOLDER_LENGTH} placeholder). ` +
286
+ 'Increase SIG_PLACEHOLDER_LENGTH.'
287
+ );
193
288
  }
194
289
 
195
- pdfDoc.setProducer('CertySign Trust Services');
196
- pdfDoc.setModificationDate(new Date());
290
+ // Write PKCS#7 hex into the /Contents placeholder
291
+ const paddedHex = p7Hex.padEnd(SIG_PLACEHOLDER_LENGTH, '0');
292
+ pdfBytes.write(paddedHex, placeholderIdx, SIG_PLACEHOLDER_LENGTH, 'latin1');
197
293
 
198
- const signedBytes = await pdfDoc.save();
199
- return Buffer.from(signedBytes);
294
+ return pdfBytes;
200
295
  }
201
296
 
202
297
  /**
@@ -356,6 +451,208 @@ function _xmlEscape(str) {
356
451
  .replace(/'/g, '&apos;');
357
452
  }
358
453
 
454
+ /**
455
+ * Build a PKCS#7 SignedData ASN.1 structure wrapping the raw RSA signature
456
+ * and the signer certificate (+ optional chain).
457
+ *
458
+ * The HSM already produced the raw RSA signature over the document hash.
459
+ * We wrap it into a CMS SignedData container so PDF readers recognise it.
460
+ */
461
+ function _buildPkcs7(forge, rawSigBase64, certPem, chainPem, signDate, meta) {
462
+ const rawSigBytes = forge.util.decode64(rawSigBase64);
463
+
464
+ // Parse the signing certificate
465
+ const certs = [];
466
+ if (certPem) {
467
+ certs.push(forge.pki.certificateFromPem(certPem));
468
+ }
469
+ if (chainPem) {
470
+ // Chain may contain multiple PEM blocks
471
+ const chainBlocks = chainPem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) || [];
472
+ for (const block of chainBlocks) {
473
+ try { certs.push(forge.pki.certificateFromPem(block)); } catch { /* skip invalid */ }
474
+ }
475
+ }
476
+
477
+ const signerCert = certs[0] || null;
478
+
479
+ // ── Build ASN.1 SignedData manually ──
480
+ // OID: 1.2.840.113549.1.7.2 (signedData)
481
+ const contentType = forge.asn1.oidToDer('1.2.840.113549.1.7.2').getBytes();
482
+ // OID: 1.2.840.113549.1.7.1 (data)
483
+ const dataType = forge.asn1.oidToDer('1.2.840.113549.1.7.1').getBytes();
484
+ // OID: 2.16.840.1.101.3.4.2.1 (sha-256)
485
+ const sha256Oid = forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes();
486
+
487
+ // Create certificate SET
488
+ const certSet = [];
489
+ for (const cert of certs) {
490
+ certSet.push(forge.asn1.fromDer(forge.asn1.toDer(forge.pki.certificateToAsn1(cert))));
491
+ }
492
+
493
+ // Build SignerInfo
494
+ const signerInfoSets = [];
495
+ if (signerCert) {
496
+ const issuerSeq = forge.asn1.fromDer(
497
+ forge.asn1.toDer(forge.pki.distinguishedNameToAsn1(signerCert.issuer))
498
+ );
499
+ const serialInt = forge.asn1.create(
500
+ forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
501
+ forge.util.hexToBytes(signerCert.serialNumber)
502
+ );
503
+
504
+ // Authenticated attributes
505
+ const signingTime = forge.asn1.create(
506
+ forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
507
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
508
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
509
+ forge.asn1.oidToDer('1.2.840.113549.1.9.5').getBytes()), // signingTime OID
510
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
511
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.UTCTIME, false,
512
+ _asn1UtcTime(signDate))
513
+ ])
514
+ ])
515
+ ]
516
+ );
517
+
518
+ const signerInfo = forge.asn1.create(
519
+ forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
520
+ // version
521
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
522
+ forge.util.hexToBytes('01')),
523
+ // issuerAndSerialNumber
524
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
525
+ issuerSeq,
526
+ serialInt
527
+ ]),
528
+ // digestAlgorithm
529
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
530
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, sha256Oid),
531
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, '')
532
+ ]),
533
+ // signatureAlgorithm (rsaEncryption)
534
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
535
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
536
+ forge.asn1.oidToDer('1.2.840.113549.1.1.1').getBytes()),
537
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, '')
538
+ ]),
539
+ // signature
540
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false,
541
+ rawSigBytes)
542
+ ]
543
+ );
544
+ signerInfoSets.push(signerInfo);
545
+ }
546
+
547
+ // SignedData SEQUENCE
548
+ const signedData = forge.asn1.create(
549
+ forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
550
+ // version
551
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
552
+ forge.util.hexToBytes('01')),
553
+ // digestAlgorithms SET
554
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
555
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
556
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, sha256Oid),
557
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, '')
558
+ ])
559
+ ]),
560
+ // contentInfo (empty data — detached signature)
561
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
562
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, dataType)
563
+ ]),
564
+ // certificates [0] IMPLICIT
565
+ ...(certSet.length > 0 ? [
566
+ forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, certSet)
567
+ ] : []),
568
+ // signerInfos SET
569
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, signerInfoSets)
570
+ ]
571
+ );
572
+
573
+ // Wrap in ContentInfo
574
+ const contentInfo = forge.asn1.create(
575
+ forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
576
+ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, contentType),
577
+ forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [signedData])
578
+ ]
579
+ );
580
+
581
+ return contentInfo;
582
+ }
583
+
584
+ /**
585
+ * Convert a Date to ASN.1 UTCTime format (YYMMDDHHmmssZ)
586
+ */
587
+ function _asn1UtcTime(date) {
588
+ const pad = n => String(n).padStart(2, '0');
589
+ const y = date.getUTCFullYear() % 100;
590
+ return `${pad(y)}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}` +
591
+ `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;
592
+ }
593
+
594
+ /**
595
+ * Convert a Date to PDF date format (D:YYYYMMDDHHmmss+00'00')
596
+ */
597
+ function _pdfDate(date) {
598
+ const pad = n => String(n).padStart(2, '0');
599
+ return `D:${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}` +
600
+ `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}+00'00'`;
601
+ }
602
+
603
+ /**
604
+ * Patch the placeholder /Contents hex string in the saved PDF with actual PKCS#7 DER bytes.
605
+ * Searches for the placeholder pattern and replaces it with the real signature.
606
+ */
607
+ function _patchSignatureContents(pdfBytes, p7Hex) {
608
+ // The placeholder is a hex string of null bytes (00) of length SIG_PLACEHOLDER_LENGTH
609
+ const placeholderHex = '0'.repeat(SIG_PLACEHOLDER_LENGTH);
610
+ const pdfStr = pdfBytes.toString('latin1');
611
+
612
+ // Find the placeholder in the PDF — it appears inside angle brackets: <0000...0000>
613
+ const placeholderIdx = pdfStr.indexOf(placeholderHex);
614
+ if (placeholderIdx === -1) {
615
+ return pdfBytes;
616
+ }
617
+
618
+ // Pad the actual signature hex to fill the full placeholder length
619
+ const paddedHex = p7Hex.padEnd(SIG_PLACEHOLDER_LENGTH, '0');
620
+
621
+ // Replace in a mutable buffer
622
+ const result = Buffer.from(pdfBytes);
623
+ result.write(paddedHex, placeholderIdx, SIG_PLACEHOLDER_LENGTH, 'latin1');
624
+
625
+ // Calculate actual ByteRange values
626
+ // '<' is at placeholderIdx - 1, '>' is at placeholderIdx + SIG_PLACEHOLDER_LENGTH
627
+ const contentsStart = placeholderIdx - 1; // byte offset of '<'
628
+ const contentsEnd = placeholderIdx + SIG_PLACEHOLDER_LENGTH + 1; // byte after '>'
629
+ const totalLen = result.length;
630
+
631
+ // ByteRange: [before_sig_start, before_sig_len, after_sig_start, after_sig_len]
632
+ const br0 = 0;
633
+ const br1 = contentsStart;
634
+ const br2 = contentsEnd;
635
+ const br3 = totalLen - contentsEnd;
636
+
637
+ // Find /ByteRange [...] near the signature and patch it
638
+ const searchStart = Math.max(0, placeholderIdx - 500);
639
+ const searchRegion = pdfStr.substring(searchStart, placeholderIdx);
640
+ const brRelIdx = searchRegion.lastIndexOf('/ByteRange');
641
+ if (brRelIdx !== -1) {
642
+ const absIdx = searchStart + brRelIdx;
643
+ const closeBracket = pdfStr.indexOf(']', absIdx);
644
+ if (closeBracket !== -1) {
645
+ const oldBrLen = closeBracket + 1 - absIdx;
646
+ const newBrValue = `/ByteRange [${br0} ${br1} ${br2} ${br3}]`;
647
+ // Pad with spaces to exactly match original length — prevents shifting bytes
648
+ const newBr = newBrValue.padEnd(oldBrLen, ' ');
649
+ result.write(newBr, absIdx, oldBrLen, 'latin1');
650
+ }
651
+ }
652
+
653
+ return result;
654
+ }
655
+
359
656
  /**
360
657
  * @typedef {Object} SignatureEntry
361
658
  * @property {string} signature - Base64 CMS/PKCS#7 from CertySign