mirror of
https://github.com/crypto-pro-web/crypto-pro-js.git
synced 2024-11-27 12:56:00 +03:00
commit
7256536037
8
dist/api/addAttachedSignature.d.ts
vendored
Normal file
8
dist/api/addAttachedSignature.d.ts
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Добавляет присоединенную подпись к подписанному сообщению по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param signedMessage - подписанное сообщение
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export declare const addAttachedSignature: (thumbprint: string, signedMessage: string | ArrayBuffer) => Promise<string>;
|
9
dist/api/addDetachedSignature.d.ts
vendored
Normal file
9
dist/api/addDetachedSignature.d.ts
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Добавляет отсоединенную подпись хеша к подписанному сообщению по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param signedMessage - подписанное сообщение
|
||||
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11-2012 256 бит
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export declare const addDetachedSignature: (thumbprint: string, signedMessage: string | ArrayBuffer, messageHash: string) => Promise<string>;
|
5
dist/api/index.d.ts
vendored
5
dist/api/index.d.ts
vendored
@ -1,10 +1,15 @@
|
||||
export * from './getCertificate';
|
||||
export * from './getUserCertificates';
|
||||
export * from './getAllUserCertificates';
|
||||
export * from './getSystemInfo';
|
||||
export * from './isValidSystemSetup';
|
||||
export * from './createSignature';
|
||||
export * from './createXMLSignature';
|
||||
export * from './createDetachedSignature';
|
||||
export * from './addDetachedSignature';
|
||||
export * from './createAttachedSignature';
|
||||
export * from './addAttachedSignature';
|
||||
export * from './createHash';
|
||||
export * from './certificate';
|
||||
export * from './getCspVersion';
|
||||
export * from './getPluginVersion';
|
||||
|
7
dist/crypto-pro.d.ts
vendored
7
dist/crypto-pro.d.ts
vendored
@ -1,7 +0,0 @@
|
||||
// Type definitions for crypto-pro 2.2.0
|
||||
// Project: crypto-pro
|
||||
// Definitions by: Vitalii Goma https://github.com/vgoma
|
||||
|
||||
export as namespace cryptoPro;
|
||||
|
||||
export * from './api';
|
5113
dist/crypto-pro.js
vendored
5113
dist/crypto-pro.js
vendored
File diff suppressed because it is too large
Load Diff
1
dist/crypto-pro.js.map
vendored
1
dist/crypto-pro.js.map
vendored
File diff suppressed because one or more lines are too long
9
dist/crypto-pro.min.js
vendored
9
dist/crypto-pro.min.js
vendored
File diff suppressed because one or more lines are too long
1
dist/crypto-pro.min.js.map
vendored
1
dist/crypto-pro.min.js.map
vendored
File diff suppressed because one or more lines are too long
@ -1,12 +1,15 @@
|
||||
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
|
||||
# For additional information regarding the format and rule options, please see:
|
||||
# https://github.com/browserslist/browserslist#queries
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
# You can see what browsers were selected by your queries by running:
|
||||
# npx browserslist
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
|
||||
esac
|
||||
|
||||
> 0.5%
|
||||
last 2 versions
|
||||
Firefox ESR
|
||||
not dead
|
||||
not IE 9-11 # For IE 9-11 support, remove 'not'.
|
||||
if [ -x "$basedir/node" ]; then
|
||||
"$basedir/node" "$basedir/node_modules/browserslist/cli.js" "$@"
|
||||
ret=$?
|
||||
else
|
||||
node "$basedir/node_modules/browserslist/cli.js" "$@"
|
||||
ret=$?
|
||||
fi
|
||||
exit $ret
|
||||
|
22
lib/api/certificate/certificate.d.ts
vendored
22
lib/api/certificate/certificate.d.ts
vendored
@ -1,22 +0,0 @@
|
||||
import { TagTranslation } from '../../helpers/_parseCertInfo';
|
||||
import { ExtendedKeysTranslations } from './getDecodedExtendedKeyUsage';
|
||||
export declare type CadesCertificate = any;
|
||||
export declare class Certificate {
|
||||
_cadesCertificate: CadesCertificate;
|
||||
name: string;
|
||||
issuerName: string;
|
||||
subjectName: string;
|
||||
thumbprint: string;
|
||||
validFrom: string;
|
||||
validTo: string;
|
||||
constructor(_cadesCertificate: CadesCertificate, name: string, issuerName: string, subjectName: string, thumbprint: string, validFrom: string, validTo: string);
|
||||
getOwnerInfo(): Promise<TagTranslation[]>;
|
||||
getIssuerInfo(): Promise<TagTranslation[]>;
|
||||
getExtendedKeyUsage(): Promise<string[]>;
|
||||
getDecodedExtendedKeyUsage(): Promise<ExtendedKeysTranslations>;
|
||||
getAlgorithm(): Promise<string>;
|
||||
getCadesProp(propName: any): Promise<any>;
|
||||
isValid(): Promise<boolean>;
|
||||
exportBase64(): Promise<string>;
|
||||
hasExtendedKeyUsage(oids: any): Promise<boolean>;
|
||||
}
|
6
lib/api/certificate/exportBase64.d.ts
vendored
6
lib/api/certificate/exportBase64.d.ts
vendored
@ -1,6 +0,0 @@
|
||||
/**
|
||||
* Экспортирует сертификат в формате base64
|
||||
*
|
||||
* @returns сертификат в формате base64
|
||||
*/
|
||||
export declare const exportBase64: () => Promise<string>;
|
11
lib/api/certificate/getAlgorithm.d.ts
vendored
11
lib/api/certificate/getAlgorithm.d.ts
vendored
@ -1,11 +0,0 @@
|
||||
interface AlgorithmInfo {
|
||||
algorithm: string;
|
||||
oid: string;
|
||||
}
|
||||
/**
|
||||
* Возвращает информацию об алгоритме сертификата
|
||||
*
|
||||
* @returns информацию об алгоритме и его OID'е
|
||||
*/
|
||||
export declare const getAlgorithm: () => Promise<AlgorithmInfo>;
|
||||
export {};
|
7
lib/api/certificate/getCadesProp.d.ts
vendored
7
lib/api/certificate/getCadesProp.d.ts
vendored
@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Возвращает указанное внутренее свойство у сертификата в формате Cades
|
||||
*
|
||||
* @param propName = наименование свойства
|
||||
* @returns значение запрошенного свойства
|
||||
*/
|
||||
export declare const getCadesProp: (propName: string) => Promise<any>;
|
@ -1,9 +0,0 @@
|
||||
export interface ExtendedKeysTranslations {
|
||||
[key: string]: string | null;
|
||||
}
|
||||
/**
|
||||
* Возвращает расшифрованные ОИД'ы сертификата
|
||||
*
|
||||
* @returns словарь расшифрованных ОИД'ов
|
||||
*/
|
||||
export declare const getDecodedExtendedKeyUsage: () => Promise<ExtendedKeysTranslations>;
|
6
lib/api/certificate/getExtendedKeyUsage.d.ts
vendored
6
lib/api/certificate/getExtendedKeyUsage.d.ts
vendored
@ -1,6 +0,0 @@
|
||||
/**
|
||||
* Возвращает ОИД'ы сертификата
|
||||
*
|
||||
* @returns список ОИД'ов
|
||||
*/
|
||||
export declare const getExtendedKeyUsage: () => Promise<string[]>;
|
10
lib/api/certificate/getInfo.d.ts
vendored
10
lib/api/certificate/getInfo.d.ts
vendored
@ -1,10 +0,0 @@
|
||||
import { TagsTranslations } from '../../constants/tags-translations';
|
||||
import { TagTranslation } from '../../helpers/_parseCertInfo';
|
||||
/**
|
||||
* Возвращает расшифрованную информацию о сертификате из указанного свойства по тэгам
|
||||
*
|
||||
* @param tags = словарь
|
||||
* @param entitiesPath = путь к разбираемой сущности
|
||||
* @returns расшифрованная информация по отдельным тэгам
|
||||
*/
|
||||
export declare const getInfo: (tags: TagsTranslations[], entitiesPath: string) => Promise<TagTranslation[]>;
|
7
lib/api/certificate/hasExtendedKeyUsage.d.ts
vendored
7
lib/api/certificate/hasExtendedKeyUsage.d.ts
vendored
@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Проверяет наличие ОИД'а (ОИД'ов) у сертификата
|
||||
*
|
||||
* @param oids - ОИД'ы для проверки
|
||||
* @returns флаг наличия ОИД'ов у сертификата
|
||||
*/
|
||||
export declare const hasExtendedKeyUsage: (oids: string | string[]) => Promise<boolean>;
|
1
lib/api/certificate/index.d.ts
vendored
1
lib/api/certificate/index.d.ts
vendored
@ -1 +0,0 @@
|
||||
export * from './certificate';
|
6
lib/api/certificate/isValid.d.ts
vendored
6
lib/api/certificate/isValid.d.ts
vendored
@ -1,6 +0,0 @@
|
||||
/**
|
||||
* Проверяет действительность сертификата
|
||||
*
|
||||
* @returns флаг валидности
|
||||
*/
|
||||
export declare const isValid: () => Promise<boolean>;
|
8
lib/api/createAttachedSignature.d.ts
vendored
8
lib/api/createAttachedSignature.d.ts
vendored
@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Создает присоединенную подпись сообщения по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param message - подписываемое сообщение
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export declare const createAttachedSignature: (thumbprint: string, unencryptedMessage: string | ArrayBuffer) => Promise<string>;
|
8
lib/api/createDetachedSignature.d.ts
vendored
8
lib/api/createDetachedSignature.d.ts
vendored
@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Создает отсоединенную подпись хеша по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11-2012 256 бит
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export declare const createDetachedSignature: (thumbprint: string, messageHash: string) => Promise<string>;
|
9
lib/api/createHash.d.ts
vendored
9
lib/api/createHash.d.ts
vendored
@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Создает хеш сообщения по ГОСТ Р 34.11-2012 256 бит
|
||||
* https://ru.wikipedia.org/wiki/%D0%A1%D1%82%D1%80%D0%B8%D0%B1%D0%BE%D0%B3_(%D1%85%D0%B5%D1%88-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D1%8F)
|
||||
*
|
||||
* @param unencryptedMessage - сообщение для хеширования
|
||||
*
|
||||
* @returns хеш
|
||||
*/
|
||||
export declare const createHash: (unencryptedMessage: string | ArrayBuffer) => Promise<string>;
|
9
lib/api/createSignature.d.ts
vendored
9
lib/api/createSignature.d.ts
vendored
@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Создает подпись base64 строки по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11
|
||||
* @param detachedSignature = true - тип подписи открепленная (true) / присоединенная (false)
|
||||
* @returns подпись
|
||||
*/
|
||||
export declare const createSignature: (thumbprint: string, messageHash: string, detachedSignature?: boolean) => Promise<string>;
|
8
lib/api/createXMLSignature.d.ts
vendored
8
lib/api/createXMLSignature.d.ts
vendored
@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Создает XML подпись для документа в формате XML
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param unencryptedMessage - подписываемое сообщение в формате XML
|
||||
* @returns подпись
|
||||
*/
|
||||
export declare const createXMLSignature: (thumbprint: string, unencryptedMessage: string) => Promise<string>;
|
8
lib/api/getCertificate.d.ts
vendored
8
lib/api/getCertificate.d.ts
vendored
@ -1,8 +0,0 @@
|
||||
import { Certificate } from './certificate';
|
||||
/**
|
||||
* Возвращает сертификат по отпечатку
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @returns сертификат
|
||||
*/
|
||||
export declare const getCertificate: (thumbprint: string) => Promise<Certificate>;
|
10
lib/api/getSystemInfo.d.ts
vendored
10
lib/api/getSystemInfo.d.ts
vendored
@ -1,10 +0,0 @@
|
||||
export interface SystemInfo {
|
||||
cadesVersion: string;
|
||||
cspVersion: string;
|
||||
}
|
||||
/**
|
||||
* Предоставляет информацию о системе
|
||||
*
|
||||
* @returns информацию о CSP и плагине
|
||||
*/
|
||||
export declare const getSystemInfo: () => Promise<SystemInfo>;
|
8
lib/api/getUserCertificates.d.ts
vendored
8
lib/api/getUserCertificates.d.ts
vendored
@ -1,8 +0,0 @@
|
||||
import { Certificate } from './certificate';
|
||||
/**
|
||||
* Возвращает список сертификатов, доступных пользователю в системе
|
||||
*
|
||||
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
|
||||
* @returns список сертификатов
|
||||
*/
|
||||
export declare const getUserCertificates: (resetCache?: boolean) => Promise<Certificate[]>;
|
10
lib/api/index.d.ts
vendored
10
lib/api/index.d.ts
vendored
@ -1,10 +0,0 @@
|
||||
export * from './getCertificate';
|
||||
export * from './getUserCertificates';
|
||||
export * from './getSystemInfo';
|
||||
export * from './isValidSystemSetup';
|
||||
export * from './createSignature';
|
||||
export * from './createXMLSignature';
|
||||
export * from './createDetachedSignature';
|
||||
export * from './createAttachedSignature';
|
||||
export * from './createHash';
|
||||
export * from './certificate';
|
6
lib/api/isValidSystemSetup.d.ts
vendored
6
lib/api/isValidSystemSetup.d.ts
vendored
@ -1,6 +0,0 @@
|
||||
/**
|
||||
* Проверяет корректность настроек ЭП на машине
|
||||
*
|
||||
* @returns флаг корректности настроек
|
||||
*/
|
||||
export declare const isValidSystemSetup: () => Promise<boolean>;
|
149
lib/constants/cades-constants.d.ts
vendored
149
lib/constants/cades-constants.d.ts
vendored
@ -1,149 +0,0 @@
|
||||
export declare const CADESCOM_ATTRIBUTE_OTHER = -1;
|
||||
export declare const CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2;
|
||||
export declare const CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1;
|
||||
export declare const CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
|
||||
export declare const CADESCOM_AllowNoOutstandingRequest = 1;
|
||||
export declare const CADESCOM_AllowNone = 0;
|
||||
export declare const CADESCOM_AllowUntrustedCertificate = 2;
|
||||
export declare const CADESCOM_AllowUntrustedRoot = 4;
|
||||
export declare const CADESCOM_BASE64_TO_BINARY = 1;
|
||||
export declare const CADESCOM_CADES_BES = 1;
|
||||
export declare const CADESCOM_CADES_DEFAULT = 0;
|
||||
export declare const CADESCOM_CADES_T = 5;
|
||||
export declare const CADESCOM_CADES_X_LONG_TYPE_1 = 93;
|
||||
export declare const CADESCOM_CONTAINER_STORE = 100;
|
||||
export declare const CADESCOM_CURRENT_USER_STORE = 2;
|
||||
export declare const CADESCOM_DISPLAY_DATA_ATTRIBUTE = 2;
|
||||
export declare const CADESCOM_DISPLAY_DATA_CONTENT = 1;
|
||||
export declare const CADESCOM_DISPLAY_DATA_NONE = 0;
|
||||
export declare const CADESCOM_ENCODE_ANY = -1;
|
||||
export declare const CADESCOM_ENCODE_BASE64 = 0;
|
||||
export declare const CADESCOM_ENCODE_BINARY = 1;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_3DES = 3;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_AES = 4;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_DES = 2;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89 = 25;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_RC2 = 0;
|
||||
export declare const CADESCOM_ENCRYPTION_ALGORITHM_RC4 = 1;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411 = 100;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256 = 101;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256_HMAC = 111;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512 = 102;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512_HMAC = 112;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_CP_GOST_3411_HMAC = 110;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_MD2 = 1;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_MD4 = 2;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_MD5 = 3;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_SHA1 = 0;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_SHA_256 = 4;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_SHA_384 = 5;
|
||||
export declare const CADESCOM_HASH_ALGORITHM_SHA_512 = 6;
|
||||
export declare const CADESCOM_LOCAL_MACHINE_STORE = 1;
|
||||
export declare const CADESCOM_PKCS7_TYPE = 65535;
|
||||
export declare const CADESCOM_STRING_TO_UCS2LE = 0;
|
||||
export declare const CADESCOM_SkipInstallToStore = 268435456;
|
||||
export declare const CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED = 0;
|
||||
export declare const CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING = 1;
|
||||
export declare const CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE = 2;
|
||||
export declare const CAPICOM_ACTIVE_DIRECTORY_USER_STORE = 3;
|
||||
export declare const CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION = 2;
|
||||
export declare const CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME = 1;
|
||||
export declare const CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY = 7;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY = 8;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_EXTENSION = 5;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_ROOT_NAME = 3;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME = 4;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10;
|
||||
export declare const CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
|
||||
export declare const CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT = 0;
|
||||
export declare const CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY = 2;
|
||||
export declare const CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN = 1;
|
||||
export declare const CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME = 1;
|
||||
export declare const CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0;
|
||||
export declare const CAPICOM_CURRENT_USER_STORE = 2;
|
||||
export declare const CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 128;
|
||||
export declare const CAPICOM_EKU_CLIENT_AUTH = 2;
|
||||
export declare const CAPICOM_EKU_OTHER = 0;
|
||||
export declare const CAPICOM_EKU_SMARTCARD_LOGON = 5;
|
||||
export declare const CAPICOM_LOCAL_MACHINE_STORE = 1;
|
||||
export declare const CAPICOM_MEMORY_STORE = 0;
|
||||
export declare const CAPICOM_MY_STORE = "My";
|
||||
export declare const CAPICOM_OID_KEY_USAGE_EXTENSION = 10;
|
||||
export declare const CAPICOM_OID_OTHER = 0;
|
||||
export declare const CAPICOM_PROPID_ACCESS_STATE = 14;
|
||||
export declare const CAPICOM_PROPID_ARCHIVED = 19;
|
||||
export declare const CAPICOM_PROPID_ARCHIVED_KEY_HASH = 65;
|
||||
export declare const CAPICOM_PROPID_AUTO_ENROLL = 21;
|
||||
export declare const CAPICOM_PROPID_CROSS_CERT_DIST_POINTS = 23;
|
||||
export declare const CAPICOM_PROPID_CTL_USAGE = 9;
|
||||
export declare const CAPICOM_PROPID_DATE_STAMP = 27;
|
||||
export declare const CAPICOM_PROPID_DESCRIPTION = 13;
|
||||
export declare const CAPICOM_PROPID_EFS = 17;
|
||||
export declare const CAPICOM_PROPID_ENHKEY_USAGE = 9;
|
||||
export declare const CAPICOM_PROPID_ENROLLMENT = 26;
|
||||
export declare const CAPICOM_PROPID_EXTENDED_ERROR_INFO = 30;
|
||||
export declare const CAPICOM_PROPID_FIRST_RESERVED = 66;
|
||||
export declare const CAPICOM_PROPID_FIRST_USER = 32768;
|
||||
export declare const CAPICOM_PROPID_FORTEZZA_DATA = 18;
|
||||
export declare const CAPICOM_PROPID_FRIENDLY_NAME = 11;
|
||||
export declare const CAPICOM_PROPID_HASH_PROP = 3;
|
||||
export declare const CAPICOM_PROPID_IE30_RESERVED = 7;
|
||||
export declare const CAPICOM_PROPID_ISSUER_PUBLIC_KEY_MD5_HASH = 24;
|
||||
export declare const CAPICOM_PROPID_ISSUER_SERIAL_NUMBER_MD5_HASH = 28;
|
||||
export declare const CAPICOM_PROPID_KEY_CONTEXT = 5;
|
||||
export declare const CAPICOM_PROPID_KEY_IDENTIFIER = 20;
|
||||
export declare const CAPICOM_PROPID_KEY_PROV_HANDLE = 1;
|
||||
export declare const CAPICOM_PROPID_KEY_PROV_INFO = 2;
|
||||
export declare const CAPICOM_PROPID_KEY_SPEC = 6;
|
||||
export declare const CAPICOM_PROPID_LAST_RESERVED = 32767;
|
||||
export declare const CAPICOM_PROPID_LAST_USER = 65535;
|
||||
export declare const CAPICOM_PROPID_MD5_HASH = 4;
|
||||
export declare const CAPICOM_PROPID_NEXT_UPDATE_LOCATION = 10;
|
||||
export declare const CAPICOM_PROPID_PUBKEY_ALG_PARA = 22;
|
||||
export declare const CAPICOM_PROPID_PUBKEY_HASH_RESERVED = 8;
|
||||
export declare const CAPICOM_PROPID_PVK_FILE = 12;
|
||||
export declare const CAPICOM_PROPID_RENEWAL = 64;
|
||||
export declare const CAPICOM_PROPID_SHA1_HASH = 3;
|
||||
export declare const CAPICOM_PROPID_SIGNATURE_HASH = 15;
|
||||
export declare const CAPICOM_PROPID_SMART_CARD_DATA = 16;
|
||||
export declare const CAPICOM_PROPID_SUBJECT_NAME_MD5_HASH = 29;
|
||||
export declare const CAPICOM_PROPID_SUBJECT_PUBLIC_KEY_MD5_HASH = 25;
|
||||
export declare const CAPICOM_PROPID_UNKNOWN = 0;
|
||||
export declare const CAPICOM_SMART_CARD_USER_STORE = 4;
|
||||
export declare const CAPICOM_STORE_OPEN_EXISTING_ONLY = 128;
|
||||
export declare const CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED = 256;
|
||||
export declare const CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2;
|
||||
export declare const CAPICOM_STORE_OPEN_READ_ONLY = 0;
|
||||
export declare const CAPICOM_STORE_OPEN_READ_WRITE = 1;
|
||||
export declare const CHECK_NONE = 0;
|
||||
export declare const CHECK_OFFLINE_REVOCATION_STATUS = 16;
|
||||
export declare const CHECK_ONLINE_REVOCATION_STATUS = 8;
|
||||
export declare const CHECK_SIGNATURE_VALIDITY = 4;
|
||||
export declare const CHECK_TIME_VALIDITY = 2;
|
||||
export declare const CHECK_TRUSTED_ROOT = 1;
|
||||
export declare const LOG_LEVEL_DEBUG = 4;
|
||||
export declare const LOG_LEVEL_ERROR = 1;
|
||||
export declare const LOG_LEVEL_INFO = 2;
|
||||
export declare const TRUST_CTL_IS_NOT_SIGNATURE_VALID = 262144;
|
||||
export declare const TRUST_CTL_IS_NOT_TIME_VALID = 131072;
|
||||
export declare const TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 524288;
|
||||
export declare const TRUST_IS_CYCLIC = 128;
|
||||
export declare const TRUST_IS_NOT_SIGNATURE_VALID = 8;
|
||||
export declare const TRUST_IS_NOT_TIME_NESTED = 2;
|
||||
export declare const TRUST_IS_NOT_TIME_VALID = 1;
|
||||
export declare const TRUST_IS_NOT_VALID_FOR_USAGE = 16;
|
||||
export declare const TRUST_IS_PARTIAL_CHAIN = 65536;
|
||||
export declare const TRUST_IS_REVOKED = 4;
|
||||
export declare const TRUST_IS_UNTRUSTED_ROOT = 32;
|
||||
export declare const TRUST_REVOCATION_STATUS_UNKNOWN = 64;
|
||||
export declare const XmlDsigGost3410Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411";
|
||||
export declare const XmlDsigGost3410UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
|
||||
export declare const XmlDsigGost3411Url = "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411";
|
||||
export declare const XmlDsigGost3411UrlObsolete = "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
|
4
lib/constants/index.d.ts
vendored
4
lib/constants/index.d.ts
vendored
@ -1,4 +0,0 @@
|
||||
export * from './cades-constants';
|
||||
export * from './issuer-tags-translations';
|
||||
export * from './oids-dictionary';
|
||||
export * from './subject-tags-translations';
|
2
lib/constants/issuer-tags-translations.d.ts
vendored
2
lib/constants/issuer-tags-translations.d.ts
vendored
@ -1,2 +0,0 @@
|
||||
import { TagsTranslations } from './tags-translations';
|
||||
export declare const ISSUER_TAGS_TRANSLATIONS: TagsTranslations[];
|
44
lib/constants/oids-dictionary.d.ts
vendored
44
lib/constants/oids-dictionary.d.ts
vendored
@ -1,44 +0,0 @@
|
||||
export declare const OIDS_DICTIONARY: {
|
||||
'1.2.643.2.2.34.6': string;
|
||||
'1.2.643.2.39.1.1': string;
|
||||
'1.2.643.3.131.1.1': string;
|
||||
'1.2.643.3.141.1.1': string;
|
||||
'1.2.643.3.141.1.2': string;
|
||||
'1.2.643.3.2.100.65.13.11': string;
|
||||
'1.2.643.3.8.100.1': string;
|
||||
'1.2.643.3.8.100.1.1': string;
|
||||
'1.2.643.3.8.100.1.10': string;
|
||||
'1.2.643.3.8.100.1.11': string;
|
||||
'1.2.643.3.8.100.1.12': string;
|
||||
'1.2.643.3.8.100.1.13': string;
|
||||
'1.2.643.3.8.100.1.14': string;
|
||||
'1.2.643.3.8.100.1.2': string;
|
||||
'1.2.643.3.8.100.1.3': string;
|
||||
'1.2.643.3.8.100.1.4': string;
|
||||
'1.2.643.3.8.100.1.5': string;
|
||||
'1.2.643.3.8.100.1.6': string;
|
||||
'1.2.643.3.8.100.1.7': string;
|
||||
'1.2.643.3.8.100.1.8': string;
|
||||
'1.2.643.3.8.100.1.9': string;
|
||||
'1.2.643.5.1.24.2.1.3': string;
|
||||
'1.2.643.5.1.24.2.1.3.1': string;
|
||||
'1.2.643.5.1.24.2.2.2': string;
|
||||
'1.2.643.5.1.24.2.2.3': string;
|
||||
'1.2.643.6.2.1.7.1': string;
|
||||
'1.2.643.6.2.1.7.2': string;
|
||||
'1.2.643.6.3': string;
|
||||
'1.2.643.6.3.1.1': string;
|
||||
'1.2.643.6.3.1.2.1': string;
|
||||
'1.2.643.6.3.1.2.2': string;
|
||||
'1.2.643.6.3.1.2.3': string;
|
||||
'1.2.643.6.3.1.3.1': string;
|
||||
'1.2.643.6.3.1.4.1': string;
|
||||
'1.2.643.6.3.1.4.2': string;
|
||||
'1.2.643.6.3.1.4.3': string;
|
||||
'1.2.840.113549.1.9.2': string;
|
||||
'1.3.6.1.4.1.24138.1.1.8.1': string;
|
||||
'1.3.6.1.4.1.29919.21': string;
|
||||
'1.3.6.1.5.5.7.3.2': string;
|
||||
'1.3.6.1.5.5.7.3.4': string;
|
||||
'1.3.643.3.8.100.15': string;
|
||||
};
|
2
lib/constants/subject-tags-translations.d.ts
vendored
2
lib/constants/subject-tags-translations.d.ts
vendored
@ -1,2 +0,0 @@
|
||||
import { TagsTranslations } from './tags-translations';
|
||||
export declare const SUBJECT_TAGS_TRANSLATIONS: TagsTranslations[];
|
4
lib/constants/tags-translations.d.ts
vendored
4
lib/constants/tags-translations.d.ts
vendored
@ -1,4 +0,0 @@
|
||||
export interface TagsTranslations {
|
||||
possibleNames: string[];
|
||||
translation: string;
|
||||
}
|
5
lib/crypto-pro.d.ts
vendored
5
lib/crypto-pro.d.ts
vendored
@ -1,5 +0,0 @@
|
||||
// Type definitions for crypto-pro 2.2.0
|
||||
// Project: crypto-pro
|
||||
// Definitions by: Vitalii Goma https://github.com/vgoma
|
||||
|
||||
export * from './api';
|
4705
lib/crypto-pro.js
4705
lib/crypto-pro.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
3
lib/helpers/_afterPluginsLoaded.d.ts
vendored
3
lib/helpers/_afterPluginsLoaded.d.ts
vendored
@ -1,3 +0,0 @@
|
||||
declare type Unpromisify<T> = T extends Promise<infer R> ? R : T;
|
||||
export declare const _afterPluginsLoaded: <T extends (...args: any[]) => any>(fn: T) => (...args: Parameters<T>) => Promise<Unpromisify<ReturnType<T>>>;
|
||||
export {};
|
1
lib/helpers/_extractCommonName.d.ts
vendored
1
lib/helpers/_extractCommonName.d.ts
vendored
@ -1 +0,0 @@
|
||||
export declare const _extractCommonName: (subjectName: string) => string;
|
@ -1 +0,0 @@
|
||||
export declare const _extractMeaningfulErrorMessage: (error: Error) => string;
|
3
lib/helpers/_generateCadesFn.d.ts
vendored
3
lib/helpers/_generateCadesFn.d.ts
vendored
@ -1,3 +0,0 @@
|
||||
export declare const __cadesAsyncToken__: {};
|
||||
export declare const __createCadesPluginObject__: (...args: any[]) => any;
|
||||
export declare const _generateCadesFn: (callback: Function) => string;
|
7
lib/helpers/_getCadesCert.d.ts
vendored
7
lib/helpers/_getCadesCert.d.ts
vendored
@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Возвращает сертификат в формате Cades по отпечатку
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @returns сертификат в формате Cades
|
||||
*/
|
||||
export declare const _getCadesCert: (thumbprint: string) => Promise<any>;
|
7
lib/helpers/_getDateObj.d.ts
vendored
7
lib/helpers/_getDateObj.d.ts
vendored
@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Возвращает объект даты, совместимый с Cades plugin'ом, зависящий от браузера.
|
||||
*
|
||||
* В IE необходимо использовать специфичный формат "VT_DATE"
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Microsoft_Extensions/Date.getVarDate
|
||||
*/
|
||||
export declare const _getDateObj: (dateObj: any) => Date;
|
1
lib/helpers/_isSupportedCSPVersion.d.ts
vendored
1
lib/helpers/_isSupportedCSPVersion.d.ts
vendored
@ -1 +0,0 @@
|
||||
export declare const _isSupportedCSPVersion: (version: string) => boolean;
|
1
lib/helpers/_isSupportedCadesVersion.d.ts
vendored
1
lib/helpers/_isSupportedCadesVersion.d.ts
vendored
@ -1 +0,0 @@
|
||||
export declare const _isSupportedCadesVersion: (version: string) => boolean;
|
14
lib/helpers/_parseCertInfo.d.ts
vendored
14
lib/helpers/_parseCertInfo.d.ts
vendored
@ -1,14 +0,0 @@
|
||||
import { TagsTranslations } from '../constants/tags-translations';
|
||||
export interface TagTranslation {
|
||||
description: string;
|
||||
title: string;
|
||||
isTranslated: boolean;
|
||||
}
|
||||
/**
|
||||
* Парсит информацию из строки с информацией о сертификате
|
||||
*
|
||||
* @param tagsTranslations - словарь с расшифровками тэгов
|
||||
* @param rawInfo - данные для парсинга
|
||||
* @returns расшифрованная информация по отдельным тэгам
|
||||
*/
|
||||
export declare const _parseCertInfo: (tagsTranslations: TagsTranslations[], rawInfo: string) => TagTranslation[];
|
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "crypto-pro",
|
||||
"version": "2.2.0",
|
||||
"name": "crypto-pro-custom",
|
||||
"version": "2.2.1",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
|
36
package.json
36
package.json
@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "crypto-pro",
|
||||
"version": "2.2.0",
|
||||
"description": "API для взаимодействия с КриптоПро",
|
||||
"main": "./lib/crypto-pro.js",
|
||||
"types": "./lib/crypto-pro.d.ts",
|
||||
"name": "crypto-pro-custom",
|
||||
"version": "2.2.2",
|
||||
"description": "Кастомизированный API для взаимодействия с КриптоПро",
|
||||
"main": "./lib/crypto-pro-custom.js",
|
||||
"types": "./lib/crypto-pro-custom.d.ts",
|
||||
"files": [
|
||||
"lib/**/*",
|
||||
"dist/**/*",
|
||||
@ -20,29 +20,35 @@
|
||||
"build:definition-header:esm": "cross-env TS_CONFIG=tsconfig-esm.json node definition-header.js",
|
||||
"build:esm": "npm run build:uncompressed:esm && npm run build:definition-header:esm",
|
||||
"build": "npm run clean && npm run build:es5 && npm run build:esm",
|
||||
"pack:clean": "cross-env-shell rimraf $npm_package_name-$npm_package_version.tgz",
|
||||
"pack:uncompress": "cross-env-shell tar xopf $npm_package_name-$npm_package_version.tgz",
|
||||
"pack:clean": "cross-env rimraf %npm_package_name%-%npm_package_version%.tgz",
|
||||
"pack:uncompress": "cross-env tar xopf %npm_package_name%-%npm_package_version%.tgz",
|
||||
"test": "jest --coverage && coveralls < coverage/lcov.info",
|
||||
"lint": "eslint --config .eslintrc.js './src/**/*'",
|
||||
"lint:fix": "eslint --fix --config .eslintrc.js './src/**/*'",
|
||||
"lint": "eslint --config .eslintrc.js --ext .ts --ext .js src",
|
||||
"lint:fix": "eslint --fix --config .eslintrc.js --ext .ts --ext .js src",
|
||||
"examples-update": "npm run examples-update:script-tag && npm run examples-update:angular && npm run examples-update:react",
|
||||
"examples-update:script-tag": "npm --prefix ./examples/script-tag r crypto-pro && npm --prefix ./examples/script-tag i crypto-pro",
|
||||
"examples-update:angular": "npm --prefix ./examples/angular r crypto-pro && npm --prefix ./examples/angular i crypto-pro",
|
||||
"examples-update:react": "npm --prefix ./examples/react r crypto-pro && npm --prefix ./examples/react i crypto-pro",
|
||||
"prepack": "npm run build",
|
||||
"postpack": "npm run pack:uncompress && npm run pack:clean",
|
||||
"prepublishOnly": "npm run lint && jest && npm run build",
|
||||
"postpublish": "npm run examples-update"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/vgoma/crypto-pro"
|
||||
"url": "https://github.com/kernusr/crypto-pro"
|
||||
},
|
||||
"author": {
|
||||
"name": "Vitalii Goma",
|
||||
"email": "vgoma@yandex.ru",
|
||||
"url": "https://github.com/vgoma"
|
||||
"name": "Artem Vasilev",
|
||||
"email": "kern.usr@gmail.com",
|
||||
"url": "https://github.com/kernusr"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Vitalii Goma",
|
||||
"email": "vgoma@yandex.ru",
|
||||
"url": "https://github.com/vgoma"
|
||||
}
|
||||
],
|
||||
"keywords": [
|
||||
"crypto",
|
||||
"cryptopro",
|
||||
@ -59,7 +65,7 @@
|
||||
"@typescript-eslint/eslint-plugin": "2.25.0",
|
||||
"@typescript-eslint/parser": "2.25.0",
|
||||
"coveralls": "3.0.11",
|
||||
"cross-env": "7.0.2",
|
||||
"cross-env": "^7.0.2",
|
||||
"eslint": "6.8.0",
|
||||
"eslint-config-prettier": "6.10.1",
|
||||
"eslint-plugin-prettier": "3.1.2",
|
||||
|
89
src/api/addAttachedSignature.test.ts
Normal file
89
src/api/addAttachedSignature.test.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import 'cadesplugin';
|
||||
import { rawCertificates, parsedCertificates } from '../__mocks__/certificates';
|
||||
import { createAttachedSignature } from './createAttachedSignature';
|
||||
import { _getCadesCert } from '../helpers/_getCadesCert';
|
||||
import { addAttachedSignature } from './addAttachedSignature';
|
||||
|
||||
const [rawCertificateMock] = rawCertificates;
|
||||
const [parsedCertificateMock] = parsedCertificates;
|
||||
|
||||
jest.mock('../helpers/_getCadesCert', () => ({ _getCadesCert: jest.fn(() => rawCertificateMock) }));
|
||||
|
||||
beforeEach(() => {
|
||||
(_getCadesCert as jest.Mock).mockClear();
|
||||
});
|
||||
|
||||
const executionSteps = [
|
||||
Symbol('step 0'),
|
||||
Symbol('step 1'),
|
||||
Symbol('step 2'),
|
||||
Symbol('step 3'),
|
||||
Symbol('step 4'),
|
||||
Symbol('step 5'),
|
||||
];
|
||||
|
||||
const executionFlow = {
|
||||
[executionSteps[0]]: {
|
||||
propset_Name: jest.fn(),
|
||||
propset_Value: jest.fn(),
|
||||
},
|
||||
[executionSteps[1]]: {
|
||||
propset_ContentEncoding: jest.fn(),
|
||||
propset_Content: jest.fn(),
|
||||
SignCades: jest.fn(() => executionSteps[4]),
|
||||
VerifyCades: jest.fn(),
|
||||
CoSignCades: jest.fn(() => executionSteps[5]),
|
||||
},
|
||||
[executionSteps[2]]: {
|
||||
propset_Certificate: jest.fn(),
|
||||
AuthenticatedAttributes2: executionSteps[3],
|
||||
propset_Options: jest.fn(),
|
||||
},
|
||||
[executionSteps[3]]: {
|
||||
Add: jest.fn(),
|
||||
},
|
||||
[executionSteps[4]]: 'signature',
|
||||
[executionSteps[5]]: 'newSignature',
|
||||
};
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation((object) => {
|
||||
switch (object) {
|
||||
case 'CADESCOM.CPAttribute':
|
||||
return executionSteps[0];
|
||||
case 'CAdESCOM.CadesSignedData':
|
||||
return executionSteps[1];
|
||||
case 'CAdESCOM.CPSigner':
|
||||
return executionSteps[2];
|
||||
}
|
||||
});
|
||||
|
||||
describe('addAttachedSignature', () => {
|
||||
test('uses Buffer to encrypt the message', async () => {
|
||||
const originalBufferFrom = global.Buffer.from;
|
||||
|
||||
(global.Buffer.from as jest.Mock) = jest.fn(() => ({
|
||||
toString: jest.fn(),
|
||||
}));
|
||||
|
||||
await createAttachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
await addAttachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
|
||||
expect(global.Buffer.from).toHaveBeenCalledTimes(2);
|
||||
|
||||
global.Buffer.from = originalBufferFrom;
|
||||
});
|
||||
|
||||
test('uses specified certificate', async () => {
|
||||
await addAttachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
|
||||
expect(_getCadesCert).toHaveBeenCalledWith(parsedCertificateMock.thumbprint);
|
||||
});
|
||||
|
||||
test('returns new signature', async () => {
|
||||
await createAttachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
const signature = await addAttachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
|
||||
expect(signature).toEqual('newSignature');
|
||||
});
|
||||
});
|
87
src/api/addAttachedSignature.ts
Normal file
87
src/api/addAttachedSignature.ts
Normal file
@ -0,0 +1,87 @@
|
||||
import { CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME } from '../constants';
|
||||
import { _afterPluginsLoaded } from '../helpers/_afterPluginsLoaded';
|
||||
import { _extractMeaningfulErrorMessage } from '../helpers/_extractMeaningfulErrorMessage';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from '../helpers/_generateCadesFn';
|
||||
import { _getCadesCert } from '../helpers/_getCadesCert';
|
||||
import { _getDateObj } from '../helpers/_getDateObj';
|
||||
|
||||
/**
|
||||
* Добавляет присоединенную подпись к подписанному сообщению по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param signedMessage - подписанное сообщение
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export const addAttachedSignature = _afterPluginsLoaded(
|
||||
async (thumbprint: string, signedMessage: string | ArrayBuffer): Promise<string> => {
|
||||
const { cadesplugin } = window;
|
||||
const cadesCertificate = await _getCadesCert(thumbprint);
|
||||
|
||||
return eval(
|
||||
_generateCadesFn(function addAttachedSignature(): string {
|
||||
let cadesAttrs;
|
||||
let cadesSignedData;
|
||||
let cadesSigner;
|
||||
|
||||
try {
|
||||
cadesAttrs = __cadesAsyncToken__ + __createCadesPluginObject__('CADESCOM.CPAttribute');
|
||||
cadesSignedData = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.CadesSignedData');
|
||||
cadesSigner = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.CPSigner');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при инициализации подписи');
|
||||
}
|
||||
|
||||
const currentTime = _getDateObj(new Date());
|
||||
|
||||
try {
|
||||
void (__cadesAsyncToken__ + cadesAttrs.propset_Name(CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME));
|
||||
void (__cadesAsyncToken__ + cadesAttrs.propset_Value(currentTime));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при установке времени подписи');
|
||||
}
|
||||
|
||||
let messageBase64;
|
||||
|
||||
try {
|
||||
messageBase64 = Buffer.from(signedMessage).toString('base64');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error('Ошибка при преобразовании сообщения в Base64');
|
||||
}
|
||||
|
||||
let cadesAuthAttrs;
|
||||
|
||||
try {
|
||||
void (__cadesAsyncToken__ + cadesSigner.propset_Certificate(cadesCertificate));
|
||||
cadesAuthAttrs = __cadesAsyncToken__ + cadesSigner.AuthenticatedAttributes2;
|
||||
void (__cadesAsyncToken__ + cadesAuthAttrs.Add(cadesAttrs));
|
||||
void (__cadesAsyncToken__ + cadesSignedData.propset_ContentEncoding(cadesplugin.CADESCOM_BASE64_TO_BINARY));
|
||||
void (__cadesAsyncToken__ + cadesSignedData.propset_Content(messageBase64));
|
||||
void (__cadesAsyncToken__ + cadesSigner.propset_Options(cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при указании данных для подписи');
|
||||
}
|
||||
|
||||
let signature: string;
|
||||
|
||||
try {
|
||||
void (__cadesAsyncToken__ + cadesSignedData.VerifyCades(signedMessage, cadesplugin.CADESCOM_PKCS7_TYPE));
|
||||
signature = __cadesAsyncToken__ + cadesSignedData.CoSignCades(cadesSigner, cadesplugin.CADESCOM_PKCS7_TYPE);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при подписании данных');
|
||||
}
|
||||
|
||||
return signature;
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
112
src/api/addDetachedSignature.test.ts
Normal file
112
src/api/addDetachedSignature.test.ts
Normal file
@ -0,0 +1,112 @@
|
||||
import 'cadesplugin';
|
||||
import { rawCertificates, parsedCertificates } from '../__mocks__/certificates';
|
||||
import { createDetachedSignature } from './createDetachedSignature';
|
||||
import { _getCadesCert } from '../helpers/_getCadesCert';
|
||||
import { addDetachedSignature } from './addDetachedSignature';
|
||||
import { createHash } from './createHash';
|
||||
|
||||
const [rawCertificateMock] = rawCertificates;
|
||||
const [parsedCertificateMock] = parsedCertificates;
|
||||
|
||||
jest.mock('../helpers/_getCadesCert', () => ({ _getCadesCert: jest.fn(() => rawCertificateMock) }));
|
||||
|
||||
beforeEach(() => {
|
||||
(_getCadesCert as jest.Mock).mockClear();
|
||||
});
|
||||
|
||||
const executionSteps = [
|
||||
Symbol('step 0'),
|
||||
Symbol('step 1'),
|
||||
Symbol('step 2'),
|
||||
Symbol('step 3'),
|
||||
Symbol('step 4'),
|
||||
Symbol('step 5'),
|
||||
Symbol('step 6'),
|
||||
Symbol('step 7'),
|
||||
];
|
||||
|
||||
const executionFlow = {
|
||||
[executionSteps[0]]: {
|
||||
propset_Name: jest.fn(),
|
||||
propset_Value: jest.fn(),
|
||||
},
|
||||
[executionSteps[1]]: {
|
||||
propset_ContentEncoding: jest.fn(),
|
||||
propset_Content: jest.fn(),
|
||||
SignHash: jest.fn(() => executionSteps[4]),
|
||||
VerifyHash: jest.fn(),
|
||||
CoSignHash: jest.fn(() => executionSteps[6]),
|
||||
},
|
||||
[executionSteps[2]]: {
|
||||
propset_Certificate: jest.fn(),
|
||||
AuthenticatedAttributes2: executionSteps[3],
|
||||
propset_Options: jest.fn(),
|
||||
},
|
||||
[executionSteps[3]]: {
|
||||
Add: jest.fn(),
|
||||
},
|
||||
[executionSteps[4]]: 'signature',
|
||||
[executionSteps[5]]: {
|
||||
propset_Algorithm: jest.fn(),
|
||||
propset_DataEncoding: jest.fn(),
|
||||
Hash: jest.fn(),
|
||||
Value: executionSteps[7],
|
||||
SetHashValue: jest.fn(),
|
||||
},
|
||||
[executionSteps[6]]: 'newSignature',
|
||||
[executionSteps[7]]: 'hash',
|
||||
};
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation((object) => {
|
||||
switch (object) {
|
||||
case 'CADESCOM.CPAttribute':
|
||||
return executionSteps[0];
|
||||
case 'CAdESCOM.CadesSignedData':
|
||||
return executionSteps[1];
|
||||
case 'CAdESCOM.CPSigner':
|
||||
return executionSteps[2];
|
||||
case 'CAdESCOM.HashedData':
|
||||
return executionSteps[5];
|
||||
}
|
||||
});
|
||||
|
||||
describe('addDetachedSignature', () => {
|
||||
test('uses specified certificate', async () => {
|
||||
const originalBufferFrom = global.Buffer.from;
|
||||
|
||||
(global.Buffer.from as jest.Mock) = jest.fn(() => ({
|
||||
toString: jest.fn(),
|
||||
}));
|
||||
|
||||
const signature = await createDetachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
const signatureHash = await createHash(signature);
|
||||
await addDetachedSignature(parsedCertificateMock.thumbprint, signature, signatureHash);
|
||||
|
||||
expect(_getCadesCert).toHaveBeenCalledWith(parsedCertificateMock.thumbprint);
|
||||
|
||||
expect(global.Buffer.from).toHaveBeenCalledTimes(1);
|
||||
|
||||
global.Buffer.from = originalBufferFrom;
|
||||
});
|
||||
|
||||
test('returns new signature', async () => {
|
||||
const originalBufferFrom = global.Buffer.from;
|
||||
|
||||
(global.Buffer.from as jest.Mock) = jest.fn(() => ({
|
||||
toString: jest.fn(),
|
||||
}));
|
||||
|
||||
let signature = await createDetachedSignature(parsedCertificateMock.thumbprint, 'message');
|
||||
const signatureHash = await createHash(signature);
|
||||
signature = await addDetachedSignature(parsedCertificateMock.thumbprint, signature, signatureHash);
|
||||
|
||||
expect(_getCadesCert).toHaveBeenCalledWith(parsedCertificateMock.thumbprint);
|
||||
|
||||
expect(global.Buffer.from).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(signature).toEqual('newSignature');
|
||||
|
||||
global.Buffer.from = originalBufferFrom;
|
||||
});
|
||||
});
|
95
src/api/addDetachedSignature.ts
Normal file
95
src/api/addDetachedSignature.ts
Normal file
@ -0,0 +1,95 @@
|
||||
import { CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME } from '../constants';
|
||||
import { _afterPluginsLoaded } from '../helpers/_afterPluginsLoaded';
|
||||
import { _extractMeaningfulErrorMessage } from '../helpers/_extractMeaningfulErrorMessage';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from '../helpers/_generateCadesFn';
|
||||
import { _getCadesCert } from '../helpers/_getCadesCert';
|
||||
import { _getDateObj } from '../helpers/_getDateObj';
|
||||
|
||||
/**
|
||||
* Добавляет отсоединенную подпись хеша к подписанному сообщению по отпечатку сертификата
|
||||
*
|
||||
* @param thumbprint - отпечаток сертификата
|
||||
* @param signedMessage - подписанное сообщение
|
||||
* @param messageHash - хеш подписываемого сообщения, сгенерированный по ГОСТ Р 34.11-2012 256 бит
|
||||
* @returns подпись в формате PKCS#7
|
||||
*/
|
||||
export const addDetachedSignature = _afterPluginsLoaded(
|
||||
async (thumbprint: string, signedMessage: string | ArrayBuffer, messageHash: string): Promise<string> => {
|
||||
const { cadesplugin } = window;
|
||||
const cadesCertificate = await _getCadesCert(thumbprint);
|
||||
|
||||
return eval(
|
||||
_generateCadesFn(function addDetachedSignature(): string {
|
||||
let cadesAttrs;
|
||||
let cadesHashedData;
|
||||
let cadesSignedData;
|
||||
let cadesSigner;
|
||||
|
||||
try {
|
||||
cadesAttrs = __cadesAsyncToken__ + __createCadesPluginObject__('CADESCOM.CPAttribute');
|
||||
cadesHashedData = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.HashedData');
|
||||
cadesSignedData = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.CadesSignedData');
|
||||
cadesSigner = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.CPSigner');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при инициализации подписи');
|
||||
}
|
||||
|
||||
const currentTime = _getDateObj(new Date());
|
||||
|
||||
try {
|
||||
void (__cadesAsyncToken__ + cadesAttrs.propset_Name(CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME));
|
||||
void (__cadesAsyncToken__ + cadesAttrs.propset_Value(currentTime));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при установке времени подписи');
|
||||
}
|
||||
|
||||
let cadesAuthAttrs;
|
||||
|
||||
try {
|
||||
void (__cadesAsyncToken__ + cadesSigner.propset_Certificate(cadesCertificate));
|
||||
cadesAuthAttrs = __cadesAsyncToken__ + cadesSigner.AuthenticatedAttributes2;
|
||||
void (__cadesAsyncToken__ + cadesAuthAttrs.Add(cadesAttrs));
|
||||
void (__cadesAsyncToken__ + cadesSigner.propset_Options(cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при установке сертификата');
|
||||
}
|
||||
|
||||
try {
|
||||
void (
|
||||
__cadesAsyncToken__ +
|
||||
cadesHashedData.propset_Algorithm(cadesplugin.CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256)
|
||||
);
|
||||
void (__cadesAsyncToken__ + cadesHashedData.SetHashValue(messageHash));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при установке хеша');
|
||||
}
|
||||
|
||||
let signature: string;
|
||||
|
||||
try {
|
||||
void (
|
||||
__cadesAsyncToken__ +
|
||||
cadesSignedData.VerifyHash(cadesHashedData, signedMessage, cadesplugin.CADESCOM_PKCS7_TYPE)
|
||||
);
|
||||
signature =
|
||||
__cadesAsyncToken__ +
|
||||
cadesSignedData.CoSignHash(cadesHashedData, cadesSigner, cadesplugin.CADESCOM_PKCS7_TYPE);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при подписании данных');
|
||||
}
|
||||
|
||||
return signature;
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
60
src/api/getAllUserCertificates.test.ts
Normal file
60
src/api/getAllUserCertificates.test.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import 'cadesplugin';
|
||||
import { rawCertificates, parsedCertificates } from '../__mocks__/certificates';
|
||||
import { getAllUserCertificates } from './getAllUserCertificates';
|
||||
|
||||
const [rawCertificateMock] = rawCertificates;
|
||||
const [parsedCertificateMock] = parsedCertificates;
|
||||
|
||||
const executionSteps = [
|
||||
Symbol('step 0'),
|
||||
Symbol('step 1'),
|
||||
Symbol('step 2'),
|
||||
Symbol('step 3'),
|
||||
Symbol('step 4'),
|
||||
Symbol('step 5'),
|
||||
Symbol('step 6'),
|
||||
Symbol('step 7'),
|
||||
Symbol('step 8'),
|
||||
];
|
||||
|
||||
const executionFlow = {
|
||||
[executionSteps[0]]: {
|
||||
Certificates: executionSteps[1],
|
||||
Close: jest.fn(),
|
||||
Open: jest.fn(),
|
||||
},
|
||||
[executionSteps[1]]: {
|
||||
Count: executionSteps[2],
|
||||
Item: jest.fn(() => executionSteps[3]),
|
||||
},
|
||||
[executionSteps[2]]: 1,
|
||||
[executionSteps[3]]: {
|
||||
IssuerName: executionSteps[6],
|
||||
SubjectName: executionSteps[5],
|
||||
Thumbprint: executionSteps[4],
|
||||
ValidFromDate: executionSteps[7],
|
||||
ValidToDate: executionSteps[8],
|
||||
},
|
||||
[executionSteps[6]]: rawCertificateMock.IssuerName,
|
||||
[executionSteps[5]]: rawCertificateMock.SubjectName,
|
||||
[executionSteps[4]]: rawCertificateMock.Thumbprint,
|
||||
[executionSteps[7]]: rawCertificateMock.ValidFromDate,
|
||||
[executionSteps[8]]: rawCertificateMock.ValidToDate,
|
||||
};
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation(() => executionSteps[0]);
|
||||
|
||||
describe('getUserCertificates', () => {
|
||||
test('returns certificates list', async () => {
|
||||
const certificates = await getAllUserCertificates();
|
||||
|
||||
expect(certificates.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('returns certificates with correct fields', async () => {
|
||||
const [certificate] = await getAllUserCertificates();
|
||||
|
||||
expect(certificate).toMatchObject(parsedCertificateMock);
|
||||
});
|
||||
});
|
99
src/api/getAllUserCertificates.ts
Normal file
99
src/api/getAllUserCertificates.ts
Normal file
@ -0,0 +1,99 @@
|
||||
import { CadesCertificate, Certificate } from './certificate';
|
||||
import { _afterPluginsLoaded } from '../helpers/_afterPluginsLoaded';
|
||||
import { _extractCommonName } from '../helpers/_extractCommonName';
|
||||
import { _extractMeaningfulErrorMessage } from '../helpers/_extractMeaningfulErrorMessage';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from '../helpers/_generateCadesFn';
|
||||
|
||||
let certificatesCache: Certificate[];
|
||||
|
||||
/**
|
||||
* Возвращает все сертификаты без фильтрации по дате и наличию приватного ключа
|
||||
*
|
||||
* @param resetCache = false - позволяет сбросить кэш ранее полученных сертификатов
|
||||
* @returns список сертификатов
|
||||
*/
|
||||
export const getAllUserCertificates = _afterPluginsLoaded((resetCache: boolean = false): Certificate[] => {
|
||||
const { cadesplugin } = window;
|
||||
|
||||
if (!resetCache && certificatesCache) {
|
||||
return certificatesCache;
|
||||
}
|
||||
|
||||
return eval(
|
||||
_generateCadesFn(function getAllUserCertificates(): Certificate[] {
|
||||
let cadesStore;
|
||||
|
||||
try {
|
||||
cadesStore = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.Store');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при попытке доступа к хранилищу');
|
||||
}
|
||||
|
||||
try {
|
||||
void (
|
||||
__cadesAsyncToken__ +
|
||||
cadesStore.Open(
|
||||
cadesplugin.CAPICOM_CURRENT_USER_STORE,
|
||||
cadesplugin.CAPICOM_MY_STORE,
|
||||
cadesplugin.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED,
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при открытии хранилища');
|
||||
}
|
||||
|
||||
let cadesCertificates;
|
||||
let cadesCertificatesCount;
|
||||
|
||||
try {
|
||||
cadesCertificates = __cadesAsyncToken__ + cadesStore.Certificates;
|
||||
cadesCertificatesCount = __cadesAsyncToken__ + cadesCertificates.Count;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка получения списка сертификатов');
|
||||
}
|
||||
|
||||
if (!cadesCertificatesCount) {
|
||||
throw new Error('Нет доступных сертификатов');
|
||||
}
|
||||
|
||||
const certificateList: Certificate[] = [];
|
||||
|
||||
try {
|
||||
while (cadesCertificatesCount) {
|
||||
const cadesCertificate: CadesCertificate =
|
||||
__cadesAsyncToken__ + cadesCertificates.Item(cadesCertificatesCount);
|
||||
|
||||
certificateList.push(
|
||||
new Certificate(
|
||||
cadesCertificate,
|
||||
_extractCommonName(__cadesAsyncToken__ + cadesCertificate.SubjectName),
|
||||
__cadesAsyncToken__ + cadesCertificate.IssuerName,
|
||||
__cadesAsyncToken__ + cadesCertificate.SubjectName,
|
||||
__cadesAsyncToken__ + cadesCertificate.Thumbprint,
|
||||
__cadesAsyncToken__ + cadesCertificate.ValidFromDate,
|
||||
__cadesAsyncToken__ + cadesCertificate.ValidToDate,
|
||||
),
|
||||
);
|
||||
|
||||
cadesCertificatesCount--;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка обработки сертификатов');
|
||||
}
|
||||
|
||||
cadesStore.Close();
|
||||
|
||||
certificatesCache = certificateList;
|
||||
|
||||
return certificatesCache;
|
||||
}),
|
||||
);
|
||||
});
|
26
src/api/getCspVersion.test.ts
Normal file
26
src/api/getCspVersion.test.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import 'cadesplugin';
|
||||
import { getCspVersion } from './getCspVersion';
|
||||
|
||||
const executionSteps = [Symbol('step 0'), Symbol('step 1'), Symbol('step 2')];
|
||||
|
||||
// "any" because of using toString on the literal
|
||||
const executionFlow: any = {
|
||||
[executionSteps[0]]: {
|
||||
CSPVersion: jest.fn(() => executionSteps[1]),
|
||||
},
|
||||
[executionSteps[1]]: {
|
||||
toString: jest.fn(() => executionSteps[2]),
|
||||
},
|
||||
[executionSteps[2]]: '4.0.9971',
|
||||
};
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation(() => executionSteps[0]);
|
||||
|
||||
describe('getCspVersion', () => {
|
||||
test('returns information about CSP', async () => {
|
||||
const cspVersion = await getCspVersion();
|
||||
|
||||
expect(cspVersion).toStrictEqual('4.0.9971');
|
||||
});
|
||||
});
|
32
src/api/getCspVersion.ts
Normal file
32
src/api/getCspVersion.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { _afterPluginsLoaded } from '../helpers/_afterPluginsLoaded';
|
||||
import { _extractMeaningfulErrorMessage } from '../helpers/_extractMeaningfulErrorMessage';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from '../helpers/_generateCadesFn';
|
||||
|
||||
/**
|
||||
* Предоставляет информацию о системе
|
||||
*
|
||||
* @returns информацию о CSP
|
||||
*/
|
||||
export const getCspVersion = _afterPluginsLoaded((): string => {
|
||||
let cspVersion = null;
|
||||
|
||||
return eval(
|
||||
_generateCadesFn(function getCspVersion(): string {
|
||||
let cadesAbout;
|
||||
|
||||
try {
|
||||
cadesAbout = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.About');
|
||||
|
||||
cspVersion = __cadesAsyncToken__ + cadesAbout.CSPVersion();
|
||||
|
||||
cspVersion = __cadesAsyncToken__ + cspVersion.toString();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при получении версии системы');
|
||||
}
|
||||
|
||||
return cspVersion;
|
||||
}),
|
||||
);
|
||||
});
|
28
src/api/getPluginVersion.test.ts
Normal file
28
src/api/getPluginVersion.test.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import 'cadesplugin';
|
||||
import { getPluginVersion } from './getPluginVersion';
|
||||
|
||||
const executionSteps = [Symbol('step 0'), Symbol('step 1'), Symbol('step 2'), Symbol('step 3')];
|
||||
|
||||
// "any" because of using toString on the literal
|
||||
const executionFlow: any = {
|
||||
[executionSteps[0]]: {
|
||||
PluginVersion: executionSteps[1],
|
||||
Version: executionSteps[2],
|
||||
},
|
||||
[executionSteps[1]]: undefined,
|
||||
[executionSteps[2]]: {
|
||||
toString: jest.fn(() => executionSteps[3]),
|
||||
},
|
||||
[executionSteps[3]]: '2.0.13771',
|
||||
};
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation(() => executionSteps[0]);
|
||||
|
||||
describe('getPluginVersion', () => {
|
||||
test('returns information about plugin', async () => {
|
||||
const pluginVersion = await getPluginVersion();
|
||||
|
||||
expect(pluginVersion).toStrictEqual('2.0.13771');
|
||||
});
|
||||
});
|
36
src/api/getPluginVersion.ts
Normal file
36
src/api/getPluginVersion.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { _afterPluginsLoaded } from '../helpers/_afterPluginsLoaded';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from '../helpers/_generateCadesFn';
|
||||
import { _extractMeaningfulErrorMessage } from '../helpers/_extractMeaningfulErrorMessage';
|
||||
|
||||
/**
|
||||
* Предоставляет информацию о системе
|
||||
*
|
||||
* @returns информацию о плагине
|
||||
*/
|
||||
export const getPluginVersion = _afterPluginsLoaded((): string => {
|
||||
let cadesVersion = null;
|
||||
|
||||
return eval(
|
||||
_generateCadesFn(function getPluginVersion(): string {
|
||||
let cadesAbout;
|
||||
|
||||
try {
|
||||
cadesAbout = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.About');
|
||||
|
||||
cadesVersion = __cadesAsyncToken__ + cadesAbout.PluginVersion;
|
||||
|
||||
if (!cadesVersion) {
|
||||
cadesVersion = __cadesAsyncToken__ + cadesAbout.Version;
|
||||
}
|
||||
|
||||
cadesVersion = __cadesAsyncToken__ + cadesVersion.toString();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
||||
throw new Error(_extractMeaningfulErrorMessage(error) || 'Ошибка при получении информации о плагине');
|
||||
}
|
||||
|
||||
return cadesVersion;
|
||||
}),
|
||||
);
|
||||
});
|
@ -1,10 +1,15 @@
|
||||
export * from './getCertificate';
|
||||
export * from './getUserCertificates';
|
||||
export * from './getAllUserCertificates';
|
||||
export * from './getSystemInfo';
|
||||
export * from './isValidSystemSetup';
|
||||
export * from './createSignature';
|
||||
export * from './createXMLSignature';
|
||||
export * from './createDetachedSignature';
|
||||
export * from './addDetachedSignature';
|
||||
export * from './createAttachedSignature';
|
||||
export * from './addAttachedSignature';
|
||||
export * from './createHash';
|
||||
export * from './certificate';
|
||||
export * from './getCspVersion';
|
||||
export * from './getPluginVersion';
|
||||
|
0
src/crypto-pro.ts → src/crypto-pro-custom.ts
Executable file → Normal file
0
src/crypto-pro.ts → src/crypto-pro-custom.ts
Executable file → Normal file
@ -5,15 +5,15 @@ describe('_extractMeaningfulErrorMessage', () => {
|
||||
test("returns meaningful message provided by vendor if it's possible", () => {
|
||||
expect(
|
||||
_extractMeaningfulErrorMessage(new Error('Какое-то более-менее подробное сообщение об ошибке. (0x8010006E)')),
|
||||
).toBe('Какое-то более-менее подробное сообщение об ошибке');
|
||||
).toBe('Какое-то более-менее подробное сообщение об ошибке (Код ошибки: 0x8010006E)');
|
||||
expect(
|
||||
_extractMeaningfulErrorMessage(new Error('Какое-то более-менее подробное сообщение об ошибке. (0x801')),
|
||||
).toBe('Какое-то более-менее подробное сообщение об ошибке');
|
||||
).toBe('Какое-то более-менее подробное сообщение об ошибке (Код ошибки: 0x801)');
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Какое-то более-менее подробное сообщение об ошибке.(0x801'))).toBe(
|
||||
'Какое-то более-менее подробное сообщение об ошибке',
|
||||
'Какое-то более-менее подробное сообщение об ошибке (Код ошибки: 0x801)',
|
||||
);
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Какое-то более-менее подробное сообщение об ошибке(0x801'))).toBe(
|
||||
'Какое-то более-менее подробное сообщение об ошибке',
|
||||
'Какое-то более-менее подробное сообщение об ошибке (Код ошибки: 0x801)',
|
||||
);
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Какое-то более-менее подробное сообщение об ошибке.'))).toBe(
|
||||
'Какое-то более-менее подробное сообщение об ошибке',
|
||||
@ -28,9 +28,11 @@ describe('_extractMeaningfulErrorMessage', () => {
|
||||
'Какое-то более-менее. Подробное сообщение об ошибке',
|
||||
);
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Какая-то error случилась, по причине 666 (0x801'))).toBe(
|
||||
'Какая-то error случилась, по причине 666',
|
||||
'Какая-то error случилась, по причине 666 (Код ошибки: 0x801)',
|
||||
);
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Не удалось. 0x8010006E'))).toBe(
|
||||
'Не удалось (Код ошибки: 0x8010006E)',
|
||||
);
|
||||
expect(_extractMeaningfulErrorMessage(new Error('Не удалось. 0x8010006E'))).toBe('Не удалось');
|
||||
});
|
||||
|
||||
test("returns null if can't extract meaningful error message", () => {
|
||||
|
@ -15,7 +15,7 @@ export const _extractMeaningfulErrorMessage = (error: Error): string | null => {
|
||||
return null;
|
||||
}
|
||||
|
||||
const searchResult = errorContainer.message.match(/^(.*?)(?:(?:\.?\s?\(?0x)|(?:\.?$))/);
|
||||
const searchResult = errorContainer.message.match(/^(.*?)(?:(?:\.?\s?\(?(0x[0-9a-zA-Z]{1,8})\)?)|(?:\.?$))/);
|
||||
|
||||
return searchResult ? searchResult[1] : null;
|
||||
return searchResult ? searchResult[1] + (searchResult[2] ? ' (Код ошибки: ' + searchResult[2] + ')' : '') : null;
|
||||
};
|
||||
|
@ -15,8 +15,7 @@ describe('_generateCadesFn', () => {
|
||||
console.log('hello from named function');
|
||||
}),
|
||||
).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
`(function anonymous() {
|
||||
|
||||
console.log('hello from named function');
|
||||
|
||||
@ -26,8 +25,7 @@ describe('_generateCadesFn', () => {
|
||||
|
||||
test('generates function body from arrow function callback', () => {
|
||||
expect(_generateCadesFn(() => console.log('hello from arrow function'))).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
`(function anonymous() {
|
||||
return console.log('hello from arrow function');
|
||||
})();//# sourceURL=crypto-pro_dynamicFn.js`,
|
||||
);
|
||||
@ -43,8 +41,7 @@ describe('_generateCadesFn', () => {
|
||||
void (__cadesAsyncToken__ + cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
}),
|
||||
).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
`(function anonymous() {
|
||||
|
||||
var cadesFoo = cadesplugin.CreateObject('CADESCOM.Foo');
|
||||
var cadesBar = cadesplugin.CreateObject('CAdESCOM.Bar');
|
||||
@ -72,8 +69,7 @@ describe('_generateCadesFn', () => {
|
||||
void (__cadesAsyncToken__ + cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
}),
|
||||
).toEqual(
|
||||
`cadesplugin.async_spawn(function* anonymous(
|
||||
) {
|
||||
`cadesplugin.async_spawn(function* anonymous() {
|
||||
|
||||
var cadesFoo = yield cadesplugin.CreateObjectAsync('CADESCOM.Foo');
|
||||
var cadesBar = yield cadesplugin.CreateObjectAsync('CAdESCOM.Bar');
|
||||
|
@ -1,50 +1,88 @@
|
||||
// @ts-ignore
|
||||
import * as sinon from 'sinon';
|
||||
import 'cadesplugin';
|
||||
import { CadesCertificate } from '../api/certificate';
|
||||
import { _getCadesCert } from './_getCadesCert';
|
||||
import { __cadesAsyncToken__, __createCadesPluginObject__, _generateCadesFn } from './_generateCadesFn';
|
||||
|
||||
const certificateMock = {
|
||||
IssuerName: 'no matter',
|
||||
SubjectName: 'no matter',
|
||||
Thumbprint: 'some thumbprint',
|
||||
ValidFromDate: 'whatever',
|
||||
ValidToDate: 'whatever',
|
||||
};
|
||||
const CreateObjectAsync = window.cadesplugin.CreateObjectAsync;
|
||||
|
||||
const executionSteps = [Symbol('step 0'), Symbol('step 1'), Symbol('step 2'), Symbol('step 3'), Symbol('step 4')];
|
||||
describe('_generateCadesFn', () => {
|
||||
describe('synchronous environment', () => {
|
||||
beforeEach(() => {
|
||||
delete window.cadesplugin.CreateObjectAsync;
|
||||
});
|
||||
|
||||
const executionFlow = {
|
||||
[executionSteps[0]]: {
|
||||
Certificates: executionSteps[1],
|
||||
Close: sinon.stub(),
|
||||
Open: sinon.stub(),
|
||||
},
|
||||
[executionSteps[1]]: {
|
||||
Count: executionSteps[3],
|
||||
Find: sinon.stub().returns(executionSteps[2]),
|
||||
},
|
||||
[executionSteps[2]]: {
|
||||
Count: executionSteps[3],
|
||||
Item: sinon.stub().returns(executionSteps[4]),
|
||||
},
|
||||
[executionSteps[3]]: 1,
|
||||
[executionSteps[4]]: {
|
||||
IssuerName: certificateMock.IssuerName,
|
||||
SubjectName: certificateMock.SubjectName,
|
||||
Thumbprint: certificateMock.Thumbprint,
|
||||
ValidFromDate: certificateMock.ValidFromDate,
|
||||
ValidToDate: certificateMock.ValidToDate,
|
||||
},
|
||||
};
|
||||
test('generates function body from named function callback', () => {
|
||||
expect(
|
||||
_generateCadesFn(function namedFunction() {
|
||||
console.log('hello from named function');
|
||||
}),
|
||||
).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
|
||||
window.cadesplugin.__defineExecutionFlow(executionFlow);
|
||||
window.cadesplugin.CreateObjectAsync.mockImplementation(() => executionSteps[0]);
|
||||
console.log('hello from named function');
|
||||
|
||||
describe('_getCadesCert', () => {
|
||||
test('returns certificate by a thumbprint', async () => {
|
||||
const certificate: CadesCertificate = await _getCadesCert(certificateMock.Thumbprint);
|
||||
})();//# sourceURL=crypto-pro_namedFunction.js`,
|
||||
);
|
||||
});
|
||||
|
||||
expect(certificate).toStrictEqual(certificateMock);
|
||||
test('generates function body from arrow function callback', () => {
|
||||
expect(_generateCadesFn(() => console.log('hello from arrow function'))).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
return console.log('hello from arrow function');
|
||||
})();//# sourceURL=crypto-pro_dynamicFn.js`,
|
||||
);
|
||||
});
|
||||
|
||||
test('generates function body with synchronous vendor library references', () => {
|
||||
expect(
|
||||
_generateCadesFn(function methodInSyncEnvironment() {
|
||||
const cadesFoo = __cadesAsyncToken__ + __createCadesPluginObject__('CADESCOM.Foo');
|
||||
const cadesBar = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.Bar');
|
||||
const cadesBarNoMatterWhat = __cadesAsyncToken__ + cadesBar.NoMatterWhat;
|
||||
void (__cadesAsyncToken__ + cadesFoo.propset_WhateverProperty('whatever value'));
|
||||
void (__cadesAsyncToken__ + cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
}),
|
||||
).toEqual(
|
||||
`(function anonymous(
|
||||
) {
|
||||
|
||||
var cadesFoo = cadesplugin.CreateObject('CADESCOM.Foo');
|
||||
var cadesBar = cadesplugin.CreateObject('CAdESCOM.Bar');
|
||||
var cadesBarNoMatterWhat = cadesBar.NoMatterWhat;
|
||||
void (cadesFoo.WhateverProperty = 'whatever value');
|
||||
void (cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
|
||||
})();//# sourceURL=crypto-pro_methodInSyncEnvironment.js`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('synchronous environment', () => {
|
||||
beforeEach(() => {
|
||||
window.cadesplugin.CreateObjectAsync = CreateObjectAsync;
|
||||
});
|
||||
|
||||
test('generates function body with asynchronous vendor library references', () => {
|
||||
expect(
|
||||
_generateCadesFn(function methodInAsyncEnvironment() {
|
||||
const cadesFoo = __cadesAsyncToken__ + __createCadesPluginObject__('CADESCOM.Foo');
|
||||
const cadesBar = __cadesAsyncToken__ + __createCadesPluginObject__('CAdESCOM.Bar');
|
||||
const cadesBarNoMatterWhat = __cadesAsyncToken__ + cadesBar.NoMatterWhat;
|
||||
void (__cadesAsyncToken__ + cadesFoo.propset_WhateverProperty('whatever value'));
|
||||
void (__cadesAsyncToken__ + cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
}),
|
||||
).toEqual(
|
||||
`cadesplugin.async_spawn(function* anonymous(
|
||||
) {
|
||||
|
||||
var cadesFoo = yield cadesplugin.CreateObjectAsync('CADESCOM.Foo');
|
||||
var cadesBar = yield cadesplugin.CreateObjectAsync('CAdESCOM.Bar');
|
||||
var cadesBarNoMatterWhat = yield cadesBar.NoMatterWhat;
|
||||
void (yield cadesFoo.propset_WhateverProperty('whatever value'));
|
||||
void (yield cadesBarNoMatterWhat.whateverMethod(cadesFoo));
|
||||
|
||||
});//# sourceURL=crypto-pro_methodInAsyncEnvironment.js`,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -14,7 +14,7 @@
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"./src/crypto-pro.ts"
|
||||
"./src/crypto-pro-custom.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
|
Loading…
Reference in New Issue
Block a user