diff --git a/src/crypto.ts b/src/crypto.ts index abc5f52..c4ca634 100644 --- a/src/crypto.ts +++ b/src/crypto.ts @@ -4,7 +4,7 @@ import { SubtleCrypto } from "./subtle"; export class Crypto extends core.Crypto { - public get nativeCrypto() { + public get nativeCrypto(): globalThis.Crypto { return nativeCrypto; } diff --git a/src/debug.ts b/src/debug.ts index e906a9f..54c85d6 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -1,41 +1,41 @@ export class Debug { - public static get enabled() { + public static get enabled(): boolean { return typeof self !== "undefined" && (self as any).PV_WEBCRYPTO_LINER_LOG; } public static log(message?: any, ...optionalParams: any[]): void; - public static log(...args: any[]) { + public static log(...args: any[]): void { if (this.enabled) { - console.log.apply(console, args); + console.log(...args); } } - public static error(message?: any, ...optionalParams: any[]): void - public static error(...args: any[]) { + public static error(message?: any, ...optionalParams: any[]): void; + public static error(...args: any[]): void { if (this.enabled) { - console.error.apply(console, args); + console.error(...args); } } public static info(message?: any, ...optionalParams: any[]): void; - public static info(...args: any[]) { + public static info(...args: any[]): void { if (this.enabled) { - console.info.apply(console, args); + console.info(...args); } } public static warn(message?: any, ...optionalParams: any[]): void; - public static warn(...args: any[]) { + public static warn(...args: any[]): void { if (this.enabled) { - console.warn.apply(console, args); + console.warn(...args); } } public static trace(message?: any, ...optionalParams: any[]): void; - public static trace(...args: any[]) { + public static trace(...args: any[]): void { if (this.enabled) { - console.trace.apply(console, args); + console.trace(...args); } } diff --git a/src/helper.ts b/src/helper.ts index bd9b54a..0d74e94 100644 --- a/src/helper.ts +++ b/src/helper.ts @@ -16,7 +16,7 @@ export interface IBrowserInfo { /** * Returns info about browser */ -export function BrowserInfo() { +export function BrowserInfo(): IBrowserInfo { const res: IBrowserInfo = { name: Browser.Unknown, version: "0", @@ -26,34 +26,33 @@ export function BrowserInfo() { } const userAgent = self.navigator.userAgent; - let reg: string[] | null; - // tslint:disable-next-line:no-conditional-assignment - if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) { + const reg = /edge\/([\d.]+)/i.exec(userAgent); + if (reg) { res.name = Browser.Edge; res.version = reg[1]; } else if (/msie/i.test(userAgent)) { res.name = Browser.IE; - res.version = /msie ([\d\.]+)/i.exec(userAgent)![1]; + res.version = /msie ([\d.]+)/i.exec(userAgent)![1]; } else if (/Trident/i.test(userAgent)) { res.name = Browser.IE; - res.version = /rv:([\d\.]+)/i.exec(userAgent)![1]; + res.version = /rv:([\d.]+)/i.exec(userAgent)![1]; } else if (/chrome/i.test(userAgent)) { res.name = Browser.Chrome; - res.version = /chrome\/([\d\.]+)/i.exec(userAgent)![1]; + res.version = /chrome\/([\d.]+)/i.exec(userAgent)![1]; } else if (/firefox/i.test(userAgent)) { res.name = Browser.Firefox; - res.version = /firefox\/([\d\.]+)/i.exec(userAgent)![1]; + res.version = /firefox\/([\d.]+)/i.exec(userAgent)![1]; } else if (/mobile/i.test(userAgent)) { res.name = Browser.Mobile; res.version = /mobile\/([\w]+)/i.exec(userAgent)![1]; } else if (/safari/i.test(userAgent)) { res.name = Browser.Safari; - res.version = /version\/([\d\.]+)/i.exec(userAgent)![1]; + res.version = /version\/([\d.]+)/i.exec(userAgent)![1]; } return res; } -export function string2buffer(binaryString: string) { +export function string2buffer(binaryString: string): Uint8Array { const res = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { res[i] = binaryString.charCodeAt(i); @@ -61,7 +60,7 @@ export function string2buffer(binaryString: string) { return res; } -export function buffer2string(buffer: Uint8Array) { +export function buffer2string(buffer: Uint8Array): string { let res = ""; // tslint:disable-next-line:prefer-for-of for (let i = 0; i < buffer.length; i++) { @@ -70,10 +69,10 @@ export function buffer2string(buffer: Uint8Array) { return res; } -export function concat(...buf: Uint8Array[]) { +export function concat(...buf: Uint8Array[]): Uint8Array { const res = new Uint8Array(buf.map((item) => item.length).reduce((prev, cur) => prev + cur)); let offset = 0; - buf.forEach((item, index) => { + buf.forEach((item) => { for (let i = 0; i < item.length; i++) { res[offset + i] = item[i]; } @@ -83,7 +82,7 @@ export function concat(...buf: Uint8Array[]) { } export function assign(target: any, ...sources: any[]): any; -export function assign(...args: any[]) { +export function assign(...args: any[]): any { const res = args[0]; for (let i = 1; i < args.length; i++) { const obj = args[i]; diff --git a/src/init.ts b/src/init.ts index 9985127..4d981d0 100644 --- a/src/init.ts +++ b/src/init.ts @@ -1,16 +1,17 @@ import { nativeSubtle } from "./native"; -function WrapFunction(subtle: any, name: string) { +function WrapFunction(subtle: any, name: string): void { const fn = subtle[name]; // tslint:disable-next-line:only-arrow-functions - subtle[name] = function () { + subtle[name] = function (): Promise { + // eslint-disable-next-line prefer-rest-params const args = arguments; return new Promise((resolve, reject) => { const op: any = fn.apply(subtle, args); - op.oncomplete = (e: any) => { + op.oncomplete = (e: any): any => { resolve(e.target.result); }; - op.onerror = (e: any) => { + op.onerror = (_e: any): void => { reject(`Error on running '${name}' function`); }; }); @@ -35,7 +36,7 @@ if (typeof self !== "undefined" && self["msCrypto"]) { // fix: Math.imul for IE if (!(Math as any).imul) { // tslint:disable-next-line:only-arrow-functions - (Math as any).imul = function imul(a: number, b: number) { + (Math as any).imul = function imul(a: number, b: number): number { const ah = (a >>> 16) & 0xffff; const al = a & 0xffff; const bh = (b >>> 16) & 0xffff; diff --git a/src/lib.ts b/src/lib.ts index 2a71b58..6ff8586 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -1,4 +1,4 @@ -import { Crypto, nativeCrypto } from "."; +import { Crypto, nativeCrypto } from "./index"; import "./init"; if (nativeCrypto) { diff --git a/src/mechs/aes/aes_ecb.ts b/src/mechs/aes/aes_ecb.ts index 740a443..c2acb8c 100644 --- a/src/mechs/aes/aes_ecb.ts +++ b/src/mechs/aes/aes_ecb.ts @@ -24,7 +24,7 @@ export class AesEcbProvider extends core.AesEcbProvider { return AesCrypto.importKey(format, keyData, algorithm, extractable, keyUsages); } - public checkCryptoKey(key: CryptoKey, keyUsage: KeyUsage) { + public checkCryptoKey(key: CryptoKey, keyUsage: KeyUsage): void { super.checkCryptoKey(key, keyUsage); AesCrypto.checkCryptoKey(key); } diff --git a/src/mechs/aes/aes_kw.ts b/src/mechs/aes/aes_kw.ts index 5e82aba..ef07190 100644 --- a/src/mechs/aes/aes_kw.ts +++ b/src/mechs/aes/aes_kw.ts @@ -3,19 +3,19 @@ import { AesCrypto } from "./crypto"; import { AesCryptoKey } from "./key"; export class AesKwProvider extends core.AesKwProvider { - public async onEncrypt(algorithm: AesCtrParams, key: CryptoKey, data: ArrayBuffer): Promise { + public async onEncrypt(_algorithm: AesCtrParams, _key: CryptoKey, _data: ArrayBuffer): Promise { throw new Error("Method not implemented."); } - public async onDecrypt(algorithm: AesCtrParams, key: CryptoKey, data: ArrayBuffer): Promise { + public async onDecrypt(_algorithm: AesCtrParams, _key: CryptoKey, _data: ArrayBuffer): Promise { throw new Error("Method not implemented."); } - public async onGenerateKey(algorithm: AesKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise { + public async onGenerateKey(_algorithm: AesKeyGenParams, _extractable: boolean, _keyUsages: KeyUsage[]): Promise { throw new Error("Method not implemented."); } - public async onExportKey(format: KeyFormat, key: CryptoKey): Promise { + public async onExportKey(_format: KeyFormat, _key: CryptoKey): Promise { throw new Error("Method not implemented."); } - public async onImportKey(format: KeyFormat, keyData: ArrayBuffer | JsonWebKey, algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise { + public async onImportKey(_format: KeyFormat, _keyData: ArrayBuffer | JsonWebKey, _algorithm: Algorithm, _extractable: boolean, _keyUsages: KeyUsage[]): Promise { throw new Error("Method not implemented."); } diff --git a/src/mechs/aes/crypto.ts b/src/mechs/aes/crypto.ts index 035fbbd..19c15ee 100644 --- a/src/mechs/aes/crypto.ts +++ b/src/mechs/aes/crypto.ts @@ -11,24 +11,24 @@ export class AesCrypto { public static AesECB = "AES-ECB"; public static AesGCM = "AES-GCM"; - public static checkCryptoKey(key: any) { + public static checkCryptoKey(key: any): void { if (!(key instanceof AesCryptoKey)) { throw new TypeError("key: Is not AesCryptoKey"); } } - public static async generateKey(algorithm: AesKeyGenParams, extractable: boolean, usages: KeyUsage[]) { + public static async generateKey(algorithm: AesKeyGenParams, extractable: boolean, usages: KeyUsage[]): Promise { // gat random bytes for key const raw = nativeCrypto.getRandomValues(new Uint8Array(algorithm.length / 8)); return new AesCryptoKey(algorithm, extractable, usages, raw); } - public static async encrypt(algorithm: Algorithm, key: AesCryptoKey, data: ArrayBuffer) { + public static async encrypt(algorithm: Algorithm, key: AesCryptoKey, data: ArrayBuffer): Promise { return this.cipher(algorithm, key, core.BufferSourceConverter.toUint8Array(data), true); } - public static async decrypt(algorithm: Algorithm, key: AesCryptoKey, data: ArrayBuffer) { + public static async decrypt(algorithm: Algorithm, key: AesCryptoKey, data: ArrayBuffer): Promise { return this.cipher(algorithm, key, core.BufferSourceConverter.toUint8Array(data), false); } @@ -66,7 +66,7 @@ export class AesCrypto { return key; } - private static async cipher(algorithm: Algorithm, key: AesCryptoKey, data: Uint8Array, encrypt: boolean) { + private static async cipher(algorithm: Algorithm, key: AesCryptoKey, data: Uint8Array, encrypt: boolean): Promise { const action = encrypt ? "encrypt" : "decrypt"; let result: Uint8Array; if (isAlgorithm(algorithm, AesCrypto.AesCBC)) { diff --git a/src/mechs/aes/key.ts b/src/mechs/aes/key.ts index 27c09ba..1d495ab 100644 --- a/src/mechs/aes/key.ts +++ b/src/mechs/aes/key.ts @@ -9,7 +9,7 @@ export class AesCryptoKey extends CryptoKey { super(algorithm, extractable, "secret", usages); } - public toJSON() { + public toJSON(): JsonWebKey { const jwk: JsonWebKey = { kty: "oct", alg: this.getJwkAlgorithm(), @@ -20,7 +20,7 @@ export class AesCryptoKey extends CryptoKey { return jwk; } - private getJwkAlgorithm() { + private getJwkAlgorithm(): string { switch (this.algorithm.name.toUpperCase()) { case "AES-CBC": return `A${this.algorithm.length}CBC`; diff --git a/src/mechs/des/crypto.ts b/src/mechs/des/crypto.ts index 2d9bf44..0feed20 100644 --- a/src/mechs/des/crypto.ts +++ b/src/mechs/des/crypto.ts @@ -1,3 +1,4 @@ +// eslint-disable-next-line @typescript-eslint/triple-slash-reference /// import * as des from "des.js"; @@ -8,13 +9,13 @@ import { DesCryptoKey } from "./key"; export class DesCrypto { - public static checkLib() { - if (typeof(des) === "undefined") { + public static checkLib(): void { + if (typeof (des) === "undefined") { throw new core.OperationError("Cannot implement DES mechanism. Add 'https://peculiarventures.github.io/pv-webcrypto-tests/src/des.js' script to your project"); } } - public static checkCryptoKey(key: any) { + public static checkCryptoKey(key: any): void { if (!(key instanceof DesCryptoKey)) { throw new TypeError("key: Is not DesCryptoKey"); } diff --git a/src/mechs/des/key.ts b/src/mechs/des/key.ts index e342842..7b6ae5c 100644 --- a/src/mechs/des/key.ts +++ b/src/mechs/des/key.ts @@ -9,7 +9,7 @@ export class DesCryptoKey extends CryptoKey { super(algorithm, extractable, "secret", usages); } - public toJSON() { + public toJSON(): JsonWebKey { const jwk: JsonWebKey = { kty: "oct", alg: this.getJwkAlgorithm(), @@ -20,7 +20,7 @@ export class DesCryptoKey extends CryptoKey { return jwk; } - private getJwkAlgorithm() { + private getJwkAlgorithm(): string { switch (this.algorithm.name.toUpperCase()) { case "DES-CBC": return `DES-CBC`; diff --git a/src/mechs/ec/crypto.ts b/src/mechs/ec/crypto.ts index ce26b8d..eeaf9c6 100644 --- a/src/mechs/ec/crypto.ts +++ b/src/mechs/ec/crypto.ts @@ -13,7 +13,7 @@ export class EcCrypto { public static readonly ASN_ALGORITHM = "1.2.840.10045.2.1"; - public static checkLib() { + public static checkLib(): void { if (typeof (elliptic) === "undefined") { throw new core.OperationError("Cannot implement EC mechanism. Add 'https://peculiarventures.github.io/pv-webcrypto-tests/src/elliptic.js' script to your project"); } @@ -47,16 +47,16 @@ export class EcCrypto { }; } - public static checkCryptoKey(key: any) { + public static checkCryptoKey(key: any): void { if (!(key instanceof EcCryptoKey)) { throw new TypeError("key: Is not EcCryptoKey"); } } - public static concat(...buf: Uint8Array[]) { + public static concat(...buf: Uint8Array[]): Uint8Array { const res = new Uint8Array(buf.map((item) => item.length).reduce((prev, cur) => prev + cur)); let offset = 0; - buf.forEach((item, index) => { + buf.forEach((item) => { for (let i = 0; i < item.length; i++) { res[offset + i] = item[i]; } @@ -114,7 +114,7 @@ export class EcCrypto { return key; } - protected static getNamedCurve(wcNamedCurve: string) { + protected static getNamedCurve(wcNamedCurve: string): string { const crv = wcNamedCurve.toUpperCase(); let res = ""; if (["P-256", "P-384", "P-521"].indexOf(crv) > -1) { @@ -129,11 +129,11 @@ export class EcCrypto { return res; } - private static initEcKey(namedCurve: string) { + private static initEcKey(namedCurve: string): EllipticJS.EC { return elliptic.ec(this.getNamedCurve(namedCurve)); } - private static exportPkcs8Key(key: EcCryptoKey) { + private static exportPkcs8Key(key: EcCryptoKey): ArrayBuffer { const keyInfo = new core.asn1.PrivateKeyInfo(); keyInfo.privateKeyAlgorithm.algorithm = this.ASN_ALGORITHM; keyInfo.privateKeyAlgorithm.parameters = AsnConvert.serialize( @@ -144,19 +144,19 @@ export class EcCrypto { return AsnConvert.serialize(keyInfo); } - private static importPkcs8Key(data: ArrayBuffer, namedCurve: string) { + private static importPkcs8Key(data: ArrayBuffer, namedCurve: string): EllipticJS.EllipticKeyPair { const keyInfo = AsnConvert.parse(data, core.asn1.PrivateKeyInfo); const privateKey = AsnConvert.parse(keyInfo.privateKey, core.asn1.EcPrivateKey); return this.importEcKey(privateKey, namedCurve); } - private static importSpkiKey(data: ArrayBuffer, namedCurve: string) { + private static importSpkiKey(data: ArrayBuffer, namedCurve: string): EllipticJS.EllipticKeyPair { const keyInfo = AsnConvert.parse(data, core.asn1.PublicKeyInfo); const publicKey = new core.asn1.EcPublicKey(keyInfo.publicKey); return this.importEcKey(publicKey, namedCurve); } - private static exportSpkiKey(key: EcCryptoKey) { + private static exportSpkiKey(key: EcCryptoKey): ArrayBuffer { const publicKey = new core.asn1.EcPublicKey(new Uint8Array(key.data.getPublic("der")).buffer); const keyInfo = new core.asn1.PublicKeyInfo(); @@ -168,7 +168,7 @@ export class EcCrypto { return AsnConvert.serialize(keyInfo); } - private static importJwkKey(data: JsonWebKey) { + private static importJwkKey(data: JsonWebKey): EllipticJS.EllipticKeyPair { let key: core.asn1.EcPrivateKey | core.asn1.EcPublicKey; if (data.d) { // private @@ -180,7 +180,7 @@ export class EcCrypto { return this.importEcKey(key, data.crv); } - private static exportJwkKey(key: EcCryptoKey) { + private static exportJwkKey(key: EcCryptoKey): JsonWebKey { const asnKey = this.exportEcKey(key); const jwk = JsonSerializer.toJSON(asnKey) as JsonWebKey; @@ -210,7 +210,7 @@ export class EcCrypto { } } - private static importEcKey(key: core.asn1.EcPrivateKey | core.asn1.EcPublicKey, namedCurve: string) { + private static importEcKey(key: core.asn1.EcPrivateKey | core.asn1.EcPublicKey, namedCurve: string): EllipticJS.EllipticKeyPair { const ecKey = this.initEcKey(namedCurve); if (key instanceof core.asn1.EcPublicKey) { @@ -219,7 +219,7 @@ export class EcCrypto { return ecKey.keyFromPrivate(new Uint8Array(key.privateKey)); } - private static getPointSize(namedCurve: string) { + private static getPointSize(namedCurve: string): number { switch (namedCurve) { case "P-256": case "K-256": diff --git a/src/mechs/ec/ec_dsa.ts b/src/mechs/ec/ec_dsa.ts index 656b15f..79a48a4 100644 --- a/src/mechs/ec/ec_dsa.ts +++ b/src/mechs/ec/ec_dsa.ts @@ -7,7 +7,7 @@ import { EcCryptoKey } from "./key"; * Converts buffer to number array * @param buffer ArrayBuffer or ArrayBufferView */ -export function b2a(buffer: ArrayBuffer | ArrayBufferView) { +export function b2a(buffer: ArrayBuffer | ArrayBufferView): number[] { const buf = new Uint8Array(buffer as ArrayBuffer); const res: number[] = []; // tslint:disable-next-line:prefer-for-of @@ -39,10 +39,9 @@ export class EcdsaProvider extends core.EcdsaProvider { // get digests const crypto = new Crypto(); - let array; const hash = await crypto.subtle.digest(algorithm.hash, data); - array = b2a(hash); + const array = b2a(hash); const signature = await key.data.sign(array); const asnSignature = new core.asn1.EcDsaSignature(); asnSignature.r = new Uint8Array(signature.r.toArray()).buffer; diff --git a/src/mechs/ec/helper.ts b/src/mechs/ec/helper.ts index 0029390..7daf469 100644 --- a/src/mechs/ec/helper.ts +++ b/src/mechs/ec/helper.ts @@ -1,6 +1,6 @@ import * as core from "webcrypto-core"; -const namedOIDs: { [key: string]: string } = { +const namedOIDs: { [key: string]: string; } = { // P-256 "1.2.840.10045.3.1.7": "P-256", "P-256": "1.2.840.10045.3.1.7", @@ -24,7 +24,7 @@ const namedOIDs: { [key: string]: string } = { "brainpoolP512r1": "1.3.36.3.3.2.8.1.1.13", }; -export function getNamedCurveByOid(oid: string) { +export function getNamedCurveByOid(oid: string): string { const namedCurve = namedOIDs[oid]; if (!namedCurve) { throw new core.OperationError(`Cannot convert OID(${oid}) to WebCrypto named curve`); @@ -32,7 +32,7 @@ export function getNamedCurveByOid(oid: string) { return namedCurve; } -export function getOidByNamedCurve(namedCurve: string) { +export function getOidByNamedCurve(namedCurve: string): string { const oid = namedOIDs[namedCurve]; if (!oid) { throw new core.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); diff --git a/src/mechs/ec/key.ts b/src/mechs/ec/key.ts index 252edb1..90696d1 100644 --- a/src/mechs/ec/key.ts +++ b/src/mechs/ec/key.ts @@ -1,3 +1,4 @@ +// eslint-disable-next-line @typescript-eslint/triple-slash-reference /// import { CryptoKey } from "../../key"; diff --git a/src/mechs/ed/crypto.ts b/src/mechs/ed/crypto.ts index 0868671..0ade5d0 100644 --- a/src/mechs/ed/crypto.ts +++ b/src/mechs/ed/crypto.ts @@ -14,16 +14,16 @@ export class EdCrypto { public static publicKeyUsages = ["verify"]; public static privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; - public static checkLib() { + public static checkLib(): void { if (typeof (elliptic) === "undefined") { throw new core.OperationError("Cannot implement EC mechanism. Add 'https://peculiarventures.github.io/pv-webcrypto-tests/src/elliptic.js' script to your project"); } } - public static concat(...buf: Uint8Array[]) { + public static concat(...buf: Uint8Array[]): Uint8Array { const res = new Uint8Array(buf.map((item) => item.length).reduce((prev, cur) => prev + cur)); let offset = 0; - buf.forEach((item, index) => { + buf.forEach((item) => { for (let i = 0; i < item.length; i++) { res[offset + i] = item[i]; } @@ -93,12 +93,13 @@ export class EdCrypto { // key[31] |= 64; // key.reverse(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const ecdh = new elliptic.ec("curve25519"); const privateKey = ecdh.keyFromPrivate(Convert.ToHex(key), "hex"); const publicHex = (algorithm.public as EdPublicKey).data.getPublic("hex") as string; - const publicView = new Uint8Array(Convert.FromHex(publicHex)); + new Uint8Array(Convert.FromHex(publicHex)); // publicView.reverse(); // const publicKey = ecdh.keyFromPublic(Convert.ToHex(publicView), "hex").getPublic(); const publicKey = (algorithm.public as EdPublicKey).data.getPublic(); @@ -130,7 +131,7 @@ export class EdCrypto { keyInfo.privateKeyAlgorithm.algorithm = getOidByNamedCurve(key.algorithm.namedCurve); keyInfo.privateKey = AsnConvert.serialize(new OctetString(raw)); - return AsnConvert.serialize(keyInfo) + return AsnConvert.serialize(keyInfo); } case "spki": { const raw = Convert.FromHex(key.data.getPublic("hex")); @@ -138,7 +139,7 @@ export class EdCrypto { keyInfo.publicKeyAlgorithm.algorithm = getOidByNamedCurve(key.algorithm.namedCurve); keyInfo.publicKey = raw; - return AsnConvert.serialize(keyInfo) + return AsnConvert.serialize(keyInfo); } case "raw": { return Convert.FromHex(key.data.getPublic("hex")); @@ -181,7 +182,7 @@ export class EdCrypto { } } - protected static importPrivateKey(asnKey: core.asn1.CurvePrivateKey, algorithm: EcKeyImportParams, extractable: boolean, keyUsages: KeyUsage[]) { + protected static importPrivateKey(asnKey: core.asn1.CurvePrivateKey, algorithm: EcKeyImportParams, extractable: boolean, keyUsages: KeyUsage[]): EdPrivateKey { const key = new EdPrivateKey( Object.assign({}, algorithm), extractable, @@ -195,7 +196,7 @@ export class EdCrypto { return key; } - protected static async importPublicKey(asnKey: ArrayBuffer, algorithm: EcKeyImportParams, extractable: boolean, keyUsages: KeyUsage[]) { + protected static async importPublicKey(asnKey: ArrayBuffer, algorithm: EcKeyImportParams, extractable: boolean, keyUsages: KeyUsage[]): Promise { const key = new EdPublicKey( Object.assign({}, algorithm), extractable, diff --git a/src/mechs/ed/helper.ts b/src/mechs/ed/helper.ts index e9482ab..5a5858e 100644 --- a/src/mechs/ed/helper.ts +++ b/src/mechs/ed/helper.ts @@ -1,6 +1,6 @@ import * as core from "webcrypto-core"; -const edOIDs: { [key: string]: string } = { +const edOIDs: { [key: string]: string; } = { // Ed448 [core.asn1.idEd448]: "Ed448", "ed448": core.asn1.idEd448, @@ -15,7 +15,7 @@ const edOIDs: { [key: string]: string } = { "x25519": core.asn1.idX25519, }; -export function getNamedCurveByOid(oid: string) { +export function getNamedCurveByOid(oid: string): string { const namedCurve = edOIDs[oid]; if (!namedCurve) { throw new core.OperationError(`Cannot convert OID(${oid}) to WebCrypto named curve`); @@ -23,7 +23,7 @@ export function getNamedCurveByOid(oid: string) { return namedCurve; } -export function getOidByNamedCurve(namedCurve: string) { +export function getOidByNamedCurve(namedCurve: string): string { const oid = edOIDs[namedCurve.toLowerCase()]; if (!oid) { throw new core.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); diff --git a/src/mechs/ed/private_key.ts b/src/mechs/ed/private_key.ts index 40e292c..c9629bf 100644 --- a/src/mechs/ed/private_key.ts +++ b/src/mechs/ed/private_key.ts @@ -8,10 +8,10 @@ export class EdPrivateKey extends CryptoKey implements IJsonConvertible { public algorithm!: EcKeyAlgorithm; public constructor(algorithm: EcKeyAlgorithm, extractable: boolean, usages: KeyUsage[], public data: EllipticJS.EllipticKeyPair) { - super(algorithm, extractable, "private", usages) + super(algorithm, extractable, "private", usages); } - public toJSON() { + public toJSON(): JsonWebKey { const json: JsonWebKey = { kty: "OKP", crv: this.algorithm.namedCurve, @@ -24,7 +24,7 @@ export class EdPrivateKey extends CryptoKey implements IJsonConvertible { }); } - public fromJSON(json: JsonWebKey) { + public fromJSON(json: JsonWebKey): this { if (!json.d) { throw new core.OperationError(`Cannot get private data from JWK. Property 'd' is required`); } @@ -33,7 +33,7 @@ export class EdPrivateKey extends CryptoKey implements IJsonConvertible { } const hexPrivateKey = Convert.ToHex(Convert.FromBase64Url(json.d)); - if (true || /^ed/i.test(json.crv)) { + if (/^ed/i.test(json.crv)) { // const eddsa = new elliptic.eddsa(json.crv.toLowerCase()); const eddsa = new elliptic.eddsa("ed25519"); this.data = eddsa.keyFromSecret(hexPrivateKey); diff --git a/src/mechs/ed/public_key.ts b/src/mechs/ed/public_key.ts index 4c6cf08..7c50903 100644 --- a/src/mechs/ed/public_key.ts +++ b/src/mechs/ed/public_key.ts @@ -1,20 +1,18 @@ -import { AsnConvert } from "@peculiar/asn1-schema"; import { IJsonConvertible } from "@peculiar/json-schema"; import * as elliptic from "elliptic"; import { Convert } from "pvtsutils"; import * as core from "webcrypto-core"; import { CryptoKey } from "../../key"; -import { getOidByNamedCurve } from "./helper"; export class EdPublicKey extends CryptoKey implements IJsonConvertible { public algorithm!: EcKeyAlgorithm; public constructor(algorithm: EcKeyAlgorithm, extractable: boolean, usages: KeyUsage[], public data: EllipticJS.EllipticKeyPair) { - super(algorithm, extractable, "public", usages) + super(algorithm, extractable, "public", usages); } - public toJSON() { + public toJSON(): JsonWebKey { const json: JsonWebKey = { kty: "OKP", crv: this.algorithm.namedCurve, @@ -27,7 +25,7 @@ export class EdPublicKey extends CryptoKey implements IJsonConvertible { }); } - public fromJSON(json: JsonWebKey) { + public fromJSON(json: JsonWebKey): this { if (!json.crv) { throw new core.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); } diff --git a/src/mechs/hmac/hmac.ts b/src/mechs/hmac/hmac.ts index 648122b..11d20a3 100644 --- a/src/mechs/hmac/hmac.ts +++ b/src/mechs/hmac/hmac.ts @@ -76,9 +76,10 @@ export class HmacProvider extends core.HmacProvider { public async onExportKey(format: KeyFormat, key: HmacCryptoKey): Promise { switch (format.toLowerCase()) { - case "jwk": + case "jwk": { const jwk = JsonSerializer.toJSON(key) as JsonWebKey; return jwk; + } case "raw": return new Uint8Array(key.data).buffer; default: @@ -86,7 +87,7 @@ export class HmacProvider extends core.HmacProvider { } } - public checkCryptoKey(key: CryptoKey, keyUsage?: KeyUsage) { + public checkCryptoKey(key: CryptoKey, keyUsage?: KeyUsage): void { super.checkCryptoKey(key, keyUsage); if (!(key instanceof HmacCryptoKey)) { throw new TypeError("key: Is not HMAC CryptoKey"); diff --git a/src/mechs/hmac/key.ts b/src/mechs/hmac/key.ts index 72fd5d5..74f8205 100644 --- a/src/mechs/hmac/key.ts +++ b/src/mechs/hmac/key.ts @@ -26,7 +26,7 @@ export class HmacCryptoKey extends CryptoKey { protected readonly kty: string = "oct"; @JsonProp({ type: JsonPropTypes.String }) - protected get alg() { + protected get alg(): string { const hash = this.algorithm.hash.name.toUpperCase(); return `HS${hash.replace("SHA-", "")}`; } @@ -35,13 +35,13 @@ export class HmacCryptoKey extends CryptoKey { // nothing, cause set is needed for json-schema, but is not used by module } - constructor() + constructor(); constructor( algorithm: KeyAlgorithm, extractable: boolean, usages: KeyUsage[], data: Uint8Array, - ) + ); constructor( algorithm = { name: "HMAC" }, extractable = false, diff --git a/src/mechs/rsa/crypto.ts b/src/mechs/rsa/crypto.ts index 28a50a1..b5d85ff 100644 --- a/src/mechs/rsa/crypto.ts +++ b/src/mechs/rsa/crypto.ts @@ -93,7 +93,7 @@ export class RsaCrypto { return key; } - public static randomNonZeroValues(data: Uint8Array) { + public static randomNonZeroValues(data: Uint8Array): Uint8Array { data = nativeCrypto.getRandomValues(data); return data.map((n) => { while (!n) { @@ -103,7 +103,7 @@ export class RsaCrypto { }); } - private static exportPkcs8Key(key: RsaCryptoKey) { + private static exportPkcs8Key(key: RsaCryptoKey): ArrayBuffer { const keyInfo = new core.asn1.PrivateKeyInfo(); keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; keyInfo.privateKeyAlgorithm.parameters = null; @@ -112,19 +112,19 @@ export class RsaCrypto { return AsnConvert.serialize(keyInfo); } - private static importPkcs8Key(data: ArrayBuffer) { + private static importPkcs8Key(data: ArrayBuffer): AsmCryptoRsaKey { const keyInfo = AsnConvert.parse(data, core.asn1.PrivateKeyInfo); const privateKey = AsnConvert.parse(keyInfo.privateKey, core.asn1.RsaPrivateKey); return this.importAsmKey(privateKey); } - private static importSpkiKey(data: ArrayBuffer) { + private static importSpkiKey(data: ArrayBuffer): AsmCryptoRsaKey { const keyInfo = AsnConvert.parse(data, core.asn1.PublicKeyInfo); const publicKey = AsnConvert.parse(keyInfo.publicKey, core.asn1.RsaPublicKey); return this.importAsmKey(publicKey); } - private static exportSpkiKey(key: RsaCryptoKey) { + private static exportSpkiKey(key: RsaCryptoKey): ArrayBuffer { const publicKey = new core.asn1.RsaPublicKey(); publicKey.modulus = key.data[0].buffer; publicKey.publicExponent = key.data[1][1] === 1 @@ -139,7 +139,7 @@ export class RsaCrypto { return AsnConvert.serialize(keyInfo); } - private static importJwkKey(data: JsonWebKey) { + private static importJwkKey(data: JsonWebKey): AsmCryptoRsaKey { let key: core.asn1.RsaPrivateKey | core.asn1.RsaPublicKey; if (data.d) { // private @@ -151,7 +151,7 @@ export class RsaCrypto { return this.importAsmKey(key); } - private static exportJwkKey(key: RsaCryptoKey) { + private static exportJwkKey(key: RsaCryptoKey): JsonWebKey { const asnKey = this.exportAsmKey(key.data); const jwk = JsonSerializer.toJSON(asnKey) as JsonWebKey; @@ -163,11 +163,12 @@ export class RsaCrypto { return jwk; } - private static getJwkAlgorithm(algorithm: RsaHashedKeyAlgorithm) { + private static getJwkAlgorithm(algorithm: RsaHashedKeyAlgorithm): string { switch (algorithm.name.toUpperCase()) { - case "RSA-OAEP": + case "RSA-OAEP": { const mdSize = /(\d+)$/.exec(algorithm.hash.name)![1]; return `RSA-OAEP${mdSize !== "1" ? `-${mdSize}` : ""}`; + } case "RSASSA-PKCS1-V1_5": return `RS${/(\d+)$/.exec(algorithm.hash.name)![1]}`; case "RSA-PSS": @@ -203,7 +204,7 @@ export class RsaCrypto { return key; } - private static importAsmKey(key: core.asn1.RsaPrivateKey | core.asn1.RsaPublicKey) { + private static importAsmKey(key: core.asn1.RsaPrivateKey | core.asn1.RsaPublicKey): AsmCryptoRsaKey { const expPadding = new Uint8Array(4 - key.publicExponent.byteLength); const asmKey: AsmCryptoRsaKey = [ new Uint8Array(key.modulus), diff --git a/src/mechs/rsa/rsa_es.ts b/src/mechs/rsa/rsa_es.ts index f9ff47a..ef607ab 100644 --- a/src/mechs/rsa/rsa_es.ts +++ b/src/mechs/rsa/rsa_es.ts @@ -1,7 +1,6 @@ import * as asmCrypto from "asmcrypto.js"; import { Convert } from "pvtsutils"; import * as core from "webcrypto-core"; -import { Crypto } from "../../crypto"; import { RsaCrypto } from "./crypto"; import { RsaCryptoKey } from "./key"; @@ -21,7 +20,7 @@ export class RsaEsProvider extends core.ProviderCrypto { return RsaCrypto.generateKey(algorithm, extractable, keyUsages); } - public checkGenerateKeyParams(algorithm: RsaKeyGenParams) { + public checkGenerateKeyParams(algorithm: RsaKeyGenParams): void { // public exponent this.checkRequiredProperty(algorithm, "publicExponent"); if (!(algorithm.publicExponent && algorithm.publicExponent instanceof Uint8Array)) { @@ -110,9 +109,4 @@ export class RsaEsProvider extends core.ProviderCrypto { super.checkCryptoKey(key, keyUsage); RsaCrypto.checkCryptoKey(key); } - - private async prepareSignData(algorithm: RsaPkcs1SignParams, data: ArrayBuffer) { - const crypto = new Crypto(); - return crypto.subtle.digest(algorithm.hash, data); - } } diff --git a/src/mechs/rsa/rsa_oaep.ts b/src/mechs/rsa/rsa_oaep.ts index c96bbdc..e229c2a 100644 --- a/src/mechs/rsa/rsa_oaep.ts +++ b/src/mechs/rsa/rsa_oaep.ts @@ -31,7 +31,7 @@ export class RsaOaepProvider extends core.RsaOaepProvider { RsaCrypto.checkCryptoKey(key); } - private cipher(algorithm: RsaOaepParams, key: RsaCryptoKey, data: ArrayBuffer) { + private cipher(algorithm: RsaOaepParams, key: RsaCryptoKey, data: ArrayBuffer): ArrayBuffer { const digest = ShaCrypto.getDigest(key.algorithm.hash.name); let label: Uint8Array | undefined; if (algorithm.label) { diff --git a/src/mechs/sha/crypto.ts b/src/mechs/sha/crypto.ts index 2a38b2a..de3a972 100644 --- a/src/mechs/sha/crypto.ts +++ b/src/mechs/sha/crypto.ts @@ -3,7 +3,7 @@ import * as core from "webcrypto-core"; export class ShaCrypto { - public static getDigest(name: string) { + public static getDigest(name: string): asmCrypto.Sha1 | asmCrypto.Sha256 | asmCrypto.Sha512 { switch (name) { case "SHA-1": return new asmCrypto.Sha1(); diff --git a/src/native.ts b/src/native.ts index c3693a6..c7663e7 100644 --- a/src/native.ts +++ b/src/native.ts @@ -17,7 +17,7 @@ try { // Safari throws error on crypto.webkitSubtle in Worker } -export function setCrypto(crypto: Crypto) { +export function setCrypto(crypto: Crypto): void { nativeCrypto = crypto; nativeSubtle = crypto.subtle; } diff --git a/src/subtle.ts b/src/subtle.ts index 7f83e44..0bbf2fe 100644 --- a/src/subtle.ts +++ b/src/subtle.ts @@ -106,57 +106,57 @@ export class SubtleCrypto extends core.SubtleCrypto { //#endregion } - public async digest(...args: any[]) { + public async digest(...args: any[]): Promise { return this.wrapNative("digest", ...args); } - public async importKey(...args: any[]) { + public async importKey(...args: any[]): Promise { this.fixFirefoxEcImportPkcs8(args); return this.wrapNative("importKey", ...args); } - public async exportKey(...args: any[]) { + public async exportKey(...args: any[]): Promise { return await this.fixFirefoxEcExportPkcs8(args) || await this.wrapNative("exportKey", ...args); } - public async generateKey(...args: any[]) { + public async generateKey(...args: any[]): Promise { return this.wrapNative("generateKey", ...args); } - public async sign(...args: any[]) { + public async sign(...args: any[]): Promise { return this.wrapNative("sign", ...args); } - public async verify(...args: any[]) { + public async verify(...args: any[]): Promise { return this.wrapNative("verify", ...args); } - public async encrypt(...args: any[]) { + public async encrypt(...args: any[]): Promise { return this.wrapNative("encrypt", ...args); } - public async decrypt(...args: any[]) { + public async decrypt(...args: any[]): Promise { return this.wrapNative("decrypt", ...args); } - public async wrapKey(...args: any[]) { + public async wrapKey(...args: any[]): Promise { return this.wrapNative("wrapKey", ...args); } - public async unwrapKey(...args: any[]) { + public async unwrapKey(...args: any[]): Promise { return this.wrapNative("unwrapKey", ...args); } - public async deriveBits(...args: any[]) { + public async deriveBits(...args: any[]): Promise { return this.wrapNative("deriveBits", ...args); } - public async deriveKey(...args: any[]) { + public async deriveKey(...args: any[]): Promise { return this.wrapNative("deriveKey", ...args); } - private async wrapNative(method: SubtleMethods, ...args: any[]) { + private async wrapNative(method: SubtleMethods, ...args: any[]): Promise { if (~["generateKey", "unwrapKey", "deriveKey", "importKey"].indexOf(method)) { this.fixAlgorithmName(args); } @@ -166,6 +166,7 @@ export class SubtleCrypto extends core.SubtleCrypto { const nativeArgs = this.fixNativeArguments(method, args); Debug.info(`Call native '${method}' method`, nativeArgs); + // eslint-disable-next-line prefer-spread const res = await nativeSubtle[method].apply(nativeSubtle, nativeArgs); return this.fixNativeResult(method, args, res); @@ -238,7 +239,7 @@ export class SubtleCrypto extends core.SubtleCrypto { throw new Error("Incorrect type of 'method'. Must be 'function'."); } - private fixNativeArguments(method: SubtleMethods, args: any[]) { + private fixNativeArguments(method: SubtleMethods, args: any[]): any[] { const res = [...args]; if (method === "importKey") { if (this.browserInfo.name === Browser.IE && res[0]?.toLowerCase?.() === "jwk" && !BufferSourceConverter.isBufferSource(res[1])) { @@ -343,7 +344,7 @@ export class SubtleCrypto extends core.SubtleCrypto { return key; } - private async castKey(key: core.NativeCryptoKey) { + private async castKey(key: core.NativeCryptoKey): Promise { Debug.info("Cast native CryptoKey to linter key.", key); if (!key.extractable) { throw new Error("Cannot cast unextractable crypto key"); @@ -359,7 +360,7 @@ export class SubtleCrypto extends core.SubtleCrypto { * Fixes name of the algorithms. Edge doesn't normilize algorithm names in keys * @param args */ - private fixAlgorithmName(args: any[]) { + private fixAlgorithmName(args: any[]): void { if (this.browserInfo.name === Browser.Edge) { for (let i = 0; i < args.length; i++) { const arg = args[0]; @@ -390,7 +391,7 @@ export class SubtleCrypto extends core.SubtleCrypto { /** * Firefox doesn't support import PKCS8 key for ECDSA/ECDH */ - private fixFirefoxEcImportPkcs8(args: any[]) { + private fixFirefoxEcImportPkcs8(args: any[]): void { const preparedAlgorithm = this.prepareAlgorithm(args[2]) as EcKeyImportParams; const algName = preparedAlgorithm.name.toUpperCase(); if (this.browserInfo.name === Browser.Firefox @@ -419,7 +420,7 @@ export class SubtleCrypto extends core.SubtleCrypto { /** * Firefox doesn't support export PKCS8 key for ECDSA/ECDH */ - private async fixFirefoxEcExportPkcs8(args: any[]) { + private async fixFirefoxEcExportPkcs8(args: any[]): Promise { try { if (this.browserInfo.name === Browser.Firefox && args[0] === "pkcs8" diff --git a/src/wrapped_native_key.ts b/src/wrapped_native_key.ts index 0aac790..4b52604 100644 --- a/src/wrapped_native_key.ts +++ b/src/wrapped_native_key.ts @@ -18,7 +18,7 @@ export class WrappedNativeCryptoKey extends CryptoKey { } // @internal - public getNative() { + public getNative(): CryptoKey { return this.#nativeKey; } diff --git a/test/aes.ts b/test/aes.ts index c523a76..8f1352d 100644 --- a/test/aes.ts +++ b/test/aes.ts @@ -1,10 +1,10 @@ import { Convert } from "pvtsutils"; import { Browser } from "../src/helper"; -import { browser, testCrypto } from "./utils"; +import { browser, liner, testCrypto } from "./utils"; context("AES", () => { - testCrypto(crypto, [ + testCrypto(liner, [ //#region AES-CBC { name: "AES-128-CBC", diff --git a/test/des.ts b/test/des.ts index 8ec3742..24fdb7c 100644 --- a/test/des.ts +++ b/test/des.ts @@ -1,11 +1,10 @@ -import * as assert from "assert"; import { Convert } from "pvtsutils"; import * as core from "webcrypto-core"; -import { testCrypto } from "./utils"; +import { liner, testCrypto } from "./utils"; context("DES", () => { - testCrypto(crypto, [ + testCrypto(liner, [ { name: "DES-CBC", actions: { diff --git a/test/ec.ts b/test/ec.ts index f832dab..6bb3529 100644 --- a/test/ec.ts +++ b/test/ec.ts @@ -1,11 +1,11 @@ import * as assert from "assert"; import { Convert } from "pvtsutils"; import { Browser } from "../src/helper"; -import { browser, ITestGenerateKeyAction, testCrypto } from "./utils"; +import { browser, ITestGenerateKeyAction, liner, testCrypto } from "./utils"; context("EC", () => { - testCrypto(crypto, [ + testCrypto(liner, [ { name: "ECDSA", actions: { @@ -542,11 +542,11 @@ context("EC", () => { it("sig", async () => { const data = new Uint8Array(10); - const keys = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "brainpoolP512r1" }, false, ["sign", "verify"]); - const spki = await crypto.subtle.exportKey("spki", keys.publicKey); + const keys = await liner.subtle.generateKey({ name: "ECDSA", namedCurve: "brainpoolP512r1" }, false, ["sign", "verify"]); + await liner.subtle.exportKey("spki", keys.publicKey); - const signature = await crypto.subtle.sign({ ...keys.privateKey.algorithm, hash: "SHA-256" }, keys.privateKey, data); - const ok = await crypto.subtle.verify({name: "ECDSA", hash: "SHA-256"}, keys.publicKey, signature, data); + const signature = await liner.subtle.sign({ ...keys.privateKey.algorithm, hash: "SHA-256" }, keys.privateKey, data); + const ok = await liner.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, keys.publicKey, signature, data); assert.strictEqual(ok, true); }); diff --git a/test/ed.ts b/test/ed.ts index bfca532..00d086d 100644 --- a/test/ed.ts +++ b/test/ed.ts @@ -1,5 +1,4 @@ import * as assert from "assert"; -import { Convert } from "pvtsutils"; import { Crypto as NodeCrypto } from "@peculiar/webcrypto"; import { Crypto } from "../src"; diff --git a/test/hmac.ts b/test/hmac.ts index 383cfe0..a631d5a 100644 --- a/test/hmac.ts +++ b/test/hmac.ts @@ -1,9 +1,9 @@ import { Convert } from "pvtsutils"; -import { ITestGenerateKeyAction, testCrypto } from "./utils"; +import { ITestGenerateKeyAction, liner, testCrypto } from "./utils"; context("HMAC", () => { - testCrypto(crypto, [ + testCrypto(liner, [ { name: "HMAC", actions: { diff --git a/test/pbkdf.ts b/test/pbkdf.ts index 1254815..6809426 100644 --- a/test/pbkdf.ts +++ b/test/pbkdf.ts @@ -1,9 +1,9 @@ import { Convert } from "pvtsutils"; -import { testCrypto } from "./utils"; +import { liner, testCrypto } from "./utils"; context("PBKDF", () => { - testCrypto(crypto, [ + testCrypto(liner, [ { name: "PBKDF2", actions: { diff --git a/test/rsa.ts b/test/rsa.ts index c9533a3..06965d6 100644 --- a/test/rsa.ts +++ b/test/rsa.ts @@ -1,17 +1,17 @@ import { Convert } from "pvtsutils"; import { Browser } from "../src/helper"; -import { browser, ITestGenerateKeyAction, testCrypto } from "./utils"; +import { browser, ITestGenerateKeyAction, liner, testCrypto } from "./utils"; context("RSA", () => { - testCrypto(crypto, [ + testCrypto(liner, [ // RSASSA-PKCS1-v1_5 { name: "RSASSA-PKCS1-v1_5", actions: { - generateKey: (() => { + generateKey: ((): ITestGenerateKeyAction[] => { const res: ITestGenerateKeyAction[] = []; - ["SHA-1", "SHA-256"].forEach((hash) => + ["SHA-1", "SHA-256"].forEach((_hash) => ["SHA-1", "SHA-256", "SHA-512"].forEach((hash) => [new Uint8Array([3]), new Uint8Array([1, 0, 1])].forEach((publicExponent) => [1024, 2048].forEach((modulusLength) => { diff --git a/test/sha.ts b/test/sha.ts index 2d21780..c4dabe5 100644 --- a/test/sha.ts +++ b/test/sha.ts @@ -1,12 +1,12 @@ import { Convert } from "pvtsutils"; import { ShakeParams } from "webcrypto-core"; -import { testCrypto } from "./utils"; +import { liner, testCrypto } from "./utils"; context("SHA", () => { const data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); - testCrypto(crypto, [ + testCrypto(liner, [ { name: "SHA", actions: { diff --git a/test/utils/helper.ts b/test/utils/helper.ts index 1b84e99..c4f49da 100644 --- a/test/utils/helper.ts +++ b/test/utils/helper.ts @@ -98,7 +98,7 @@ export interface ITestParams extends ITestMochaFunction { actions: ITestActions; } -async function getKeys(crypto: Crypto, key: IImportKeyParams | IImportKeyPairParams) { +async function getKeys(crypto: Crypto, key: IImportKeyParams | IImportKeyPairParams): Promise { const keys = {} as CryptoKeyPair; if ("privateKey" in key) { keys.privateKey = await crypto.subtle.importKey( @@ -127,7 +127,7 @@ async function getKeys(crypto: Crypto, key: IImportKeyParams | IImportKeyPairPar function wrapSkipOnly(item: Mocha.TestFunction, params: ITestMochaFunction): Mocha.PendingTestFunction; function wrapSkipOnly(item: Mocha.SuiteFunction, params: ITestMochaFunction): Mocha.PendingSuiteFunction; -function wrapSkipOnly(item: Mocha.TestFunction | Mocha.SuiteFunction, params: ITestMochaFunction) { +function wrapSkipOnly(item: Mocha.TestFunction | Mocha.SuiteFunction, params: ITestMochaFunction): Mocha.PendingTestFunction | Mocha.PendingSuiteFunction { return params.skip ? item.skip : params.only @@ -135,10 +135,10 @@ function wrapSkipOnly(item: Mocha.TestFunction | Mocha.SuiteFunction, params: IT : item; } -async function wrapTest(promise: () => Promise, action: ITestAction, index: number) { +async function wrapTest(promise: () => Promise, action: ITestAction, index: number): Promise { wrapSkipOnly(it, action)(action.name || `#${index + 1}`, async () => { if (action.error) { - if (typeof(action.error) === "boolean") { + if (typeof (action.error) === "boolean") { await assert.rejects(promise()); } else { await assert.rejects(promise(), action.error); @@ -149,7 +149,7 @@ async function wrapTest(promise: () => Promise, action: ITestAction, index }); } -export function testCrypto(crypto: Crypto, params: ITestParams[]) { +export function testCrypto(crypto: Crypto, params: ITestParams[]): void { params.forEach((param) => { wrapSkipOnly(context, param)(param.name, () => { //#region Generate key diff --git a/test/utils/index.ts b/test/utils/index.ts index ecc848b..61d6648 100644 --- a/test/utils/index.ts +++ b/test/utils/index.ts @@ -1,2 +1,2 @@ -import "./init"; +export * from "./init"; export * from "./helper"; diff --git a/test/utils/init.ts b/test/utils/init.ts index 9fe4f6d..5ec15e7 100644 --- a/test/utils/init.ts +++ b/test/utils/init.ts @@ -6,7 +6,7 @@ const nativeGenerateKey = crypto.subtle.generateKey; const nativeExportKey = crypto.subtle.exportKey; // asmCrypto doesn't have key generation function and uses native generateKey with RSA-PSS -crypto.subtle.generateKey = async function (...args: any[]) { +crypto.subtle.generateKey = async function (...args: any[]): Promise { if (args[0]?.name !== "RSA-PSS") { throw new Error("Function is broken for test cases"); } @@ -14,7 +14,7 @@ crypto.subtle.generateKey = async function (...args: any[]) { }; // asmCrypto doesn't have key generation function and uses native exportKey with RSA-PSS -crypto.subtle.exportKey = async function (...args: any[]) { +crypto.subtle.exportKey = async function (...args: any[]): Promise { if (!( (args[0] === "pkcs8" || args[0] === "spki") @@ -34,12 +34,12 @@ crypto.subtle.exportKey = async function (...args: any[]) { "importKey", "digest", ].forEach((o) => { - crypto.subtle[o] = async () => { + crypto.subtle[o] = async (): Promise => { throw new Error("Function is broken for test cases"); }; }); // set native crypto -setCrypto(crypto as globalThis.Crypto); +setCrypto(crypto); -global["crypto"] = new WebCrypto(); +export const liner = new WebCrypto();