From 7c4a981434d25caaca5987a6af334053325c6101 Mon Sep 17 00:00:00 2001 From: fyears Date: Fri, 5 Nov 2021 01:21:58 +0800 Subject: [PATCH] allow tests --- package.json | 10 ++++++++-- src/encrypt.ts | 6 ++++++ tests/test-encrypt.ts | 21 +++++++++++++++++++++ webpack.config.js | 1 + 4 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 tests/test-encrypt.ts diff --git a/package.json b/package.json index 576ae66..7df6eab 100644 --- a/package.json +++ b/package.json @@ -6,18 +6,24 @@ "dev": "webpack --mode development --watch", "build": "webpack --mode production", "format": "npx prettier --write .", - "clean": "npx rimraf main.js" + "clean": "npx rimraf main.js", + "test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/register -r jsdom-global/register 'tests/**/*.ts'" }, "source": "main.ts", "keywords": [], "author": "", "license": "Apache-2.0", "devDependencies": { - "@types/node": "^14.14.37", + "@types/chai": "^4.2.22", "@types/mime-types": "^2.1.1", + "@types/mocha": "^9.0.0", + "@types/node": "^14.14.37", + "chai": "^4.3.4", + "mocha": "^9.1.3", "prettier": "^2.4.1", "terser-webpack-plugin": "^5.2.4", "ts-loader": "^9.2.6", + "ts-node": "^10.4.0", "tslib": "^2.2.0", "typescript": "^4.4.4", "webdav-server": "^2.6.2", diff --git a/src/encrypt.ts b/src/encrypt.ts index 50d6e64..d5e58ca 100644 --- a/src/encrypt.ts +++ b/src/encrypt.ts @@ -1,6 +1,12 @@ import * as base32 from "hi-base32"; import { bufferToArrayBuffer, arrayBufferToBuffer } from "./misc"; +if (window === undefined) { + global.window = { + crypto: require("crypto").webcrypto, + } as any; +} + const DEFAULT_ITER = 10000; const getKeyIVFromPassword = async ( diff --git a/tests/test-encrypt.ts b/tests/test-encrypt.ts new file mode 100644 index 0000000..a7a805f --- /dev/null +++ b/tests/test-encrypt.ts @@ -0,0 +1,21 @@ +const webcrypto = require("crypto").webcrypto; + +import { expect } from "chai"; +import { encryptStringToBase32 } from "../src/encrypt"; + +describe("Encryption tests", () => { + beforeEach(function () { + const window = { + crypto: webcrypto, + }; + + global.window = window as any; + }); + + it("should encrypt string", async () => { + const k = "dkjdhkfhdkjgsdklxxd"; + const password = "hey"; + //console.log(window.crypto.getRandomValues) + expect(await encryptStringToBase32(k, password)).to.not.equal(k); + }); +}); diff --git a/webpack.config.js b/webpack.config.js index 7c17227..b450699 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -38,6 +38,7 @@ module.exports = { // console: require.resolve("console-browserify"), // constants: require.resolve("constants-browserify"), // crypto: require.resolve("crypto-browserify"), + crypto: false, // deliberately set to false, since we use webcrypto here // domain: require.resolve("domain-browser"), // events: require.resolve("events"), // http: require.resolve("stream-http"),