all files / core/security/digital-signature/signature/ pdf-signature.js

7.06% Statements 18/255
0% Branches 0/223
11.11% Functions 2/18
7.11% Lines 18/253
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
define(["require", "exports", "../../../enumerator", "../../../pdf-document", "../../../pdf-primitives", "../../../utils", "./../pdf-certificate", "./signature-dictionary", "../x509/x509-certificate-parser", "./signature-privatekey", "./cryptographic-signer", "@syncfusion/ej2-file-utils"], function (require, exports, enumerator_1, pdf_document_1, pdf_primitives_1, utils_1, pdf_certificate_1, signature_dictionary_1, x509_certificate_parser_1, signature_privatekey_1, cryptographic_signer_1, ej2_file_utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var PdfSignature = (function () {
        function PdfSignature() {
            this._visible = true;
            this._isTimeStampOnly = false;
            this._externalChain = [];
            this._isLocked = false;
            this._signed = false;
            this._appendCertificates = false;
            this._digestAlgorithm = enumerator_1.DigestAlgorithm.sha256;
            this._cryptographicStandard = enumerator_1.CryptographicStandard.cms;
            this._documentPermissions = enumerator_1.PdfCertificationFlags.forbidChanges;
        }
        PdfSignature.create = function (arg1, arg2, arg3) {
            var signature = new PdfSignature();
            if (arg1 instanceof Uint8Array || typeof arg1 === 'string') {
                var data = arg1 instanceof Uint8Array ? arg1
                    : utils_1._decode(arg1);
                if (!data || data.length === 0) {
                    throw new Error('Certificate data is required.');
                }
                if (typeof arg2 !== 'string' || !arg2) {
                    throw new Error('Password is required to open the certificate.');
                }
                var certificate = new pdf_certificate_1._PdfCertificate(data, arg2);
                if (certificate) {
                    signature._certificate = certificate;
                    signature._certificateInfo = {
                        issuerName: certificate._issuerName,
                        serialNumber: certificate._serialNumber,
                        subjectName: certificate._subjectName,
                        validFrom: certificate._validFrom,
                        validTo: certificate._validTo,
                        version: certificate._version
                    };
                }
                signature._applySignatureOptions(arg3);
            }
            else {
                signature._externalSignatureCallback = arg1;
                if (arg2 && Array.isArray(arg2) && arg2.length > 0) {
                    for (var _i = 0, arg2_1 = arg2; _i < arg2_1.length; _i++) {
                        var data = arg2_1[_i];
                        var publicCertificate = data;
                        if (publicCertificate && publicCertificate.length > 0) {
                            signature._externalChain.push(new x509_certificate_parser_1._PdfX509CertificateParser()._readCertificate(publicCertificate));
                        }
                    }
                    signature._applySignatureOptions(arg3);
                }
                else {
                    signature._applySignatureOptions(arg2);
                }
            }
            return signature;
        };
        PdfSignature.prototype.getSignedDate = function () {
            return this._signedDate;
        };
        PdfSignature.prototype.getCertificateInformation = function () {
            return this._certificateInfo;
        };
        PdfSignature.prototype.getSignatureOptions = function () {
            var options = {
                cryptographicStandard: this._cryptographicStandard,
                digestAlgorithm: this._digestAlgorithm,
                contactInfo: this._contactInfo,
                reason: this._reason,
                locationInfo: this._locationInfo,
                certify: this._certify,
                documentPermissions: this._documentPermissions,
                signedName: this._signedName,
                isLocked: this._isLocked
            };
            return options;
        };
        PdfSignature.replaceEmptySignature = function (inputPdfData, signatureName, signedData, algorithm, publicCertificates, arg6, arg7) {
            if (!(inputPdfData instanceof Uint8Array) || inputPdfData.length === 0 &&
                !(signedData instanceof Uint8Array) || signedData.length === 0) {
                throw new Error('Invalid Uint8Array: Data is either not a Uint8Array or is empty.');
            }
            if (typeof signatureName !== 'string' && signatureName !== '') {
                throw new Error('Signature field name is required');
            }
            var _externalChain = [];
            var options;
            if (arg6 && typeof arg6 !== 'string') {
                options = arg6;
            }
            else {
                options = arg7;
            }
            if (publicCertificates && Array.isArray(publicCertificates)) {
                for (var _i = 0, publicCertificates_1 = publicCertificates; _i < publicCertificates_1.length; _i++) {
                    var data = publicCertificates_1[_i];
                    var publicCertificatesData = data;
                    if (publicCertificatesData && publicCertificatesData.length > 0) {
                        _externalChain.push(new x509_certificate_parser_1._PdfX509CertificateParser()._readCertificate(publicCertificatesData));
                    }
                }
            }
            if (!Array.isArray(_externalChain) || _externalChain.length === 0) {
                throw new Error('Invalid certificate chain: Expected a non-empty array of Certificate.');
            }
            var document;
            var encodeSignature;
            if (options) {
                document = new pdf_document_1.PdfDocument(inputPdfData, options.password);
                encodeSignature = typeof options.skipSignatureEncoding === 'undefined' ||
                    options.skipSignatureEncoding === null ||
                    options.skipSignatureEncoding === false ? true : false;
            }
            else {
                document = new pdf_document_1.PdfDocument(inputPdfData);
                encodeSignature = true;
            }
            try {
                var form = document.form;
                var field = void 0;
                for (var i = 0; i < form.count; i++) {
                    if (form.fieldAt(i).name === signatureName) {
                        field = form.fieldAt(i);
                        break;
                    }
                }
                if (!field) {
                    throw new Error('Signature field name not found.');
                }
                var signatureDict = field._dictionary;
                if (signatureDict && signatureDict.has('V')) {
                    signatureDict = signatureDict.get('V');
                    var byteRange = signatureDict.getArray('ByteRange');
                    if (byteRange.length >= 4) {
                        var buf1 = inputPdfData.subarray(0, byteRange[1]);
                        var buf2 = inputPdfData.subarray(byteRange[2]);
                        var combined = new Uint8Array(buf1.length + buf2.length);
                        combined.set(buf1, 0);
                        combined.set(buf2, buf1.length);
                        var signedContent = void 0;
                        if (encodeSignature) {
                            var hashAlgorithm = '';
                            var externalSignature = void 0;
                            var crlBytes = void 0;
                            var ocspByte = void 0;
                            var chain = void 0;
                            if (_externalChain && _externalChain.length > 0) {
                                hashAlgorithm = enumerator_1.DigestAlgorithm[algorithm];
                                var pks = new signature_privatekey_1._PdfSignaturePrivateKey(hashAlgorithm);
                                externalSignature = pks;
                                chain = _externalChain;
                            }
                            var pkcs7 = new cryptographic_signer_1._PdfCryptographicMessageSyntaxSigner(null, chain, hashAlgorithm, false);
                            var hash = pkcs7._getDigestAlgorithm()._digest(combined, hashAlgorithm);
                            pkcs7._setSignedData(signedData, null, externalSignature._getEncryptionAlgorithm());
                            var subFilter = {
                                'adbe.pkcs7.detached': enumerator_1.CryptographicStandard.cms,
                                'ETSI.CAdES.detached': enumerator_1.CryptographicStandard.cades
                            };
                            var cryptographicStandard = enumerator_1.CryptographicStandard.cms;
                            if (signatureDict.has('SubFilter')) {
                                var filter = signatureDict.get('SubFilter');
                                var kind = filter.name ? subFilter[filter.name] : undefined;
                                if (kind === enumerator_1.CryptographicStandard.cades) {
                                    cryptographicStandard = enumerator_1.CryptographicStandard.cades;
                                }
                            }
                            signedContent = pkcs7._sign(hash, null, ocspByte, crlBytes, cryptographicStandard, hashAlgorithm);
                        }
                        var spaceAvailable = (byteRange[2] - byteRange[1]) - 2;
                        if ((spaceAvailable & 1) !== 0) {
                            throw new Error('Allocated space was not enough');
                        }
                        spaceAvailable = Math.floor(spaceAvailable / 2);
                        if (spaceAvailable < signedContent.length) {
                            throw new Error('Signature content space is not enough for signed bytes');
                        }
                        var hexEncodedSignature = utils_1._bytesToHex(signedContent);
                        var signatureStartPos = byteRange[1];
                        inputPdfData[signatureStartPos] = '<'.charCodeAt(0) & 0xff;
                        for (var i = 0; i < hexEncodedSignature.length; i++) {
                            inputPdfData[signatureStartPos + 1 + i] = hexEncodedSignature.charCodeAt(i) & 0xff;
                        }
                        var signatureEndPos = signatureStartPos + 1 + hexEncodedSignature.length;
                        var paddingLength = byteRange[2] - signatureEndPos - 1;
                        if (paddingLength > 0) {
                            inputPdfData.fill('0'.charCodeAt(0) & 0xff, signatureEndPos, signatureEndPos + paddingLength);
                        }
                        inputPdfData[byteRange[2] - 1] = '>'.charCodeAt(0) & 0xff;
                    }
                }
                if (arg6 && typeof arg6 === 'string') {
                    ej2_file_utils_1.Save.save(arg6, new Blob([inputPdfData], { type: 'application/pdf' }));
                }
                else {
                    return inputPdfData;
                }
            }
            catch (error) {
                throw new Error("Signing failed: " + error.message);
            }
            finally {
                document.destroy();
            }
        };
        PdfSignature.prototype._applySignatureOptions = function (options) {
            if (options) {
                if (typeof options.cryptographicStandard !== 'undefined' && options.cryptographicStandard !== null) {
                    this._cryptographicStandard = options.cryptographicStandard;
                }
                if (typeof options.digestAlgorithm !== 'undefined' && options.digestAlgorithm !== null) {
                    this._digestAlgorithm = options.digestAlgorithm;
                }
                if (utils_1._isNullOrUndefined(options.contactInfo)) {
                    this._contactInfo = options.contactInfo;
                }
                if (utils_1._isNullOrUndefined(options.reason)) {
                    this._reason = options.reason;
                }
                if (utils_1._isNullOrUndefined(options.locationInfo)) {
                    this._locationInfo = options.locationInfo;
                }
                if (typeof options.documentPermissions !== 'undefined' && options.documentPermissions !== null) {
                    this._documentPermissions = options.documentPermissions;
                }
                if (utils_1._isNullOrUndefined(options.signedName)) {
                    this._signedName = options.signedName;
                }
                if (typeof options.certify === 'boolean') {
                    this._certify = options.certify;
                }
                if (typeof options.isLocked === 'boolean') {
                    this._isLocked = options.isLocked;
                }
            }
        };
        PdfSignature.prototype._initializeInternals = function (dictionary, field) {
            this._crossReference = field._crossReference;
            this._signed = true;
            this._signatureField = field;
            var subFilter = {
                'adbe.pkcs7.detached': enumerator_1.CryptographicStandard.cms,
                'ETSI.CAdES.detached': enumerator_1.CryptographicStandard.cades
            };
            this._signatureDictionary = new signature_dictionary_1._PdfSignatureDictionary(dictionary, this);
            if (dictionary.has('SubFilter')) {
                var filter = dictionary.get('SubFilter');
                var kind = filter.name ? subFilter[filter.name] : undefined;
                if (kind === enumerator_1.CryptographicStandard.cades) {
                    this._cryptographicStandard = enumerator_1.CryptographicStandard.cades;
                }
            }
            if (dictionary.has('Contents')) {
                this._digestAlgorithm = this._signatureDictionary._parseDigestAlgorithm();
                if (this._signatureDictionary._certificate) {
                    var certificate = this._signatureDictionary._certificate;
                    if (certificate) {
                        this._certificate = certificate;
                        this._certificateInfo = {
                            issuerName: certificate._issuerName,
                            serialNumber: certificate._serialNumber,
                            subjectName: certificate._subjectName,
                            validFrom: certificate._validFrom,
                            validTo: certificate._validTo,
                            version: certificate._version
                        };
                    }
                }
            }
            this._signedDate = this._signatureDictionary._parseSignedDate();
            this._signedName = this._signatureDictionary._parseDirect('Name');
            this._reason = this._signatureDictionary._parseDirect('Reason');
            this._locationInfo = this._signatureDictionary._parseDirect('Location');
            this._contactInfo = this._signatureDictionary._parseDirect('ContactInfo');
            if (dictionary.has('ByteRange')) {
                var arr = dictionary.get('ByteRange');
                var actualRange_1 = this._toNumberArray(arr);
                if (actualRange_1 && actualRange_1.length > 0) {
                    var hasPermission = false;
                    var catalog = this._crossReference._document._catalog._catalogDictionary;
                    if (catalog && catalog.has('Perms')) {
                        var permission = catalog.get('Perms');
                        if (permission && permission.has('DocMDP')) {
                            var docPermission = permission.get('DocMDP');
                            if (docPermission && docPermission.has('ByteRange')) {
                                var byteRange = docPermission.get('ByteRange');
                                var range = this._toNumberArray(byteRange);
                                if (range && actualRange_1 &&
                                    range.length === actualRange_1.length &&
                                    range.every(function (v, i) { return v === actualRange_1[i]; })) {
                                    hasPermission = true;
                                }
                            }
                        }
                    }
                    if (hasPermission && dictionary.has('Reference')) {
                        var primitive = dictionary.get('Reference');
                        if (primitive && Array.isArray(primitive)) {
                            primitive = primitive[0];
                        }
                        if (primitive && primitive.has('TransformParams')) {
                            var transformParam = primitive.get('TransformParams');
                            if (transformParam && transformParam.has('P')) {
                                this._documentPermissions = transformParam.get('P');
                            }
                        }
                    }
                }
            }
            if (field._dictionary && field._dictionary.has('Kids') && this._crossReference) {
                var reference = field._dictionary.get('Kids');
                var dictionary_1 = this._crossReference._cacheMap.get(reference[0]);
                if (dictionary_1 && dictionary_1.has('Lock')) {
                    var lock = dictionary_1.get('Lock');
                    if (lock) {
                        this._isLocked = true;
                    }
                }
            }
            if (!this._certify && this._crossReference._document._isLoaded && this._crossReference._document._catalog) {
                this._certify = this._checkCertificated(dictionary.objId);
            }
        };
        PdfSignature.prototype._toNumberArray = function (arr) {
            if (!arr) {
                return undefined;
            }
            if (Array.isArray(arr)) {
                var values = arr.map(function (v) { return (typeof v === 'number' ? v : Number(v)); });
                return values.every(function (n) { return Number.isFinite(n); }) ? values : undefined;
            }
            return undefined;
        };
        PdfSignature.prototype._checkCertificated = function (objId) {
            var certificatedSignature = false;
            if (this._crossReference && this._crossReference._document) {
                var document_1 = this._crossReference._document;
                if (document_1._catalog && document_1._catalog._catalogDictionary && document_1._catalog._catalogDictionary.has('Perms')) {
                    var perms = document_1._catalog._catalogDictionary.get('Perms');
                    if (perms && perms.has('DocMDP')) {
                        var documentPermissions = perms.get('DocMDP');
                        if (documentPermissions && documentPermissions.objId && objId && documentPermissions.objId === objId) {
                            certificatedSignature = true;
                        }
                    }
                }
            }
            return certificatedSignature;
        };
        PdfSignature.prototype._catalogBeginSave = function () {
            if (this._certify) {
                var document_2 = this._signatureField._crossReference._document;
                var permission = document_2._catalog._catalogDictionary.get('Perms');
                if (typeof permission === 'undefined' || permission === null) {
                    permission = new pdf_primitives_1._PdfDictionary(this._crossReference);
                    permission.update('DocMDP', this._reference);
                    permission._updated = true;
                    document_2._catalog._catalogDictionary.update('Perms', permission);
                    document_2._catalog._catalogDictionary._updated = true;
                }
                else if (!permission.has('DocMDP')) {
                    var ref = this._crossReference._getNextReference();
                    this._signatureField._crossReference._cacheMap.set(ref, this._signatureDictionary._dictionary);
                    permission.set('DocMDP', ref);
                    permission._updated = true;
                }
            }
        };
        PdfSignature.prototype._lockSignature = function () {
            var lockDictionary = new pdf_primitives_1._PdfDictionary();
            lockDictionary.update('Type', pdf_primitives_1._PdfName.get('SigFieldLock'));
            lockDictionary.update('Action', pdf_primitives_1._PdfName.get('All'));
            lockDictionary.update('P', enumerator_1.PdfCertificationFlags.forbidChanges);
            if (this._signatureField && this._signatureField._crossReference) {
                var ref = this._signatureField._crossReference._getNextReference();
                this._signatureField._crossReference._cacheMap.set(ref, lockDictionary);
                this._signatureField._widgetAnnot._dictionary.update('Lock', ref);
            }
        };
        PdfSignature.prototype._createDictionary = function (document, signature) {
            return new signature_dictionary_1._PdfSignatureDictionary(document, signature);
        };
        return PdfSignature;
    }());
    exports.PdfSignature = PdfSignature;
});