вернул к исходному состоянию сторонний скрипт cadesplugin_api.js

This commit is contained in:
Vitalii Goma 2017-04-20 13:46:23 +03:00
parent 96fc0d159f
commit f6750a71e3
3 changed files with 671 additions and 756 deletions

712
dist/crypto-pro.js vendored
View File

@ -211,128 +211,113 @@ var CryptoPro =
/***/ function(module, exports) { /***/ function(module, exports) {
;(function () { ;(function () {
/** //already loaded
* Это переделанная версия cadesplugin_api.js с сайта Крипто ПРО, if(window.cadesplugin)
* в которую добавлена поддержка IE-8.
*
* Обсуждение:
* https://www.cryptopro.ru/forum2/default.aspx?g=posts&t=9271
*
* Оригинальный файл:
* https://www.cryptopro.ru/sites/default/files/products/cades/cadesplugin_api.js
* */
var pluginObject,
plugin_resolved = 0,
plugin_reject,
plugin_resolve,
isOpera = 0,
isYaBrowser = 0,
isFireFox = 0,
canPromise = Boolean(window.Promise),
cadesplugin;
if (window.cadesplugin) {
return; return;
}
if (canPromise) { var pluginObject;
cadesplugin = new Promise(function (resolve, reject) { var plugin_resolved = 0;
var plugin_reject;
var plugin_resolve;
var isOpera = 0;
var isYaBrowser = 0;
var isFireFox = 0;
var failed_extensions = 0;
var canPromise = !!window.Promise;
var cadesplugin;
if(canPromise)
{
cadesplugin = new Promise(function(resolve, reject)
{
plugin_resolve = resolve; plugin_resolve = resolve;
plugin_reject = reject; plugin_reject = reject;
}); });
} else { } else
{
cadesplugin = {}; cadesplugin = {};
} }
function cpcsp_console_log(level, msg) { function cpcsp_console_log(level, msg){
//IE9 не может писать в консоль если не открыта вкладка developer tools //IE9 не может писать в консоль если не открыта вкладка developer tools
if (typeof console === 'undefined') { if(typeof(console) == 'undefined')
return;
if (level <= cadesplugin.current_log_level ){
if (level == cadesplugin.LOG_LEVEL_DEBUG)
console.log("DEBUG: %s", msg);
if (level == cadesplugin.LOG_LEVEL_INFO)
console.info("INFO: %s", msg);
if (level == cadesplugin.LOG_LEVEL_ERROR)
console.error("ERROR: %s", msg);
return; return;
}
if (level <= cadesplugin.current_log_level) {
if (level == cadesplugin.LOG_LEVEL_DEBUG) {
console.log('DEBUG: %s', msg);
}
if (level == cadesplugin.LOG_LEVEL_INFO) {
console.info('INFO: %s', msg);
}
if (level == cadesplugin.LOG_LEVEL_ERROR) {
console.error('ERROR: %s', msg);
}
} }
} }
function set_log_level(level) { function set_log_level(level){
var isSetLoglevel = (level == cadesplugin.LOG_LEVEL_DEBUG) if (!((level == cadesplugin.LOG_LEVEL_DEBUG) ||
|| (level == cadesplugin.LOG_LEVEL_INFO) (level == cadesplugin.LOG_LEVEL_INFO) ||
|| (level == cadesplugin.LOG_LEVEL_ERROR); (level == cadesplugin.LOG_LEVEL_ERROR))){
cpcsp_console_log(cadesplugin.LOG_LEVEL_ERROR, "cadesplugin_api.js: Incorrect log_level: " + level);
if (!isSetLoglevel) {
cpcsp_console_log(cadesplugin.LOG_LEVEL_ERROR, 'cadesplugin_api.js: Incorrect log_level: ' + level);
return; return;
} }
cadesplugin.current_log_level = level; cadesplugin.current_log_level = level;
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) { cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = DEBUG");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = DEBUG'); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO)
} cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = INFO");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) { cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = ERROR");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = INFO'); if(isNativeMessageSupported())
} {
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) { window.postMessage("set_log_level=debug", "*");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = ERROR'); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO)
} window.postMessage("set_log_level=info", "*");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR)
if (isNativeMessageSupported()) { window.postMessage("set_log_level=error", "*");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) {
window.postMessage('set_log_level=debug', '*');
}
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) {
window.postMessage('set_log_level=info', '*');
}
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) {
window.postMessage('set_log_level=error', '*');
}
} }
} }
function set_constantValues() { function set_constantValues()
{
cadesplugin.CAPICOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CAPICOM_LOCAL_MACHINE_STORE = 1;
cadesplugin.CAPICOM_CURRENT_USER_STORE = 2; cadesplugin.CAPICOM_CURRENT_USER_STORE = 2;
cadesplugin.CADESCOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CADESCOM_LOCAL_MACHINE_STORE = 1;
cadesplugin.CADESCOM_CURRENT_USER_STORE = 2; cadesplugin.CADESCOM_CURRENT_USER_STORE = 2;
cadesplugin.CADESCOM_CONTAINER_STORE = 100; cadesplugin.CADESCOM_CONTAINER_STORE = 100;
cadesplugin.CAPICOM_MY_STORE = 'My';
cadesplugin.CAPICOM_MY_STORE = "My";
cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2; cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2;
cadesplugin.XmlDsigGost3410UrlObsolete = 'http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411';
cadesplugin.XmlDsigGost3411UrlObsolete = 'http://www.w3.org/2001/04/xmldsig-more#gostr3411'; cadesplugin.XmlDsigGost3410UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
cadesplugin.XmlDsigGost3410Url = 'urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411'; cadesplugin.XmlDsigGost3411UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
cadesplugin.XmlDsigGost3411Url = 'urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411'; cadesplugin.XmlDsigGost3410Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411";
cadesplugin.XmlDsigGost3411Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411";
cadesplugin.CADESCOM_CADES_DEFAULT = 0; cadesplugin.CADESCOM_CADES_DEFAULT = 0;
cadesplugin.CADESCOM_CADES_BES = 1; cadesplugin.CADESCOM_CADES_BES = 1;
cadesplugin.CADESCOM_CADES_T = 0x5; cadesplugin.CADESCOM_CADES_T = 0x5;
cadesplugin.CADESCOM_CADES_X_LONG_TYPE_1 = 0x5d; cadesplugin.CADESCOM_CADES_X_LONG_TYPE_1 = 0x5d;
cadesplugin.CADESCOM_ENCODE_BASE64 = 0; cadesplugin.CADESCOM_ENCODE_BASE64 = 0;
cadesplugin.CADESCOM_ENCODE_BINARY = 1; cadesplugin.CADESCOM_ENCODE_BINARY = 1;
cadesplugin.CADESCOM_ENCODE_ANY = -1; cadesplugin.CADESCOM_ENCODE_ANY = -1;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2;
cadesplugin.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0; cadesplugin.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0;
cadesplugin.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1; cadesplugin.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0; cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
cadesplugin.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2; cadesplugin.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2;
@ -346,28 +331,37 @@ var CryptoPro =
cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10;
cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11;
cadesplugin.CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12; cadesplugin.CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
cadesplugin.CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128; cadesplugin.CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128;
cadesplugin.CAPICOM_PROPID_ENHKEY_USAGE = 9; cadesplugin.CAPICOM_PROPID_ENHKEY_USAGE = 9;
cadesplugin.CAPICOM_OID_OTHER = 0; cadesplugin.CAPICOM_OID_OTHER = 0;
cadesplugin.CAPICOM_OID_KEY_USAGE_EXTENSION = 10; cadesplugin.CAPICOM_OID_KEY_USAGE_EXTENSION = 10;
cadesplugin.CAPICOM_EKU_CLIENT_AUTH = 2; cadesplugin.CAPICOM_EKU_CLIENT_AUTH = 2;
cadesplugin.CAPICOM_EKU_SMARTCARD_LOGON = 5; cadesplugin.CAPICOM_EKU_SMARTCARD_LOGON = 5;
cadesplugin.CAPICOM_EKU_OTHER = 0; cadesplugin.CAPICOM_EKU_OTHER = 0;
cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0; cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1;
cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2;
cadesplugin.CADESCOM_ATTRIBUTE_OTHER = -1; cadesplugin.CADESCOM_ATTRIBUTE_OTHER = -1;
cadesplugin.CADESCOM_STRING_TO_UCS2LE = 0; cadesplugin.CADESCOM_STRING_TO_UCS2LE = 0;
cadesplugin.CADESCOM_BASE64_TO_BINARY = 1; cadesplugin.CADESCOM_BASE64_TO_BINARY = 1;
cadesplugin.CADESCOM_DISPLAY_DATA_NONE = 0; cadesplugin.CADESCOM_DISPLAY_DATA_NONE = 0;
cadesplugin.CADESCOM_DISPLAY_DATA_CONTENT = 1; cadesplugin.CADESCOM_DISPLAY_DATA_CONTENT = 1;
cadesplugin.CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2; cadesplugin.CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_DES = 2; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_DES = 2;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_AES = 4; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_AES = 4;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25;
cadesplugin.CADESCOM_HASH_ALGORITHM_SHA1 = 0; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA1 = 0;
cadesplugin.CADESCOM_HASH_ALGORITHM_MD2 = 1; cadesplugin.CADESCOM_HASH_ALGORITHM_MD2 = 1;
cadesplugin.CADESCOM_HASH_ALGORITHM_MD4 = 2; cadesplugin.CADESCOM_HASH_ALGORITHM_MD4 = 2;
@ -378,67 +372,65 @@ var CryptoPro =
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100;
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101;
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102;
cadesplugin.LOG_LEVEL_DEBUG = 4; cadesplugin.LOG_LEVEL_DEBUG = 4;
cadesplugin.LOG_LEVEL_INFO = 2; cadesplugin.LOG_LEVEL_INFO = 2;
cadesplugin.LOG_LEVEL_ERROR = 1; cadesplugin.LOG_LEVEL_ERROR = 1;
} }
function async_spawn(generatorFunc) { function async_spawn(generatorFunc) {
var generator = generatorFunc(Array.prototype.slice.call(arguments, 1)), function continuer(verb, arg) {
onFulfilled = continuer.bind(continuer, 'next'), var result;
onRejected = continuer.bind(continuer, 'throw'); try {
result = generator[verb](arg);
function continuer(verb, arg) { } catch (err) {
var result; return Promise.reject(err);
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
} }
if (result.done) {
return onFulfilled(); return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc(Array.prototype.slice.call(arguments, 1));
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
} }
function isIE() { function isIE() {
return navigator.appName === 'Microsoft Internet Explorer' // IE < 11 var retVal = (("Microsoft Internet Explorer" == navigator.appName) || // IE < 11
|| navigator.userAgent.match(/Trident\/./i); // IE 11 navigator.userAgent.match(/Trident\/./i)); // IE 11
return retVal;
} }
function isIOS() { function isIOS() {
return navigator.userAgent.match(/ipod/i) var retVal = (navigator.userAgent.match(/ipod/i) ||
|| navigator.userAgent.match(/ipad/i) navigator.userAgent.match(/ipad/i) ||
|| navigator.userAgent.match(/iphone/i); navigator.userAgent.match(/iphone/i));
return retVal;
} }
function isNativeMessageSupported() { function isNativeMessageSupported()
{
var retVal_chrome = navigator.userAgent.match(/chrome/i); var retVal_chrome = navigator.userAgent.match(/chrome/i);
isOpera = navigator.userAgent.match(/opr/i); isOpera = navigator.userAgent.match(/opr/i);
isYaBrowser = navigator.userAgent.match(/YaBrowser/i); isYaBrowser = navigator.userAgent.match(/YaBrowser/i);
isFireFox = navigator.userAgent.match(/Firefox/i); isFireFox = navigator.userAgent.match(/Firefox/i);
if (isFireFox && window.allow_firefox_cadesplugin_async) { if(isFireFox && window.allow_firefox_cadesplugin_async)
return true; return true;
}
if (retVal_chrome == null) { if(retVal_chrome == null) // В IE работаем через NPAPI
// В IE работаем через NPAPI
return false; return false;
} else { else
{
// В Chrome и Opera работаем через асинхронную версию // В Chrome и Opera работаем через асинхронную версию
if (retVal_chrome.length > 0 || isOpera != null) { if(retVal_chrome.length > 0 || isOpera != null )
{
return true; return true;
} }
} }
return false; return false;
} }
@ -447,30 +439,26 @@ var CryptoPro =
if (isIOS()) { if (isIOS()) {
// На iOS для создания объектов используется функция // На iOS для создания объектов используется функция
// call_ru_cryptopro_npcades_10_native_bridge, определенная в IOS_npcades_supp.js // call_ru_cryptopro_npcades_10_native_bridge, определенная в IOS_npcades_supp.js
return call_ru_cryptopro_npcades_10_native_bridge('CreateObject', [name]); return call_ru_cryptopro_npcades_10_native_bridge("CreateObject", [name]);
} }
if (isIE()) { if (isIE()) {
// В Internet Explorer создаются COM-объекты // В Internet Explorer создаются COM-объекты
if (name.match(/X509Enrollment/i)) { if (name.match(/X509Enrollment/i)) {
try { try {
// Объекты CertEnroll создаются через CX509EnrollmentWebClassFactory // Объекты CertEnroll создаются через CX509EnrollmentWebClassFactory
var objCertEnrollClassFactory = document.getElementById('certEnrollClassFactory'); var objCertEnrollClassFactory = document.getElementById("certEnrollClassFactory");
return objCertEnrollClassFactory.CreateObject(name); return objCertEnrollClassFactory.CreateObject(name);
} catch (e) { }
throw( catch (e) {
'Для создания обьектов X509Enrollment следует настроить ' + throw("Для создания обьектов X509Enrollment следует настроить веб-узел на использование проверки подлинности по протоколу HTTPS");
'веб-узел на использование проверки подлинности по протоколу HTTPS'
);
} }
} }
// Объекты CAPICOM и CAdESCOM создаются через CAdESCOM.WebClassFactory // Объекты CAPICOM и CAdESCOM создаются через CAdESCOM.WebClassFactory
try { try {
var objWebClassFactory = document.getElementById('webClassFactory'); var objWebClassFactory = document.getElementById("webClassFactory");
return objWebClassFactory.CreateObject(name); return objWebClassFactory.CreateObject(name);
} catch (e) { }
catch (e) {
try { try {
// Для версий плагина ниже 2.0.12538 // Для версий плагина ниже 2.0.12538
return new ActiveXObject(name); return new ActiveXObject(name);
@ -493,7 +481,6 @@ var CryptoPro =
} }
} }
} }
// В Firefox, Safari создаются объекты NPAPI // В Firefox, Safari создаются объекты NPAPI
return pluginObject.CreateObject(name); return pluginObject.CreateObject(name);
} }
@ -508,24 +495,22 @@ var CryptoPro =
function GetMessageFromException(e) { function GetMessageFromException(e) {
var err = e.message; var err = e.message;
if (!err) { if (!err) {
err = e; err = e;
} else if (e.number) { } else if (e.number) {
err += ' (0x' + decimalToHexString(e.number) + ')'; err += " (0x" + decimalToHexString(e.number) + ")";
} }
return err; return err;
} }
function getLastError(exception) { function getLastError(exception) {
if (isNativeMessageSupported() || isIE() || isIOS()) { if(isNativeMessageSupported() || isIE() || isIOS() ) {
return GetMessageFromException(exception); return GetMessageFromException(exception);
} }
try { try {
return pluginObject.getLastError(); return pluginObject.getLastError();
} catch (e) { } catch(e) {
return GetMessageFromException(exception); return GetMessageFromException(exception);
} }
} }
@ -535,312 +520,284 @@ var CryptoPro =
return pluginObject.CreateObjectAsync(name); return pluginObject.CreateObjectAsync(name);
} }
// Функции для IOS //Функции для IOS
var ru_cryptopro_npcades_10_native_bridge = { var ru_cryptopro_npcades_10_native_bridge = {
callbacksCount: 1, callbacksCount : 1,
callbacks: {}, callbacks : {},
// Automatically called by native layer when a result is available // Automatically called by native layer when a result is available
resultForCallback: function resultForCallback(callbackId, resultArray) { resultForCallback : function resultForCallback(callbackId, resultArray) {
var callback = ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId]; var callback = ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId];
if (!callback) return;
callback.apply(null,resultArray);
},
if (!callback) { // Use this in javascript to request native objective-c code
return; // functionName : string (I think the name is explicit :p)
// args : array of arguments
// callback : function with n-arguments that is going to be called when the native code returned
call : function call(functionName, args, callback) {
var hasCallback = callback && typeof callback == "function";
var callbackId = hasCallback ? ru_cryptopro_npcades_10_native_bridge.callbacksCount++ : 0;
if (hasCallback)
ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId] = callback;
var iframe = document.createElement("IFRAME");
var arrObjs = new Array("_CPNP_handle");
try{
iframe.setAttribute("src", "cpnp-js-call:" + functionName + ":" + callbackId+ ":" + encodeURIComponent(JSON.stringify(args, arrObjs)));
} catch(e){
alert(e);
} }
document.documentElement.appendChild(iframe);
callback.apply(null, resultArray); iframe.parentNode.removeChild(iframe);
}, iframe = null;
}
// Use this in javascript to request native objective-c code
// functionName : string (I think the name is explicit :p)
// args : array of arguments
// callback : function with n-arguments that is going to be called when the native code returned
call: function call(functionName, args, callback) {
var hasCallback = callback && typeof callback == 'function',
callbackId = hasCallback ? ru_cryptopro_npcades_10_native_bridge.callbacksCount++ : 0,
iframe,
arrObjs;
if (hasCallback) {
ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId] = callback;
}
iframe = document.createElement('IFRAME');
arrObjs = new Array('_CPNP_handle');
try {
iframe.setAttribute(
'src',
'cpnp-js-call:' +
functionName + ':' + callbackId + ':' + encodeURIComponent(JSON.stringify(args, arrObjs))
);
} catch (e) {
alert(e);
}
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}; };
function call_ru_cryptopro_npcades_10_native_bridge(functionName, array) { function call_ru_cryptopro_npcades_10_native_bridge(functionName, array){
var tmpobj, var tmpobj;
ex; var ex;
ru_cryptopro_npcades_10_native_bridge.call(functionName, array, function(e, response){
ru_cryptopro_npcades_10_native_bridge.call(functionName, array, function (e, response) { ex = e;
ex = e; var str='tmpobj='+response;
var str = 'tmpobj=' + response; eval(str);
if (typeof (tmpobj) == "string"){
eval(str); tmpobj = tmpobj.replace(/\\\n/gm, "\n");
tmpobj = tmpobj.replace(/\\\r/gm, "\r");
if (typeof (tmpobj) == 'string') { }
tmpobj = tmpobj.replace(/\\\n/gm, '\n'); });
tmpobj = tmpobj.replace(/\\\r/gm, '\r'); if(ex)
}
});
if (ex) {
throw ex; throw ex;
}
return tmpobj; return tmpobj;
} }
// Выводим окно поверх других с предложением установить расширение для Opera. //Выводим окно поверх других с предложением установить расширение для Opera.
// Если установленна переменная cadesplugin_skip_extension_install - не предлагаем установить расширение //Если установленна переменная cadesplugin_skip_extension_install - не предлагаем установить расширение
function install_opera_extension() { function install_opera_extension()
if (!window.cadesplugin_skip_extension_install) { {
var ovr = document.createElement('div'); if (!window.cadesplugin_skip_extension_install)
{
document.addEventListener('DOMContentLoaded', function() {
var ovr = document.createElement('div');
ovr.id = "cadesplugin_ovr";
ovr.style = "visibility: hidden; position: fixed; left: 0px; top: 0px; width:100%; height:100%; background-color: rgba(0,0,0,0.7)";
ovr.innerHTML = "<div id='cadesplugin_ovr_item' style='position:relative; width:400px; margin:100px auto; background-color:#fff; border:2px solid #000; padding:10px; text-align:center; opacity: 1; z-index: 1500'>" +
"<button id='cadesplugin_close_install' style='float: right; font-size: 10px; background: transparent; border: 1; margin: -5px'>X</button>" +
"<p>Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо установить расширение из каталога дополнений Opera." +
"<p><button id='cadesplugin_install' style='font:12px Arial'>Установить расширение</button></p>" +
"</div>";
document.getElementsByTagName("Body")[0].appendChild(ovr);
var btn_install = document.getElementById("cadesplugin_install");
btn_install.addEventListener('click', function(event) {
opr.addons.installExtension("epebfcehmdedogndhlcacafjaacknbcm",
function()
{
document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
location.reload();
},
function(){})
});
document.getElementById("cadesplugin_close_install").addEventListener('click',function()
{
plugin_loaded_error("Плагин недоступен");
document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
});
ovr.id = 'cadesplugin_ovr'; ovr.addEventListener('click',function()
ovr.style = [ {
'visibility: hidden; position: fixed; left: 0px; top: 0px;', plugin_loaded_error("Плагин недоступен");
'width:100%; height:100%; background-color: rgba(0,0,0,0.7)' document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
].join(' '); });
ovr.style.visibility="visible";
ovr.innerHTML = '\ document.getElementById("cadesplugin_ovr_item").addEventListener('click',function(e){
<div id="cadesplugin_ovr_item" style="\ e.stopPropagation();
position:relative;\ });
width:400px;\
margin:100px auto;\
background-color:#fff;\
border:2px solid #000;\
padding:10px;\
text-align:center;\
opacity: 1;\
z-index: 1500\
">\
<button id="cadesplugin_close_install"\
style="float: right; font-size: 10px; background: transparent; border: 1; margin: -5px">\
X\
</button>\
<p>\
Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо установить\
расширение из каталога дополнений Opera.\
</p>\
<p><button id="cadesplugin_install" style="font:12px Arial">Установить расширение</button></p>\
</div>\
';
document.getElementsByTagName('Body')[0].appendChild(ovr);
var btn_install = document.getElementById('cadesplugin_install');
btn_install.addEventListener('click', function (event) {
opr.addons.installExtension('epebfcehmdedogndhlcacafjaacknbcm',
function () {
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
location.reload();
},
function () {}
);
}); });
}else
document.getElementById('cadesplugin_close_install').addEventListener('click', function () { {
plugin_loaded_error('Плагин недоступен'); plugin_loaded_error("Плагин недоступен");
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
});
ovr.addEventListener('click', function () {
plugin_loaded_error('Плагин недоступен');
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
});
ovr.style.visibility = 'visible';
document.getElementById('cadesplugin_ovr_item').addEventListener('click', function (e) {
e.stopPropagation();
});
} else {
plugin_loaded_error('Плагин недоступен');
} }
} }
function firefox_nmcades_onload() { function firefox_nmcades_onload() {
window.cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error);
} }
function nmcades_api_onload() { function nmcades_api_onload () {
window.postMessage('cadesplugin_echo_request', '*'); window.postMessage("cadesplugin_echo_request", "*");
window.addEventListener("message", function (event){
window.addEventListener('message', function (event) { if (typeof(event.data) != "string" || !event.data.match("cadesplugin_loaded"))
if (typeof event.data !== 'string' || !event.data.match('cadesplugin_loaded')) { return;
return; if(isFireFox)
} {
if (isFireFox) {
// Для Firefox вместе с сообщением cadesplugin_loaded прилетает url для загрузки nmcades_plugin_api.js // Для Firefox вместе с сообщением cadesplugin_loaded прилетает url для загрузки nmcades_plugin_api.js
var url = event.data.substring(event.data.indexOf('url:') + 4); var url = event.data.substring(event.data.indexOf("url:") + 4);
var fileref = document.createElement('script'); var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute('type', 'text/javascript'); fileref.setAttribute("src", url);
fileref.setAttribute('src', url);
fileref.onerror = plugin_loaded_error; fileref.onerror = plugin_loaded_error;
fileref.onload = firefox_nmcades_onload; fileref.onload = firefox_nmcades_onload;
document.getElementsByTagName('head')[0].appendChild(fileref); document.getElementsByTagName("head")[0].appendChild(fileref);
} else {
}else {
cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error);
} }
}, false); }, false);
} }
//Загружаем расширения для Chrome, Opera, YaBrowser, FireFox, Edge //Загружаем расширения для Chrome, Opera, YaBrowser, FireFox, Edge
function load_extension() { function load_extension()
if (isFireFox) { {
if(isFireFox){
// вызываем callback руками т.к. нам нужно узнать ID расширения. Он уникальный для браузера. // вызываем callback руками т.к. нам нужно узнать ID расширения. Он уникальный для браузера.
nmcades_api_onload(); nmcades_api_onload();
return; return;
} else { } else {
var fileref = document.createElement('script'), // в асинхронном варианте для chrome и opera подключаем оба расширения
hash = isNativeMessageSupported() && isOpera ? 'epebfcehmdedogndhlcacafjaacknbcm' : 'iifchhfnnmpdbibifmljnfjhpififfog'; var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
if (hash) { fileref.setAttribute("src", "chrome-extension://iifchhfnnmpdbibifmljnfjhpififfog/nmcades_plugin_api.js");
fileref.setAttribute('type', 'text/javascript'); fileref.onerror = plugin_loaded_error;
fileref.setAttribute('src', 'chrome-extension://' + hash + '/nmcades_plugin_api.js'); fileref.onload = nmcades_api_onload;
fileref.onerror = plugin_loaded_error; document.getElementsByTagName("head")[0].appendChild(fileref);
fileref.onload = nmcades_api_onload; fileref = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(fileref); fileref.setAttribute("type", "text/javascript");
} fileref.setAttribute("src", "chrome-extension://epebfcehmdedogndhlcacafjaacknbcm/nmcades_plugin_api.js");
fileref.onerror = plugin_loaded_error;
fileref.onload = nmcades_api_onload;
document.getElementsByTagName("head")[0].appendChild(fileref);
} }
} }
// Загружаем плагин для NPAPI //Загружаем плагин для NPAPI
function load_npapi_plugin() { function load_npapi_plugin()
{
var elem = document.createElement('object'); var elem = document.createElement('object');
elem.setAttribute("id", "cadesplugin_object");
elem.setAttribute('id', 'cadesplugin_object'); elem.setAttribute("type", "application/x-cades");
elem.setAttribute('type', 'application/x-cades'); elem.setAttribute("style", "visibility: hidden");
elem.setAttribute('style', 'visibility: hidden'); document.getElementsByTagName("body")[0].appendChild(elem);
document.getElementsByTagName('body')[0].appendChild(elem); pluginObject = document.getElementById("cadesplugin_object");
if(isIE())
pluginObject = document.getElementById('cadesplugin_object'); {
if (isIE()) {
var elem1 = document.createElement('object'); var elem1 = document.createElement('object');
elem1.setAttribute("id", "certEnrollClassFactory");
elem1.setAttribute('id', 'certEnrollClassFactory'); elem1.setAttribute("classid", "clsid:884e2049-217d-11da-b2a4-000e7bbb2b09");
elem1.setAttribute('classid', 'clsid:884e2049-217d-11da-b2a4-000e7bbb2b09'); elem1.setAttribute("style", "visibility: hidden");
elem1.setAttribute('style', 'visibility: hidden'); document.getElementsByTagName("body")[0].appendChild(elem1);
document.getElementsByTagName('body')[0].appendChild(elem1);
var elem2 = document.createElement('object'); var elem2 = document.createElement('object');
elem2.setAttribute('id', 'webClassFactory'); elem2.setAttribute("id", "webClassFactory");
elem2.setAttribute('classid', 'clsid:B04C8637-10BD-484E-B0DA-B8A039F60024'); elem2.setAttribute("classid", "clsid:B04C8637-10BD-484E-B0DA-B8A039F60024");
elem2.setAttribute('style', 'visibility: hidden'); elem2.setAttribute("style", "visibility: hidden");
document.getElementsByTagName("body")[0].appendChild(elem2);
document.getElementsByTagName('body')[0].appendChild(elem2);
} }
} }
// Отправляем событие что все ок. //Отправляем событие что все ок.
function plugin_loaded() { function plugin_loaded()
{
plugin_resolved = 1; plugin_resolved = 1;
if (canPromise) { if(canPromise)
{
plugin_resolve(); plugin_resolve();
} else { }else {
window.postMessage('cadesplugin_loaded', '*'); window.postMessage("cadesplugin_loaded", "*");
} }
} }
// Отправляем событие что сломались. //Отправляем событие что сломались.
function plugin_loaded_error(msg) { function plugin_loaded_error(msg)
if (isNativeMessageSupported()) { {
if (isOpera && (typeof(msg) == 'undefined' || typeof(msg) == 'object')) { if(isNativeMessageSupported())
{
//в асинхронном варианте подключаем оба расширения, если сломались оба пробуем установить для Opera
failed_extensions++;
if(failed_extensions<2)
return;
if(isOpera && (typeof(msg) == 'undefined'|| typeof(msg) == 'object'))
{
install_opera_extension(); install_opera_extension();
return; return;
} }
} }
if(typeof(msg) == 'undefined' || typeof(msg) == 'object')
if (typeof(msg) == 'undefined' || typeof(msg) == 'object') { msg = "Плагин недоступен";
msg = 'Плагин недоступен';
}
plugin_resolved = 1; plugin_resolved = 1;
if(canPromise)
if (canPromise) { {
plugin_reject(msg); plugin_reject(msg);
} else { } else {
window.postMessage('cadesplugin_load_error', '*'); window.postMessage("cadesplugin_load_error", "*");
} }
} }
// проверяем что у нас хоть какое то событие ушло, и если не уходило кидаем еще раз ошибку //проверяем что у нас хоть какое то событие ушло, и если не уходило кидаем еще раз ошибку
function check_load_timeout() { function check_load_timeout()
if (plugin_resolved == 1) { {
if(plugin_resolved == 1)
return; return;
}
plugin_resolved = 1; plugin_resolved = 1;
if(canPromise)
if (canPromise) { {
plugin_reject('Истекло время ожидания загрузки плагина'); plugin_reject("Истекло время ожидания загрузки плагина");
} else { } else {
window.postMessage('cadesplugin_load_error', '*'); window.postMessage("cadesplugin_load_error", "*");
} }
} }
function check_npapi_plugin() { //Вспомогательная функция для NPAPI
try { function createPromise(arg)
var oAbout = CreateObject('CAdESCOM.About'); {
return new Promise(arg);
}
function check_npapi_plugin (){
try {
var oAbout = CreateObject("CAdESCOM.About");
plugin_loaded(); plugin_loaded();
} catch (err) { }
document.getElementById('cadesplugin_object').style.display = 'none'; catch (err) {
document.getElementById("cadesplugin_object").style.display = 'none';
// Объект создать не удалось, проверим, установлен ли // Объект создать не удалось, проверим, установлен ли
// вообще плагин. Такая возможность есть не во всех браузерах // вообще плагин. Такая возможность есть не во всех браузерах
var mimetype = navigator.mimeTypes['application/x-cades']; var mimetype = navigator.mimeTypes["application/x-cades"];
if (mimetype) { if (mimetype) {
var plugin = mimetype.enabledPlugin; var plugin = mimetype.enabledPlugin;
if (plugin) { if (plugin) {
plugin_loaded_error('Плагин загружен, но не создаются обьекты'); plugin_loaded_error("Плагин загружен, но не создаются обьекты");
} else { }else
plugin_loaded_error('Ошибка при загрузке плагина'); {
plugin_loaded_error("Ошибка при загрузке плагина");
} }
} else { }else
plugin_loaded_error('Плагин недоступен'); {
plugin_loaded_error("Плагин недоступен");
} }
} }
} }
// Проверяем работает ли плагин //Проверяем работает ли плагин
function check_plugin_working() { function check_plugin_working()
if (isNativeMessageSupported()) { {
if(isNativeMessageSupported())
{
load_extension(); load_extension();
} else if (!canPromise) { }else if(!canPromise) {
window.addEventListener('message', function (event) { window.addEventListener("message", function (event){
if (event.data != 'cadesplugin_echo_request') { if (event.data != "cadesplugin_echo_request")
return; return;
} load_npapi_plugin();
check_npapi_plugin();
load_npapi_plugin(); },
check_npapi_plugin(); false);
}, false); }else
} else { {
if (window.addEventListener) { if (window.addEventListener) {
window.addEventListener('load', function (event) { window.addEventListener("load", function (event) {
load_npapi_plugin(); load_npapi_plugin();
check_npapi_plugin(); check_npapi_plugin();
}, false); }, false);
@ -851,44 +808,45 @@ var CryptoPro =
} }
} }
function set_pluginObject(obj) { function set_pluginObject(obj)
{
pluginObject = obj; pluginObject = obj;
} }
// Export //Export
cadesplugin.JSModuleVersion = '2.1.0'; cadesplugin.JSModuleVersion = "2.1.0";
cadesplugin.async_spawn = async_spawn; cadesplugin.async_spawn = async_spawn;
cadesplugin.set = set_pluginObject; cadesplugin.set = set_pluginObject;
cadesplugin.set_log_level = set_log_level; cadesplugin.set_log_level = set_log_level;
cadesplugin.getLastError = getLastError; cadesplugin.getLastError = getLastError;
if (isNativeMessageSupported()) { if(isNativeMessageSupported())
{
cadesplugin.CreateObjectAsync = CreateObjectAsync; cadesplugin.CreateObjectAsync = CreateObjectAsync;
} }
if (!isNativeMessageSupported()) { if(!isNativeMessageSupported())
{
cadesplugin.CreateObject = CreateObject; cadesplugin.CreateObject = CreateObject;
} }
if (window.cadesplugin_load_timeout) { if(window.cadesplugin_load_timeout)
{
setTimeout(check_load_timeout, window.cadesplugin_load_timeout); setTimeout(check_load_timeout, window.cadesplugin_load_timeout);
} else { }
/** else
* Даже при слабом интернете плагин успевает загрузиться {
* менее чем за секунду, тк отдается из кэша
* */
setTimeout(check_load_timeout, 20000); setTimeout(check_load_timeout, 20000);
} }
set_constantValues(); set_constantValues();
cadesplugin.current_log_level = cadesplugin.LOG_LEVEL_ERROR; cadesplugin.current_log_level = cadesplugin.LOG_LEVEL_ERROR;
window.cadesplugin = cadesplugin; window.cadesplugin = cadesplugin;
check_plugin_working(); check_plugin_working();
}()); }());
/***/ }, /***/ },
/* 2 */, /* 2 */,
/* 3 */, /* 3 */,

File diff suppressed because one or more lines are too long

View File

@ -1,126 +1,111 @@
;(function () { ;(function () {
/** //already loaded
* Это переделанная версия cadesplugin_api.js с сайта Крипто ПРО, if(window.cadesplugin)
* в которую добавлена поддержка IE-8.
*
* Обсуждение:
* https://www.cryptopro.ru/forum2/default.aspx?g=posts&t=9271
*
* Оригинальный файл:
* https://www.cryptopro.ru/sites/default/files/products/cades/cadesplugin_api.js
* */
var pluginObject,
plugin_resolved = 0,
plugin_reject,
plugin_resolve,
isOpera = 0,
isYaBrowser = 0,
isFireFox = 0,
canPromise = Boolean(window.Promise),
cadesplugin;
if (window.cadesplugin) {
return; return;
}
if (canPromise) { var pluginObject;
cadesplugin = new Promise(function (resolve, reject) { var plugin_resolved = 0;
var plugin_reject;
var plugin_resolve;
var isOpera = 0;
var isYaBrowser = 0;
var isFireFox = 0;
var failed_extensions = 0;
var canPromise = !!window.Promise;
var cadesplugin;
if(canPromise)
{
cadesplugin = new Promise(function(resolve, reject)
{
plugin_resolve = resolve; plugin_resolve = resolve;
plugin_reject = reject; plugin_reject = reject;
}); });
} else { } else
{
cadesplugin = {}; cadesplugin = {};
} }
function cpcsp_console_log(level, msg) { function cpcsp_console_log(level, msg){
//IE9 не может писать в консоль если не открыта вкладка developer tools //IE9 не может писать в консоль если не открыта вкладка developer tools
if (typeof console === 'undefined') { if(typeof(console) == 'undefined')
return;
if (level <= cadesplugin.current_log_level ){
if (level == cadesplugin.LOG_LEVEL_DEBUG)
console.log("DEBUG: %s", msg);
if (level == cadesplugin.LOG_LEVEL_INFO)
console.info("INFO: %s", msg);
if (level == cadesplugin.LOG_LEVEL_ERROR)
console.error("ERROR: %s", msg);
return; return;
}
if (level <= cadesplugin.current_log_level) {
if (level == cadesplugin.LOG_LEVEL_DEBUG) {
console.log('DEBUG: %s', msg);
}
if (level == cadesplugin.LOG_LEVEL_INFO) {
console.info('INFO: %s', msg);
}
if (level == cadesplugin.LOG_LEVEL_ERROR) {
console.error('ERROR: %s', msg);
}
} }
} }
function set_log_level(level) { function set_log_level(level){
var isSetLoglevel = (level == cadesplugin.LOG_LEVEL_DEBUG) if (!((level == cadesplugin.LOG_LEVEL_DEBUG) ||
|| (level == cadesplugin.LOG_LEVEL_INFO) (level == cadesplugin.LOG_LEVEL_INFO) ||
|| (level == cadesplugin.LOG_LEVEL_ERROR); (level == cadesplugin.LOG_LEVEL_ERROR))){
cpcsp_console_log(cadesplugin.LOG_LEVEL_ERROR, "cadesplugin_api.js: Incorrect log_level: " + level);
if (!isSetLoglevel) {
cpcsp_console_log(cadesplugin.LOG_LEVEL_ERROR, 'cadesplugin_api.js: Incorrect log_level: ' + level);
return; return;
} }
cadesplugin.current_log_level = level; cadesplugin.current_log_level = level;
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) { cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = DEBUG");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = DEBUG'); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO)
} cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = INFO");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) { cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, "cadesplugin_api.js: log_level = ERROR");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = INFO'); if(isNativeMessageSupported())
} {
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG)
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) { window.postMessage("set_log_level=debug", "*");
cpcsp_console_log(cadesplugin.LOG_LEVEL_INFO, 'cadesplugin_api.js: log_level = ERROR'); if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO)
} window.postMessage("set_log_level=info", "*");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR)
if (isNativeMessageSupported()) { window.postMessage("set_log_level=error", "*");
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_DEBUG) {
window.postMessage('set_log_level=debug', '*');
}
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_INFO) {
window.postMessage('set_log_level=info', '*');
}
if (cadesplugin.current_log_level == cadesplugin.LOG_LEVEL_ERROR) {
window.postMessage('set_log_level=error', '*');
}
} }
} }
function set_constantValues() { function set_constantValues()
{
cadesplugin.CAPICOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CAPICOM_LOCAL_MACHINE_STORE = 1;
cadesplugin.CAPICOM_CURRENT_USER_STORE = 2; cadesplugin.CAPICOM_CURRENT_USER_STORE = 2;
cadesplugin.CADESCOM_LOCAL_MACHINE_STORE = 1; cadesplugin.CADESCOM_LOCAL_MACHINE_STORE = 1;
cadesplugin.CADESCOM_CURRENT_USER_STORE = 2; cadesplugin.CADESCOM_CURRENT_USER_STORE = 2;
cadesplugin.CADESCOM_CONTAINER_STORE = 100; cadesplugin.CADESCOM_CONTAINER_STORE = 100;
cadesplugin.CAPICOM_MY_STORE = 'My';
cadesplugin.CAPICOM_MY_STORE = "My";
cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2; cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1;
cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2; cadesplugin.CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2;
cadesplugin.XmlDsigGost3410UrlObsolete = 'http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411';
cadesplugin.XmlDsigGost3411UrlObsolete = 'http://www.w3.org/2001/04/xmldsig-more#gostr3411'; cadesplugin.XmlDsigGost3410UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
cadesplugin.XmlDsigGost3410Url = 'urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411'; cadesplugin.XmlDsigGost3411UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
cadesplugin.XmlDsigGost3411Url = 'urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411'; cadesplugin.XmlDsigGost3410Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411";
cadesplugin.XmlDsigGost3411Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411";
cadesplugin.CADESCOM_CADES_DEFAULT = 0; cadesplugin.CADESCOM_CADES_DEFAULT = 0;
cadesplugin.CADESCOM_CADES_BES = 1; cadesplugin.CADESCOM_CADES_BES = 1;
cadesplugin.CADESCOM_CADES_T = 0x5; cadesplugin.CADESCOM_CADES_T = 0x5;
cadesplugin.CADESCOM_CADES_X_LONG_TYPE_1 = 0x5d; cadesplugin.CADESCOM_CADES_X_LONG_TYPE_1 = 0x5d;
cadesplugin.CADESCOM_ENCODE_BASE64 = 0; cadesplugin.CADESCOM_ENCODE_BASE64 = 0;
cadesplugin.CADESCOM_ENCODE_BINARY = 1; cadesplugin.CADESCOM_ENCODE_BINARY = 1;
cadesplugin.CADESCOM_ENCODE_ANY = -1; cadesplugin.CADESCOM_ENCODE_ANY = -1;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1;
cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2; cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2;
cadesplugin.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0; cadesplugin.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0;
cadesplugin.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1; cadesplugin.CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0; cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1; cadesplugin.CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
cadesplugin.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2; cadesplugin.CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2;
@ -134,28 +119,37 @@
cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10;
cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11; cadesplugin.CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11;
cadesplugin.CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12; cadesplugin.CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
cadesplugin.CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128; cadesplugin.CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128;
cadesplugin.CAPICOM_PROPID_ENHKEY_USAGE = 9; cadesplugin.CAPICOM_PROPID_ENHKEY_USAGE = 9;
cadesplugin.CAPICOM_OID_OTHER = 0; cadesplugin.CAPICOM_OID_OTHER = 0;
cadesplugin.CAPICOM_OID_KEY_USAGE_EXTENSION = 10; cadesplugin.CAPICOM_OID_KEY_USAGE_EXTENSION = 10;
cadesplugin.CAPICOM_EKU_CLIENT_AUTH = 2; cadesplugin.CAPICOM_EKU_CLIENT_AUTH = 2;
cadesplugin.CAPICOM_EKU_SMARTCARD_LOGON = 5; cadesplugin.CAPICOM_EKU_SMARTCARD_LOGON = 5;
cadesplugin.CAPICOM_EKU_OTHER = 0; cadesplugin.CAPICOM_EKU_OTHER = 0;
cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0; cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1;
cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2; cadesplugin.CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2;
cadesplugin.CADESCOM_ATTRIBUTE_OTHER = -1; cadesplugin.CADESCOM_ATTRIBUTE_OTHER = -1;
cadesplugin.CADESCOM_STRING_TO_UCS2LE = 0; cadesplugin.CADESCOM_STRING_TO_UCS2LE = 0;
cadesplugin.CADESCOM_BASE64_TO_BINARY = 1; cadesplugin.CADESCOM_BASE64_TO_BINARY = 1;
cadesplugin.CADESCOM_DISPLAY_DATA_NONE = 0; cadesplugin.CADESCOM_DISPLAY_DATA_NONE = 0;
cadesplugin.CADESCOM_DISPLAY_DATA_CONTENT = 1; cadesplugin.CADESCOM_DISPLAY_DATA_CONTENT = 1;
cadesplugin.CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2; cadesplugin.CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_DES = 2; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_DES = 2;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_AES = 4; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_AES = 4;
cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25; cadesplugin.CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25;
cadesplugin.CADESCOM_HASH_ALGORITHM_SHA1 = 0; cadesplugin.CADESCOM_HASH_ALGORITHM_SHA1 = 0;
cadesplugin.CADESCOM_HASH_ALGORITHM_MD2 = 1; cadesplugin.CADESCOM_HASH_ALGORITHM_MD2 = 1;
cadesplugin.CADESCOM_HASH_ALGORITHM_MD4 = 2; cadesplugin.CADESCOM_HASH_ALGORITHM_MD4 = 2;
@ -166,67 +160,65 @@
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100;
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101;
cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102; cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102;
cadesplugin.LOG_LEVEL_DEBUG = 4; cadesplugin.LOG_LEVEL_DEBUG = 4;
cadesplugin.LOG_LEVEL_INFO = 2; cadesplugin.LOG_LEVEL_INFO = 2;
cadesplugin.LOG_LEVEL_ERROR = 1; cadesplugin.LOG_LEVEL_ERROR = 1;
} }
function async_spawn(generatorFunc) { function async_spawn(generatorFunc) {
var generator = generatorFunc(Array.prototype.slice.call(arguments, 1)), function continuer(verb, arg) {
onFulfilled = continuer.bind(continuer, 'next'), var result;
onRejected = continuer.bind(continuer, 'throw'); try {
result = generator[verb](arg);
function continuer(verb, arg) { } catch (err) {
var result; return Promise.reject(err);
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
} }
if (result.done) {
return onFulfilled(); return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc(Array.prototype.slice.call(arguments, 1));
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
} }
function isIE() { function isIE() {
return navigator.appName === 'Microsoft Internet Explorer' // IE < 11 var retVal = (("Microsoft Internet Explorer" == navigator.appName) || // IE < 11
|| navigator.userAgent.match(/Trident\/./i); // IE 11 navigator.userAgent.match(/Trident\/./i)); // IE 11
return retVal;
} }
function isIOS() { function isIOS() {
return navigator.userAgent.match(/ipod/i) var retVal = (navigator.userAgent.match(/ipod/i) ||
|| navigator.userAgent.match(/ipad/i) navigator.userAgent.match(/ipad/i) ||
|| navigator.userAgent.match(/iphone/i); navigator.userAgent.match(/iphone/i));
return retVal;
} }
function isNativeMessageSupported() { function isNativeMessageSupported()
{
var retVal_chrome = navigator.userAgent.match(/chrome/i); var retVal_chrome = navigator.userAgent.match(/chrome/i);
isOpera = navigator.userAgent.match(/opr/i); isOpera = navigator.userAgent.match(/opr/i);
isYaBrowser = navigator.userAgent.match(/YaBrowser/i); isYaBrowser = navigator.userAgent.match(/YaBrowser/i);
isFireFox = navigator.userAgent.match(/Firefox/i); isFireFox = navigator.userAgent.match(/Firefox/i);
if (isFireFox && window.allow_firefox_cadesplugin_async) { if(isFireFox && window.allow_firefox_cadesplugin_async)
return true; return true;
}
if (retVal_chrome == null) { if(retVal_chrome == null) // В IE работаем через NPAPI
// В IE работаем через NPAPI
return false; return false;
} else { else
{
// В Chrome и Opera работаем через асинхронную версию // В Chrome и Opera работаем через асинхронную версию
if (retVal_chrome.length > 0 || isOpera != null) { if(retVal_chrome.length > 0 || isOpera != null )
{
return true; return true;
} }
} }
return false; return false;
} }
@ -235,30 +227,26 @@
if (isIOS()) { if (isIOS()) {
// На iOS для создания объектов используется функция // На iOS для создания объектов используется функция
// call_ru_cryptopro_npcades_10_native_bridge, определенная в IOS_npcades_supp.js // call_ru_cryptopro_npcades_10_native_bridge, определенная в IOS_npcades_supp.js
return call_ru_cryptopro_npcades_10_native_bridge('CreateObject', [name]); return call_ru_cryptopro_npcades_10_native_bridge("CreateObject", [name]);
} }
if (isIE()) { if (isIE()) {
// В Internet Explorer создаются COM-объекты // В Internet Explorer создаются COM-объекты
if (name.match(/X509Enrollment/i)) { if (name.match(/X509Enrollment/i)) {
try { try {
// Объекты CertEnroll создаются через CX509EnrollmentWebClassFactory // Объекты CertEnroll создаются через CX509EnrollmentWebClassFactory
var objCertEnrollClassFactory = document.getElementById('certEnrollClassFactory'); var objCertEnrollClassFactory = document.getElementById("certEnrollClassFactory");
return objCertEnrollClassFactory.CreateObject(name); return objCertEnrollClassFactory.CreateObject(name);
} catch (e) { }
throw( catch (e) {
'Для создания обьектов X509Enrollment следует настроить ' + throw("Для создания обьектов X509Enrollment следует настроить веб-узел на использование проверки подлинности по протоколу HTTPS");
'веб-узел на использование проверки подлинности по протоколу HTTPS'
);
} }
} }
// Объекты CAPICOM и CAdESCOM создаются через CAdESCOM.WebClassFactory // Объекты CAPICOM и CAdESCOM создаются через CAdESCOM.WebClassFactory
try { try {
var objWebClassFactory = document.getElementById('webClassFactory'); var objWebClassFactory = document.getElementById("webClassFactory");
return objWebClassFactory.CreateObject(name); return objWebClassFactory.CreateObject(name);
} catch (e) { }
catch (e) {
try { try {
// Для версий плагина ниже 2.0.12538 // Для версий плагина ниже 2.0.12538
return new ActiveXObject(name); return new ActiveXObject(name);
@ -281,7 +269,6 @@
} }
} }
} }
// В Firefox, Safari создаются объекты NPAPI // В Firefox, Safari создаются объекты NPAPI
return pluginObject.CreateObject(name); return pluginObject.CreateObject(name);
} }
@ -296,24 +283,22 @@
function GetMessageFromException(e) { function GetMessageFromException(e) {
var err = e.message; var err = e.message;
if (!err) { if (!err) {
err = e; err = e;
} else if (e.number) { } else if (e.number) {
err += ' (0x' + decimalToHexString(e.number) + ')'; err += " (0x" + decimalToHexString(e.number) + ")";
} }
return err; return err;
} }
function getLastError(exception) { function getLastError(exception) {
if (isNativeMessageSupported() || isIE() || isIOS()) { if(isNativeMessageSupported() || isIE() || isIOS() ) {
return GetMessageFromException(exception); return GetMessageFromException(exception);
} }
try { try {
return pluginObject.getLastError(); return pluginObject.getLastError();
} catch (e) { } catch(e) {
return GetMessageFromException(exception); return GetMessageFromException(exception);
} }
} }
@ -323,312 +308,284 @@
return pluginObject.CreateObjectAsync(name); return pluginObject.CreateObjectAsync(name);
} }
// Функции для IOS //Функции для IOS
var ru_cryptopro_npcades_10_native_bridge = { var ru_cryptopro_npcades_10_native_bridge = {
callbacksCount: 1, callbacksCount : 1,
callbacks: {}, callbacks : {},
// Automatically called by native layer when a result is available // Automatically called by native layer when a result is available
resultForCallback: function resultForCallback(callbackId, resultArray) { resultForCallback : function resultForCallback(callbackId, resultArray) {
var callback = ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId]; var callback = ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId];
if (!callback) return;
callback.apply(null,resultArray);
},
if (!callback) { // Use this in javascript to request native objective-c code
return; // functionName : string (I think the name is explicit :p)
// args : array of arguments
// callback : function with n-arguments that is going to be called when the native code returned
call : function call(functionName, args, callback) {
var hasCallback = callback && typeof callback == "function";
var callbackId = hasCallback ? ru_cryptopro_npcades_10_native_bridge.callbacksCount++ : 0;
if (hasCallback)
ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId] = callback;
var iframe = document.createElement("IFRAME");
var arrObjs = new Array("_CPNP_handle");
try{
iframe.setAttribute("src", "cpnp-js-call:" + functionName + ":" + callbackId+ ":" + encodeURIComponent(JSON.stringify(args, arrObjs)));
} catch(e){
alert(e);
} }
document.documentElement.appendChild(iframe);
callback.apply(null, resultArray); iframe.parentNode.removeChild(iframe);
}, iframe = null;
}
// Use this in javascript to request native objective-c code
// functionName : string (I think the name is explicit :p)
// args : array of arguments
// callback : function with n-arguments that is going to be called when the native code returned
call: function call(functionName, args, callback) {
var hasCallback = callback && typeof callback == 'function',
callbackId = hasCallback ? ru_cryptopro_npcades_10_native_bridge.callbacksCount++ : 0,
iframe,
arrObjs;
if (hasCallback) {
ru_cryptopro_npcades_10_native_bridge.callbacks[callbackId] = callback;
}
iframe = document.createElement('IFRAME');
arrObjs = new Array('_CPNP_handle');
try {
iframe.setAttribute(
'src',
'cpnp-js-call:' +
functionName + ':' + callbackId + ':' + encodeURIComponent(JSON.stringify(args, arrObjs))
);
} catch (e) {
alert(e);
}
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}; };
function call_ru_cryptopro_npcades_10_native_bridge(functionName, array) { function call_ru_cryptopro_npcades_10_native_bridge(functionName, array){
var tmpobj, var tmpobj;
ex; var ex;
ru_cryptopro_npcades_10_native_bridge.call(functionName, array, function(e, response){
ru_cryptopro_npcades_10_native_bridge.call(functionName, array, function (e, response) { ex = e;
ex = e; var str='tmpobj='+response;
var str = 'tmpobj=' + response; eval(str);
if (typeof (tmpobj) == "string"){
eval(str); tmpobj = tmpobj.replace(/\\\n/gm, "\n");
tmpobj = tmpobj.replace(/\\\r/gm, "\r");
if (typeof (tmpobj) == 'string') { }
tmpobj = tmpobj.replace(/\\\n/gm, '\n'); });
tmpobj = tmpobj.replace(/\\\r/gm, '\r'); if(ex)
}
});
if (ex) {
throw ex; throw ex;
}
return tmpobj; return tmpobj;
} }
// Выводим окно поверх других с предложением установить расширение для Opera. //Выводим окно поверх других с предложением установить расширение для Opera.
// Если установленна переменная cadesplugin_skip_extension_install - не предлагаем установить расширение //Если установленна переменная cadesplugin_skip_extension_install - не предлагаем установить расширение
function install_opera_extension() { function install_opera_extension()
if (!window.cadesplugin_skip_extension_install) { {
var ovr = document.createElement('div'); if (!window.cadesplugin_skip_extension_install)
{
document.addEventListener('DOMContentLoaded', function() {
var ovr = document.createElement('div');
ovr.id = "cadesplugin_ovr";
ovr.style = "visibility: hidden; position: fixed; left: 0px; top: 0px; width:100%; height:100%; background-color: rgba(0,0,0,0.7)";
ovr.innerHTML = "<div id='cadesplugin_ovr_item' style='position:relative; width:400px; margin:100px auto; background-color:#fff; border:2px solid #000; padding:10px; text-align:center; opacity: 1; z-index: 1500'>" +
"<button id='cadesplugin_close_install' style='float: right; font-size: 10px; background: transparent; border: 1; margin: -5px'>X</button>" +
"<p>Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо установить расширение из каталога дополнений Opera." +
"<p><button id='cadesplugin_install' style='font:12px Arial'>Установить расширение</button></p>" +
"</div>";
document.getElementsByTagName("Body")[0].appendChild(ovr);
var btn_install = document.getElementById("cadesplugin_install");
btn_install.addEventListener('click', function(event) {
opr.addons.installExtension("epebfcehmdedogndhlcacafjaacknbcm",
function()
{
document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
location.reload();
},
function(){})
});
document.getElementById("cadesplugin_close_install").addEventListener('click',function()
{
plugin_loaded_error("Плагин недоступен");
document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
});
ovr.id = 'cadesplugin_ovr'; ovr.addEventListener('click',function()
ovr.style = [ {
'visibility: hidden; position: fixed; left: 0px; top: 0px;', plugin_loaded_error("Плагин недоступен");
'width:100%; height:100%; background-color: rgba(0,0,0,0.7)' document.getElementById("cadesplugin_ovr").style.visibility = 'hidden';
].join(' '); });
ovr.style.visibility="visible";
ovr.innerHTML = '\ document.getElementById("cadesplugin_ovr_item").addEventListener('click',function(e){
<div id="cadesplugin_ovr_item" style="\ e.stopPropagation();
position:relative;\ });
width:400px;\
margin:100px auto;\
background-color:#fff;\
border:2px solid #000;\
padding:10px;\
text-align:center;\
opacity: 1;\
z-index: 1500\
">\
<button id="cadesplugin_close_install"\
style="float: right; font-size: 10px; background: transparent; border: 1; margin: -5px">\
X\
</button>\
<p>\
Для работы КриптоПро ЭЦП Browser plugin на данном сайте необходимо установить\
расширение из каталога дополнений Opera.\
</p>\
<p><button id="cadesplugin_install" style="font:12px Arial">Установить расширение</button></p>\
</div>\
';
document.getElementsByTagName('Body')[0].appendChild(ovr);
var btn_install = document.getElementById('cadesplugin_install');
btn_install.addEventListener('click', function (event) {
opr.addons.installExtension('epebfcehmdedogndhlcacafjaacknbcm',
function () {
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
location.reload();
},
function () {}
);
}); });
}else
document.getElementById('cadesplugin_close_install').addEventListener('click', function () { {
plugin_loaded_error('Плагин недоступен'); plugin_loaded_error("Плагин недоступен");
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
});
ovr.addEventListener('click', function () {
plugin_loaded_error('Плагин недоступен');
document.getElementById('cadesplugin_ovr').style.visibility = 'hidden';
});
ovr.style.visibility = 'visible';
document.getElementById('cadesplugin_ovr_item').addEventListener('click', function (e) {
e.stopPropagation();
});
} else {
plugin_loaded_error('Плагин недоступен');
} }
} }
function firefox_nmcades_onload() { function firefox_nmcades_onload() {
window.cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error);
} }
function nmcades_api_onload() { function nmcades_api_onload () {
window.postMessage('cadesplugin_echo_request', '*'); window.postMessage("cadesplugin_echo_request", "*");
window.addEventListener("message", function (event){
window.addEventListener('message', function (event) { if (typeof(event.data) != "string" || !event.data.match("cadesplugin_loaded"))
if (typeof event.data !== 'string' || !event.data.match('cadesplugin_loaded')) { return;
return; if(isFireFox)
} {
if (isFireFox) {
// Для Firefox вместе с сообщением cadesplugin_loaded прилетает url для загрузки nmcades_plugin_api.js // Для Firefox вместе с сообщением cadesplugin_loaded прилетает url для загрузки nmcades_plugin_api.js
var url = event.data.substring(event.data.indexOf('url:') + 4); var url = event.data.substring(event.data.indexOf("url:") + 4);
var fileref = document.createElement('script'); var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute('type', 'text/javascript'); fileref.setAttribute("src", url);
fileref.setAttribute('src', url);
fileref.onerror = plugin_loaded_error; fileref.onerror = plugin_loaded_error;
fileref.onload = firefox_nmcades_onload; fileref.onload = firefox_nmcades_onload;
document.getElementsByTagName('head')[0].appendChild(fileref); document.getElementsByTagName("head")[0].appendChild(fileref);
} else {
}else {
cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error); cpcsp_chrome_nmcades.check_chrome_plugin(plugin_loaded, plugin_loaded_error);
} }
}, false); }, false);
} }
//Загружаем расширения для Chrome, Opera, YaBrowser, FireFox, Edge //Загружаем расширения для Chrome, Opera, YaBrowser, FireFox, Edge
function load_extension() { function load_extension()
if (isFireFox) { {
if(isFireFox){
// вызываем callback руками т.к. нам нужно узнать ID расширения. Он уникальный для браузера. // вызываем callback руками т.к. нам нужно узнать ID расширения. Он уникальный для браузера.
nmcades_api_onload(); nmcades_api_onload();
return; return;
} else { } else {
var fileref = document.createElement('script'), // в асинхронном варианте для chrome и opera подключаем оба расширения
hash = isNativeMessageSupported() && isOpera ? 'epebfcehmdedogndhlcacafjaacknbcm' : 'iifchhfnnmpdbibifmljnfjhpififfog'; var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
if (hash) { fileref.setAttribute("src", "chrome-extension://iifchhfnnmpdbibifmljnfjhpififfog/nmcades_plugin_api.js");
fileref.setAttribute('type', 'text/javascript'); fileref.onerror = plugin_loaded_error;
fileref.setAttribute('src', 'chrome-extension://' + hash + '/nmcades_plugin_api.js'); fileref.onload = nmcades_api_onload;
fileref.onerror = plugin_loaded_error; document.getElementsByTagName("head")[0].appendChild(fileref);
fileref.onload = nmcades_api_onload; fileref = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(fileref); fileref.setAttribute("type", "text/javascript");
} fileref.setAttribute("src", "chrome-extension://epebfcehmdedogndhlcacafjaacknbcm/nmcades_plugin_api.js");
fileref.onerror = plugin_loaded_error;
fileref.onload = nmcades_api_onload;
document.getElementsByTagName("head")[0].appendChild(fileref);
} }
} }
// Загружаем плагин для NPAPI //Загружаем плагин для NPAPI
function load_npapi_plugin() { function load_npapi_plugin()
{
var elem = document.createElement('object'); var elem = document.createElement('object');
elem.setAttribute("id", "cadesplugin_object");
elem.setAttribute('id', 'cadesplugin_object'); elem.setAttribute("type", "application/x-cades");
elem.setAttribute('type', 'application/x-cades'); elem.setAttribute("style", "visibility: hidden");
elem.setAttribute('style', 'visibility: hidden'); document.getElementsByTagName("body")[0].appendChild(elem);
document.getElementsByTagName('body')[0].appendChild(elem); pluginObject = document.getElementById("cadesplugin_object");
if(isIE())
pluginObject = document.getElementById('cadesplugin_object'); {
if (isIE()) {
var elem1 = document.createElement('object'); var elem1 = document.createElement('object');
elem1.setAttribute("id", "certEnrollClassFactory");
elem1.setAttribute('id', 'certEnrollClassFactory'); elem1.setAttribute("classid", "clsid:884e2049-217d-11da-b2a4-000e7bbb2b09");
elem1.setAttribute('classid', 'clsid:884e2049-217d-11da-b2a4-000e7bbb2b09'); elem1.setAttribute("style", "visibility: hidden");
elem1.setAttribute('style', 'visibility: hidden'); document.getElementsByTagName("body")[0].appendChild(elem1);
document.getElementsByTagName('body')[0].appendChild(elem1);
var elem2 = document.createElement('object'); var elem2 = document.createElement('object');
elem2.setAttribute('id', 'webClassFactory'); elem2.setAttribute("id", "webClassFactory");
elem2.setAttribute('classid', 'clsid:B04C8637-10BD-484E-B0DA-B8A039F60024'); elem2.setAttribute("classid", "clsid:B04C8637-10BD-484E-B0DA-B8A039F60024");
elem2.setAttribute('style', 'visibility: hidden'); elem2.setAttribute("style", "visibility: hidden");
document.getElementsByTagName("body")[0].appendChild(elem2);
document.getElementsByTagName('body')[0].appendChild(elem2);
} }
} }
// Отправляем событие что все ок. //Отправляем событие что все ок.
function plugin_loaded() { function plugin_loaded()
{
plugin_resolved = 1; plugin_resolved = 1;
if (canPromise) { if(canPromise)
{
plugin_resolve(); plugin_resolve();
} else { }else {
window.postMessage('cadesplugin_loaded', '*'); window.postMessage("cadesplugin_loaded", "*");
} }
} }
// Отправляем событие что сломались. //Отправляем событие что сломались.
function plugin_loaded_error(msg) { function plugin_loaded_error(msg)
if (isNativeMessageSupported()) { {
if (isOpera && (typeof(msg) == 'undefined' || typeof(msg) == 'object')) { if(isNativeMessageSupported())
{
//в асинхронном варианте подключаем оба расширения, если сломались оба пробуем установить для Opera
failed_extensions++;
if(failed_extensions<2)
return;
if(isOpera && (typeof(msg) == 'undefined'|| typeof(msg) == 'object'))
{
install_opera_extension(); install_opera_extension();
return; return;
} }
} }
if(typeof(msg) == 'undefined' || typeof(msg) == 'object')
if (typeof(msg) == 'undefined' || typeof(msg) == 'object') { msg = "Плагин недоступен";
msg = 'Плагин недоступен';
}
plugin_resolved = 1; plugin_resolved = 1;
if(canPromise)
if (canPromise) { {
plugin_reject(msg); plugin_reject(msg);
} else { } else {
window.postMessage('cadesplugin_load_error', '*'); window.postMessage("cadesplugin_load_error", "*");
} }
} }
// проверяем что у нас хоть какое то событие ушло, и если не уходило кидаем еще раз ошибку //проверяем что у нас хоть какое то событие ушло, и если не уходило кидаем еще раз ошибку
function check_load_timeout() { function check_load_timeout()
if (plugin_resolved == 1) { {
if(plugin_resolved == 1)
return; return;
}
plugin_resolved = 1; plugin_resolved = 1;
if(canPromise)
if (canPromise) { {
plugin_reject('Истекло время ожидания загрузки плагина'); plugin_reject("Истекло время ожидания загрузки плагина");
} else { } else {
window.postMessage('cadesplugin_load_error', '*'); window.postMessage("cadesplugin_load_error", "*");
} }
} }
function check_npapi_plugin() { //Вспомогательная функция для NPAPI
try { function createPromise(arg)
var oAbout = CreateObject('CAdESCOM.About'); {
return new Promise(arg);
}
function check_npapi_plugin (){
try {
var oAbout = CreateObject("CAdESCOM.About");
plugin_loaded(); plugin_loaded();
} catch (err) { }
document.getElementById('cadesplugin_object').style.display = 'none'; catch (err) {
document.getElementById("cadesplugin_object").style.display = 'none';
// Объект создать не удалось, проверим, установлен ли // Объект создать не удалось, проверим, установлен ли
// вообще плагин. Такая возможность есть не во всех браузерах // вообще плагин. Такая возможность есть не во всех браузерах
var mimetype = navigator.mimeTypes['application/x-cades']; var mimetype = navigator.mimeTypes["application/x-cades"];
if (mimetype) { if (mimetype) {
var plugin = mimetype.enabledPlugin; var plugin = mimetype.enabledPlugin;
if (plugin) { if (plugin) {
plugin_loaded_error('Плагин загружен, но не создаются обьекты'); plugin_loaded_error("Плагин загружен, но не создаются обьекты");
} else { }else
plugin_loaded_error('Ошибка при загрузке плагина'); {
plugin_loaded_error("Ошибка при загрузке плагина");
} }
} else { }else
plugin_loaded_error('Плагин недоступен'); {
plugin_loaded_error("Плагин недоступен");
} }
} }
} }
// Проверяем работает ли плагин //Проверяем работает ли плагин
function check_plugin_working() { function check_plugin_working()
if (isNativeMessageSupported()) { {
if(isNativeMessageSupported())
{
load_extension(); load_extension();
} else if (!canPromise) { }else if(!canPromise) {
window.addEventListener('message', function (event) { window.addEventListener("message", function (event){
if (event.data != 'cadesplugin_echo_request') { if (event.data != "cadesplugin_echo_request")
return; return;
} load_npapi_plugin();
check_npapi_plugin();
load_npapi_plugin(); },
check_npapi_plugin(); false);
}, false); }else
} else { {
if (window.addEventListener) { if (window.addEventListener) {
window.addEventListener('load', function (event) { window.addEventListener("load", function (event) {
load_npapi_plugin(); load_npapi_plugin();
check_npapi_plugin(); check_npapi_plugin();
}, false); }, false);
@ -639,40 +596,40 @@
} }
} }
function set_pluginObject(obj) { function set_pluginObject(obj)
{
pluginObject = obj; pluginObject = obj;
} }
// Export //Export
cadesplugin.JSModuleVersion = '2.1.0'; cadesplugin.JSModuleVersion = "2.1.0";
cadesplugin.async_spawn = async_spawn; cadesplugin.async_spawn = async_spawn;
cadesplugin.set = set_pluginObject; cadesplugin.set = set_pluginObject;
cadesplugin.set_log_level = set_log_level; cadesplugin.set_log_level = set_log_level;
cadesplugin.getLastError = getLastError; cadesplugin.getLastError = getLastError;
if (isNativeMessageSupported()) { if(isNativeMessageSupported())
{
cadesplugin.CreateObjectAsync = CreateObjectAsync; cadesplugin.CreateObjectAsync = CreateObjectAsync;
} }
if (!isNativeMessageSupported()) { if(!isNativeMessageSupported())
{
cadesplugin.CreateObject = CreateObject; cadesplugin.CreateObject = CreateObject;
} }
if (window.cadesplugin_load_timeout) { if(window.cadesplugin_load_timeout)
{
setTimeout(check_load_timeout, window.cadesplugin_load_timeout); setTimeout(check_load_timeout, window.cadesplugin_load_timeout);
} else { }
/** else
* Даже при слабом интернете плагин успевает загрузиться {
* менее чем за секунду, тк отдается из кэша
* */
setTimeout(check_load_timeout, 20000); setTimeout(check_load_timeout, 20000);
} }
set_constantValues(); set_constantValues();
cadesplugin.current_log_level = cadesplugin.LOG_LEVEL_ERROR; cadesplugin.current_log_level = cadesplugin.LOG_LEVEL_ERROR;
window.cadesplugin = cadesplugin; window.cadesplugin = cadesplugin;
check_plugin_working(); check_plugin_working();
}()); }());