Update to Mocha v10 in tests, declare lib as module and add exports to package.json

Mocha v10 requires the lib to be esm compliant.
ESM mandates the use of file extensions in imports, so to minimize the
changes (for now), we rely on the flag `experimental-specifier-resolution=node`
and on `ts-node` (needed only for Node 20).

Breaking changes:
downstream bundlers might be affected by the package.json changes depending on
how they load the library.
NB: legacy package.json entrypoints are still available.
This commit is contained in:
larabr 2023-05-09 18:45:46 +02:00
parent 3520a357f5
commit d49d92e5cb
66 changed files with 1710 additions and 1373 deletions

6
.mocharc.json Normal file
View File

@ -0,0 +1,6 @@
{
"node-option": [
"experimental-specifier-resolution=node",
"loader=ts-node/esm"
]
}

View File

@ -1,5 +1,5 @@
{ {
"name": "openpgp-lightweight", "name": "openpgp-lightweight",
"main": "../dist/lightweight/openpgp.min.mjs", "browser": "../dist/lightweight/openpgp.min.mjs",
"types": "../openpgp.d.ts" "types": "../openpgp.d.ts"
} }

2267
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,13 +13,26 @@
"gpg", "gpg",
"openpgp" "openpgp"
], ],
"main": "dist/node/openpgp.min.js", "main": "dist/node/openpgp.min.cjs",
"module": "dist/node/openpgp.min.mjs", "module": "dist/node/openpgp.min.mjs",
"browser": { "browser": {
"./dist/node/openpgp.min.js": "./dist/openpgp.min.js", "./dist/node/openpgp.min.cjs": "./dist/openpgp.min.js",
"./dist/node/openpgp.min.mjs": "./dist/openpgp.min.mjs" "./dist/node/openpgp.min.mjs": "./dist/openpgp.min.mjs"
}, },
"exports": {
".": {
"types": "./openpgp.d.ts",
"import": "./dist/node/openpgp.mjs",
"require": "./dist/node/openpgp.min.cjs",
"browser": "./dist/openpgp.min.mjs"
},
"./lightweight": {
"types": "../openpgp.d.ts",
"browser": "./dist/lightweight/openpgp.min.mjs"
}
},
"types": "openpgp.d.ts", "types": "openpgp.d.ts",
"type": "module",
"directories": { "directories": {
"lib": "src" "lib": "src"
}, },
@ -28,27 +41,22 @@
"lightweight/", "lightweight/",
"openpgp.d.ts" "openpgp.d.ts"
], ],
"esm": {
"cjs": {
"dedefault": true
}
},
"scripts": { "scripts": {
"build": "rollup --config", "build": "rollup --config",
"build-test": "npm run build --build-only=test", "build-test": "npm run build --build-only=test",
"prepare": "npm run build", "prepare": "npm run build",
"test": "mocha --require esm --timeout 120000 test/unittests.js", "test": "mocha --timeout 120000 test/unittests.js",
"test-type-definitions": "tsc test/typescript/definitions.ts && node test/typescript/definitions.js", "test-type-definitions": "ts-node --esm test/typescript/definitions.ts",
"benchmark-time": "node test/benchmarks/time.js", "benchmark-time": "node test/benchmarks/time.js",
"benchmark-memory-usage": "node --require esm test/benchmarks/memory_usage.js", "benchmark-memory-usage": "node test/benchmarks/memory_usage.js",
"start": "http-server", "start": "http-server",
"prebrowsertest": "npm run build-test", "prebrowsertest": "npm run build-test",
"browsertest": "npm start -- -o test/unittests.html", "browsertest": "npm start -- -o test/unittests.html",
"test-browser": "karma start test/karma.conf.js", "test-browser": "karma start test/karma.conf.cjs",
"test-browserstack": "karma start test/karma.conf.js --browsers bs_safari_latest,bs_ios_14,bs_safari_13_1", "test-browserstack": "karma start test/karma.conf.cjs --browsers bs_safari_latest,bs_ios_14,bs_safari_13_1",
"coverage": "nyc npm test", "coverage": "nyc npm test",
"lint": "eslint .", "lint": "eslint .",
"docs": "jsdoc --configure .jsdocrc.js --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME", "docs": "jsdoc --configure .jsdocrc.cjs --destination docs --recurse README.md src && printf '%s' 'docs.openpgpjs.org' > docs/CNAME",
"preversion": "rm -rf dist docs node_modules && npm ci && npm test", "preversion": "rm -rf dist docs node_modules && npm ci && npm test",
"version": "npm run docs && git add -A docs", "version": "npm run docs && git add -A docs",
"postversion": "git push && git push --tags && npm publish" "postversion": "git push && git push --tags && npm publish"
@ -56,20 +64,22 @@
"devDependencies": { "devDependencies": {
"@openpgp/asmcrypto.js": "^2.3.2", "@openpgp/asmcrypto.js": "^2.3.2",
"@openpgp/elliptic": "^6.5.1", "@openpgp/elliptic": "^6.5.1",
"@openpgp/jsdoc": "^3.6.4", "@openpgp/jsdoc": "^3.6.11",
"@openpgp/pako": "^1.0.12", "@openpgp/pako": "^1.0.12",
"@openpgp/seek-bzip": "^1.0.5-git", "@openpgp/seek-bzip": "^1.0.5-git",
"@openpgp/tweetnacl": "^1.0.3", "@openpgp/tweetnacl": "^1.0.3",
"@openpgp/web-stream-tools": "^0.0.13", "@openpgp/web-stream-tools": "^0.0.14",
"@rollup/plugin-commonjs": "^11.1.0", "@rollup/plugin-alias": "^5.0.0",
"@rollup/plugin-node-resolve": "^7.1.3", "@rollup/plugin-commonjs": "^24.0.1",
"@rollup/plugin-replace": "^2.3.2", "@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-terser": "^0.4.0",
"@rollup/plugin-wasm": "^6.1.2", "@rollup/plugin-wasm": "^6.1.2",
"@types/chai": "^4.2.14", "@types/chai": "^4.2.14",
"argon2id": "^1.0.1", "argon2id": "^1.0.1",
"benchmark": "^2.1.4", "benchmark": "^2.1.4",
"bn.js": "^4.11.8", "bn.js": "^4.11.8",
"chai": "^4.3.6", "chai": "^4.3.7",
"chai-as-promised": "^7.1.1", "chai-as-promised": "^7.1.1",
"email-addresses": "3.1.0", "email-addresses": "3.1.0",
"eslint": "^8.34.0", "eslint": "^8.34.0",
@ -77,7 +87,6 @@
"eslint-config-airbnb-base": "^15.0.0", "eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-chai-friendly": "^0.7.2", "eslint-plugin-chai-friendly": "^0.7.2",
"eslint-plugin-import": "^2.27.5", "eslint-plugin-import": "^2.27.5",
"esm": "^3.2.25",
"hash.js": "^1.1.3", "hash.js": "^1.1.3",
"http-server": "^14.1.1", "http-server": "^14.1.1",
"karma": "^6.4.0", "karma": "^6.4.0",
@ -87,12 +96,12 @@
"karma-mocha": "^2.0.1", "karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5", "karma-mocha-reporter": "^2.2.5",
"karma-webkit-launcher": "^2.1.0", "karma-webkit-launcher": "^2.1.0",
"mocha": "^8.4.0", "mocha": "^10.2.0",
"nyc": "^14.1.1", "nyc": "^14.1.1",
"playwright": "^1.30.0", "playwright": "^1.30.0",
"rollup": "^2.38.5", "rollup": "^2.79.1",
"rollup-plugin-terser": "^7.0.2",
"sinon": "^4.3.0", "sinon": "^4.3.0",
"ts-node": "^10.9.1",
"typescript": "^4.1.2", "typescript": "^4.1.2",
"web-streams-polyfill": "^3.2.0" "web-streams-polyfill": "^3.2.0"
}, },

View File

@ -2,16 +2,18 @@
import { builtinModules } from 'module'; import { builtinModules } from 'module';
import alias from '@rollup/plugin-alias';
import resolve from '@rollup/plugin-node-resolve'; import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'; import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace'; import replace from '@rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser'; import terser from '@rollup/plugin-terser';
import { wasm } from '@rollup/plugin-wasm'; import { wasm } from '@rollup/plugin-wasm';
import pkg from './package.json'; import pkg from './package.json';
const nodeDependencies = Object.keys(pkg.dependencies); const nodeDependencies = Object.keys(pkg.dependencies);
const nodeBuiltinModules = builtinModules.concat(['module']);
const wasmOptions = { const wasmOptions = {
node: { targetEnv: 'node' }, node: { targetEnv: 'node' },
browser: { targetEnv: 'browser', maxFileSize: undefined } // always inlline (our wasm files are small) browser: { targetEnv: 'browser', maxFileSize: undefined } // always inlline (our wasm files are small)
@ -47,6 +49,7 @@ const terserOptions = {
export default Object.assign([ export default Object.assign([
{ {
input: 'src/index.js', input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [ output: [
{ file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro }, { file: 'dist/openpgp.js', format: 'iife', name: pkg.name, banner, intro },
{ file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true }, { file: 'dist/openpgp.min.js', format: 'iife', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
@ -59,11 +62,11 @@ export default Object.assign([
browser: true browser: true
}), }),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies)
}), }),
replace({ replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`, 'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
'require(': 'void(', "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', ''] delimiters: ['', '']
}), }),
wasm(wasmOptions.browser) wasm(wasmOptions.browser)
@ -72,10 +75,10 @@ export default Object.assign([
{ {
input: 'src/index.js', input: 'src/index.js',
inlineDynamicImports: true, inlineDynamicImports: true,
external: builtinModules.concat(nodeDependencies), external: nodeBuiltinModules.concat(nodeDependencies),
output: [ output: [
{ file: 'dist/node/openpgp.js', format: 'cjs', name: pkg.name, banner, intro }, { file: 'dist/node/openpgp.cjs', format: 'cjs', name: pkg.name, banner, intro },
{ file: 'dist/node/openpgp.min.js', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true }, { file: 'dist/node/openpgp.min.cjs', format: 'cjs', name: pkg.name, banner, intro, plugins: [terser(terserOptions)], sourcemap: true },
{ file: 'dist/node/openpgp.mjs', format: 'es', banner, intro }, { file: 'dist/node/openpgp.mjs', format: 'es', banner, intro },
{ file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true } { file: 'dist/node/openpgp.min.mjs', format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
], ],
@ -90,6 +93,7 @@ export default Object.assign([
}, },
{ {
input: 'src/index.js', input: 'src/index.js',
external: nodeBuiltinModules.concat(nodeDependencies),
output: [ output: [
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'mjs'), format: 'es', banner, intro }, { dir: 'dist/lightweight', entryFileNames: 'openpgp.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'mjs'), format: 'es', banner, intro },
{ dir: 'dist/lightweight', entryFileNames: 'openpgp.min.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'min.mjs'), format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true } { dir: 'dist/lightweight', entryFileNames: 'openpgp.min.mjs', chunkFileNames: chunkInfo => getChunkFileName(chunkInfo, 'min.mjs'), format: 'es', banner, intro, plugins: [terser(terserOptions)], sourcemap: true }
@ -100,11 +104,11 @@ export default Object.assign([
browser: true browser: true
}), }),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies)
}), }),
replace({ replace({
'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`, 'OpenPGP.js VERSION': `OpenPGP.js ${pkg.version}`,
'require(': 'void(', "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
delimiters: ['', ''] delimiters: ['', '']
}), }),
wasm(wasmOptions.browser) wasm(wasmOptions.browser)
@ -116,17 +120,22 @@ export default Object.assign([
{ file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true } { file: 'test/lib/unittests-bundle.js', format: 'es', intro, sourcemap: true }
], ],
inlineDynamicImports: true, inlineDynamicImports: true,
external: ['../..', '../../..'], external: nodeBuiltinModules.concat(nodeDependencies),
plugins: [ plugins: [
alias({
entries: {
openpgp: `./dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs`
}
}),
resolve({ resolve({
browser: true browser: true
}), }),
commonjs({ commonjs({
ignore: builtinModules.concat(nodeDependencies) ignore: nodeBuiltinModules.concat(nodeDependencies),
requireReturnsDefault: 'preferred'
}), }),
replace({ replace({
"import openpgpjs from '../../..';": `import * as openpgpjs from '/dist/${process.env.npm_config_lightweight ? 'lightweight/' : ''}openpgp.mjs'; window.openpgp = openpgpjs;`, "import { createRequire } from 'module';": 'const createRequire = () => () => {}',
'require(': 'void(',
delimiters: ['', ''] delimiters: ['', '']
}), }),
wasm(wasmOptions.browser) wasm(wasmOptions.browser)

View File

@ -2,7 +2,6 @@
* @fileoverview This module implements AES-CMAC on top of * @fileoverview This module implements AES-CMAC on top of
* native AES-CBC using either the WebCrypto API or Node.js' crypto API. * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
* @module crypto/cmac * @module crypto/cmac
* @private
*/ */
import { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc'; import { AES_CBC } from '@openpgp/asmcrypto.js/dist_es8/aes/cbc';

View File

@ -19,7 +19,6 @@
* @fileoverview This module implements AES-EAX en/decryption on top of * @fileoverview This module implements AES-EAX en/decryption on top of
* native AES-CTR using either the WebCrypto API or Node.js' crypto API. * native AES-CTR using either the WebCrypto API or Node.js' crypto API.
* @module crypto/mode/eax * @module crypto/mode/eax
* @private
*/ */
import { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr'; import { AES_CTR } from '@openpgp/asmcrypto.js/dist_es8/aes/ctr';

View File

@ -1,7 +1,6 @@
/** /**
* @fileoverview Cipher modes * @fileoverview Cipher modes
* @module crypto/mode * @module crypto/mode
* @private
*/ */
import * as cfb from './cfb'; import * as cfb from './cfb';

View File

@ -280,7 +280,7 @@ async function nodeVerify(curve, hashAlgo, { r, s }, message, publicKey) {
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
const asn1 = nodeCrypto ? require('asn1.js') : undefined; const asn1 = nodeCrypto ? util.nodeRequire('asn1.js') : undefined;
const ECDSASignature = nodeCrypto ? const ECDSASignature = nodeCrypto ?
asn1.define('ECDSASignature', function() { asn1.define('ECDSASignature', function() {

View File

@ -30,7 +30,7 @@ import enums from '../../enums';
const webCrypto = util.getWebCrypto(); const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto(); const nodeCrypto = util.getNodeCrypto();
const asn1 = nodeCrypto ? require('asn1.js') : undefined; const asn1 = nodeCrypto ? util.nodeRequire('asn1.js') : undefined;
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
const RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () { const RSAPrivateKey = nodeCrypto ? asn1.define('RSAPrivateKey', function () {

View File

@ -1,6 +1,5 @@
/** /**
* @module key/Subkey * @module key/Subkey
* @private
*/ */
import enums from '../enums'; import enums from '../enums';

View File

@ -24,6 +24,7 @@
*/ */
import * as stream from '@openpgp/web-stream-tools'; import * as stream from '@openpgp/web-stream-tools';
import { createRequire } from 'module'; // Must be stripped in browser built
import { getBigInteger } from './biginteger'; import { getBigInteger } from './biginteger';
import enums from './enums'; import enums from './enums';
@ -39,6 +40,8 @@ const util = {
return typeof data === 'string' || data instanceof String; return typeof data === 'string' || data instanceof String;
}, },
nodeRequire: createRequire(import.meta.url),
isArray: function(data) { isArray: function(data) {
return data instanceof Array; return data instanceof Array;
}, },
@ -396,11 +399,11 @@ const util = {
* @returns {Object} The crypto module or 'undefined'. * @returns {Object} The crypto module or 'undefined'.
*/ */
getNodeCrypto: function() { getNodeCrypto: function() {
return require('crypto'); return this.nodeRequire('crypto');
}, },
getNodeZlib: function() { getNodeZlib: function() {
return require('zlib'); return this.nodeRequire('zlib');
}, },
/** /**
@ -409,7 +412,7 @@ const util = {
* @returns {Function} The Buffer constructor or 'undefined'. * @returns {Function} The Buffer constructor or 'undefined'.
*/ */
getNodeBuffer: function() { getNodeBuffer: function() {
return (require('buffer') || {}).Buffer; return (this.nodeRequire('buffer') || {}).Buffer;
}, },
getHardwareConcurrency: function() { getHardwareConcurrency: function() {
@ -417,7 +420,7 @@ const util = {
return navigator.hardwareConcurrency || 1; return navigator.hardwareConcurrency || 1;
} }
const os = require('os'); // Assume we're on Node.js. const os = this.nodeRequire('os'); // Assume we're on Node.js.
return os.cpus().length; return os.cpus().length;
}, },

View File

@ -1,9 +1,10 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
const assert = require('assert'); import assert from 'assert';
const path = require('path'); import path from 'path';
const { writeFileSync, unlinkSync } = require('fs'); import { writeFileSync, unlinkSync } from 'fs';
const { fork } = require('child_process'); import { fork } from 'child_process';
const openpgp = require('../..'); import { fileURLToPath } from 'url';
import * as openpgp from 'openpgp';
/** /**
* Benchmark max memory usage recorded during execution of the given function. * Benchmark max memory usage recorded during execution of the given function.
@ -12,11 +13,12 @@ const openpgp = require('../..');
* @returns {NodeJS.MemoryUsage} memory usage snapshot with max RSS (sizes in bytes) * @returns {NodeJS.MemoryUsage} memory usage snapshot with max RSS (sizes in bytes)
*/ */
const benchmark = async function(fn) { const benchmark = async function(fn) {
const tmpFileName = path.join(__dirname, 'tmp.js'); const __dirname = path.dirname(fileURLToPath(import.meta.url));
const tmpFileName = path.join(__dirname, 'tmp.cjs');
// the code to execute must be written to a file // the code to execute must be written to a file
writeFileSync(tmpFileName, ` writeFileSync(tmpFileName, `
const assert = require('assert'); const assert = require('assert');
const openpgp = require('../..'); const openpgp = require('openpgp');
let maxMemoryComsumption; let maxMemoryComsumption;
let activeSampling = false; let activeSampling = false;

View File

@ -1,5 +1,5 @@
const Benchmark = require('benchmark'); import Benchmark from 'benchmark';
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); import * as openpgp from 'openpgp';
const wrapAsync = func => ({ const wrapAsync = func => ({
fn: async deferred => { fn: async deferred => {

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const aesKW = require('../../src/crypto/aes_kw'); import * as aesKW from '../../src/crypto/aes_kw.js';
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('AES Key Wrap and Unwrap', function () { export default () => describe('AES Key Wrap and Unwrap', function () {
const test_vectors = [ const test_vectors = [
[ [
'128 bits of Key Data with a 128-bit KEK', '128 bits of Key Data with a 128-bit KEK',

View File

@ -1,8 +1,8 @@
const { expect } = require('chai'); import { expect } from 'chai';
const { aes128: AES128 } = require('../../../src/crypto/cipher'); import { aes128 as AES128 } from '../../../src/crypto/cipher';
module.exports = () => describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function() { export default () => describe('AES Rijndael cipher test with test vectors from ecb_tbl.txt', function() {
function test_aes(input, key, output) { function test_aes(input, key, output) {
const aes = new AES128(new Uint8Array(key)); const aes = new AES128(new Uint8Array(key));

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const BF = require('../../../src/crypto/cipher/blowfish'); import BF from '../../../src/crypto/cipher/blowfish';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) { export default () => it('Blowfish cipher test with test vectors from https://www.schneier.com/code/vectors.txt', function(done) {
function test_bf(input, key, output) { function test_bf(input, key, output) {
const blowfish = new BF(util.uint8ArrayToString(key)); const blowfish = new BF(util.uint8ArrayToString(key));
const result = blowfish.encrypt(input); const result = blowfish.encrypt(input);

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const CAST5 = require('../../../src/crypto/cipher/cast5'); import CAST5 from '../../../src/crypto/cipher/cast5.js';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('CAST-128 cipher test with test vectors from RFC2144', function (done) { export default () => it('CAST-128 cipher test with test vectors from RFC2144', function (done) {
function test_cast(input, key, output) { function test_cast(input, key, output) {
const cast5 = new CAST5(key); const cast5 = new CAST5(key);
const result = cast5.encrypt(input); const result = cast5.encrypt(input);

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const { DES, TripleDES } = require('../../../src/crypto/cipher/des'); import { DES, TripleDES } from '../../../src/crypto/cipher/des.js';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() { export default () => describe('TripleDES (EDE) cipher test with test vectors from NIST SP 800-20', function() {
// see https://csrc.nist.gov/publications/nistpubs/800-20/800-20.pdf // see https://csrc.nist.gov/publications/nistpubs/800-20/800-20.pdf
const key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); const key = new Uint8Array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]);
const testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]], const testvectors = [[[0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00],[0x95,0xF8,0xA5,0xE5,0xDD,0x31,0xD9,0x00]],

View File

@ -1,7 +1,13 @@
module.exports = () => describe('Cipher', function () { import testAES from './aes';
require('./aes')(); import testBlowfish from './blowfish';
require('./blowfish')(); import testCAST5 from './cast5';
require('./cast5')(); import testDES from './des';
require('./des')(); import testTwofish from './twofish';
require('./twofish')();
export default () => describe('Cipher', function () {
testAES();
testBlowfish();
testCAST5();
testDES();
testTwofish();
}); });

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const TF = require('../../../src/crypto/cipher/twofish'); import TF from '../../../src/crypto/cipher/twofish.js';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) { export default () => it('Twofish with test vectors from https://www.schneier.com/code/ecb_ival.txt', function(done) {
function tfencrypt(block, key) { function tfencrypt(block, key) {
const tf = new TF(util.stringToUint8Array(key)); const tf = new TF(util.stringToUint8Array(key));

View File

@ -1,12 +1,13 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const crypto = require('../../src/crypto'); import crypto from '../../src/crypto';
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('API functional testing', function() { export default () => describe('API functional testing', function() {
const RSAPublicKeyMaterial = util.concatUint8Array([ const RSAPublicKeyMaterial = util.concatUint8Array([
new Uint8Array([0x08,0x00,0xac,0x15,0xb3,0xd6,0xd2,0x0f,0xf0,0x7a,0xdd,0x21,0xb7, new Uint8Array([0x08,0x00,0xac,0x15,0xb3,0xd6,0xd2,0x0f,0xf0,0x7a,0xdd,0x21,0xb7,
0xbf,0x61,0xfa,0xca,0x93,0x86,0xc8,0x55,0x5a,0x4b,0xa6,0xa4,0x1a, 0xbf,0x61,0xfa,0xca,0x93,0x86,0xc8,0x55,0x5a,0x4b,0xa6,0xa4,0x1a,

View File

@ -1,13 +1,14 @@
// Modified by ProtonTech AG // Modified by ProtonTech AG
// Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const EAX = require('../../src/crypto/mode/eax'); import EAX from '../../src/crypto/mode/eax.js';
const util = require('../../src/util'); import util from '../../src/util.js';
function testAESEAX() { function testAESEAX() {
it('Passes all test vectors', async function() { it('Passes all test vectors', async function() {
@ -124,7 +125,7 @@ function testAESEAX() {
} }
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
module.exports = () => describe('Symmetric AES-EAX', function() { export default () => describe('Symmetric AES-EAX', function() {
let sinonSandbox; let sinonSandbox;
let getWebCryptoStub; let getWebCryptoStub;
let getNodeCryptoStub; let getNodeCryptoStub;

View File

@ -1,18 +1,19 @@
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const OID = require('../../src/type/oid'); import OID from '../../src/type/oid.js';
const KDFParams = require('../../src/type/kdf_params'); import KDFParams from '../../src/type/kdf_params.js';
const elliptic_curves = require('../../src/crypto/public_key/elliptic'); import * as elliptic_curves from '../../src/crypto/public_key/elliptic';
const util = require('../../src/util'); import util from '../../src/util.js';
const elliptic_data = require('./elliptic_data'); import elliptic_data from './elliptic_data.js';
const random = require('../../src/crypto/random'); import * as random from '../../src/crypto/random.js';
const key_data = elliptic_data.key_data; const key_data = elliptic_data.key_data;
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
module.exports = () => describe('ECDH key exchange @lightweight', function () { export default () => describe('ECDH key exchange @lightweight', function () {
const decrypt_message = function (oid, hash, cipher, priv, pub, ephemeral, data, fingerprint) { const decrypt_message = function (oid, hash, cipher, priv, pub, ephemeral, data, fingerprint) {
if (util.isString(data)) { if (util.isString(data)) {
data = util.stringToUint8Array(data); data = util.stringToUint8Array(data);

View File

@ -1,18 +1,19 @@
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const elliptic_curves = require('../../src/crypto/public_key/elliptic'); import * as elliptic_curves from '../../src/crypto/public_key/elliptic';
const hashMod = require('../../src/crypto/hash'); import hashMod from '../../src/crypto/hash';
const config = require('../../src/config'); import config from '../../src/config';
const util = require('../../src/util'); import util from '../../src/util.js';
const elliptic_data = require('./elliptic_data'); import elliptic_data from './elliptic_data';
const key_data = elliptic_data.key_data; const key_data = elliptic_data.key_data;
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
module.exports = () => describe('Elliptic Curve Cryptography @lightweight', function () { export default () => describe('Elliptic Curve Cryptography @lightweight', function () {
const signature_data = { const signature_data = {
priv: new Uint8Array([ priv: new Uint8Array([
0x14, 0x2B, 0xE2, 0xB7, 0x4D, 0xBD, 0x1B, 0x22, 0x14, 0x2B, 0xE2, 0xB7, 0x4D, 0xBD, 0x1B, 0x22,

View File

@ -99,4 +99,4 @@ const elliptic_data = {
} }
}; };
module.exports = elliptic_data; export default elliptic_data;

View File

@ -1,13 +1,14 @@
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const crypto = require('../../src/crypto'); import crypto from '../../src/crypto';
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('Symmetric AES-GCM (experimental)', function() { export default () => describe('Symmetric AES-GCM (experimental)', function() {
let sinonSandbox; let sinonSandbox;
let getWebCryptoStub; let getWebCryptoStub;
let getNodeCryptoStub; let getNodeCryptoStub;

View File

@ -1,5 +1,9 @@
module.exports = () => describe('Hash', function () { import testMD5 from './md5';
require('./md5')(); import testRipeMD from './ripemd';
require('./ripemd')(); import testSHA from './sha';
require('./sha')();
export default () => describe('Hash', function () {
testMD5();
testRipeMD();
testSHA();
}); });

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const md5 = require('../../../src/crypto/hash/md5'); import md5 from '../../../src/crypto/hash/md5.js';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('MD5 with test vectors from RFC 1321', async function() { export default () => it('MD5 with test vectors from RFC 1321', async function() {
expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('')), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e'); expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('')), 'MD5("") = d41d8cd98f00b204e9800998ecf8427e')).to.equal('d41d8cd98f00b204e9800998ecf8427e');
expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('abc')), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72'); expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('abc')), 'MD5("a") = 0cc175b9c0f1b6a831c399e269772661')).to.equal('900150983cd24fb0d6963f7d28e17f72');
expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('message digest')), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0'); expect(util.uint8ArrayToHex(await md5(util.stringToUint8Array('message digest')), 'MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0')).to.equal('f96b697d7cb7938d525a2f31aaf161d0');

View File

@ -1,11 +1,11 @@
const { expect } = require('chai'); import { expect } from 'chai';
const { ripemd: rmdString } = require('../../../src/crypto/hash'); import hash from '../../../src/crypto/hash';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html', async function() { export default () => it('RIPE-MD 160 bits with test vectors from https://homes.esat.kuleuven.be/~bosselae/ripemd160.html', async function() {
expect(util.uint8ArrayToHex(await rmdString(util.stringToUint8Array('')), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31'); expect(util.uint8ArrayToHex(await hash.ripemd(util.stringToUint8Array('')), 'RMDstring("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31')).to.equal('9c1185a5c5e9fc54612808977ee8f548b2258d31');
expect(util.uint8ArrayToHex(await rmdString(util.stringToUint8Array('a')), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe'); expect(util.uint8ArrayToHex(await hash.ripemd(util.stringToUint8Array('a')), 'RMDstring("a") = 0bdc9d2d256b3ee9daae347be6f4dc835a467ffe')).to.equal('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe');
expect(util.uint8ArrayToHex(await rmdString(util.stringToUint8Array('abc')), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc'); expect(util.uint8ArrayToHex(await hash.ripemd(util.stringToUint8Array('abc')), 'RMDstring("abc") = 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc')).to.equal('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc');
expect(util.uint8ArrayToHex(await rmdString(util.stringToUint8Array('message digest')), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36'); expect(util.uint8ArrayToHex(await hash.ripemd(util.stringToUint8Array('message digest')), 'RMDstring("message digest") = 5d0689ef49d2fae572b881b123a85ffa21595f36')).to.equal('5d0689ef49d2fae572b881b123a85ffa21595f36');
}); });

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const hash = require('../../../src/crypto/hash'); import hash from '../../../src/crypto/hash';
const util = require('../../../src/util'); import util from '../../../src/util.js';
module.exports = () => it('SHA* with test vectors from NIST FIPS 180-2', async function() { export default () => it('SHA* with test vectors from NIST FIPS 180-2', async function() {
expect(util.uint8ArrayToHex(await hash.sha1(util.stringToUint8Array('abc')), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d'); expect(util.uint8ArrayToHex(await hash.sha1(util.stringToUint8Array('abc')), 'hash.sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d')).to.equal('a9993e364706816aba3e25717850c26c9cd0d89d');
expect(util.uint8ArrayToHex(await hash.sha1(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq')), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1'); expect(util.uint8ArrayToHex(await hash.sha1(util.stringToUint8Array('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq')), 'hash.sha1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") = 84983e441c3bd26ebaae4aa1f95129e5e54670f1')).to.equal('84983e441c3bd26ebaae4aa1f95129e5e54670f1');
expect(util.uint8ArrayToHex(await hash.sha224(util.stringToUint8Array('abc')), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7'); expect(util.uint8ArrayToHex(await hash.sha224(util.stringToUint8Array('abc')), 'hash.sha224("abc") = 23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7')).to.equal('23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7');

View File

@ -1,13 +1,10 @@
const { expect } = require('chai'); import { expect } from 'chai';
const computeHKDF = require('../../src/crypto/hkdf'); import computeHKDF from '../../src/crypto/hkdf';
const enums = require('../../src/enums'); import enums from '../../src/enums';
const util = require('../../src/util'); import util from '../../src/util';
// WebCrypto implements HKDF natively, no need to test it export default () => describe('HKDF test vectors', function() {
const maybeDescribe = util.getNodeCrypto() ? describe : describe;
module.exports = () => maybeDescribe('HKDF test vectors', function() {
// Vectors from https://www.rfc-editor.org/rfc/rfc5869#appendix-A // Vectors from https://www.rfc-editor.org/rfc/rfc5869#appendix-A
it('Test Case 1', async function() { it('Test Case 1', async function() {
const inputKey = util.hexToUint8Array('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'); const inputKey = util.hexToUint8Array('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');

View File

@ -1,15 +1,29 @@
module.exports = () => describe('Crypto', function () { import testCipher from './cipher';
require('./cipher')(); import testHash from './hash';
require('./hash')(); import testCrypto from './crypto';
require('./crypto')(); import testElliptic from './elliptic';
require('./elliptic')(); import testECDH from './ecdh';
require('./ecdh')(); import testPKCS5 from './pkcs5';
require('./pkcs5')(); import testAESKW from './aes_kw';
require('./aes_kw')(); import testHKDF from './hkdf';
require('./hkdf')(); import testGCM from './gcm';
require('./gcm')(); import testEAX from './eax';
require('./eax')(); import testOCB from './ocb';
require('./ocb')(); import testRSA from './rsa';
require('./rsa')(); import testValidate from './validate';
require('./validate')();
export default () => describe('Crypto', function () {
testCipher();
testHash();
testCrypto();
testElliptic();
testECDH();
testPKCS5();
testAESKW();
testHKDF();
testGCM();
testEAX();
testOCB();
testRSA();
testValidate();
}); });

View File

@ -1,14 +1,15 @@
// Modified by ProtonTech AG // Modified by ProtonTech AG
// Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js // Adapted from https://github.com/artjomb/cryptojs-extension/blob/8c61d159/test/eax.js
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const OCB = require('../../src/crypto/mode/ocb'); import OCB from '../../src/crypto/mode/ocb.js';
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('Symmetric AES-OCB', function() { export default () => describe('Symmetric AES-OCB', function() {
it('Passes all test vectors', async function() { it('Passes all test vectors', async function() {
const K = '000102030405060708090A0B0C0D0E0F'; const K = '000102030405060708090A0B0C0D0E0F';
const keyBytes = util.hexToUint8Array(K); const keyBytes = util.hexToUint8Array(K);

View File

@ -1,8 +1,8 @@
const { expect } = require('chai'); import { expect } from 'chai';
const pkcs5 = require('../../src/crypto/pkcs5'); import * as pkcs5 from '../../src/crypto/pkcs5.js';
module.exports = () => describe('PKCS5 padding', function() { export default () => describe('PKCS5 padding', function() {
it('Add and remove padding', function () { it('Add and remove padding', function () {
const m = new Uint8Array([0,1,2,3,4,5,6,7,8]); const m = new Uint8Array([0,1,2,3,4,5,6,7,8]);
const padded = pkcs5.encode(m); const padded = pkcs5.encode(m);

View File

@ -1,14 +1,15 @@
const sandbox = require('sinon/lib/sinon/sandbox'); import sandbox from 'sinon/lib/sinon/sandbox';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const crypto = require('../../src/crypto'); import crypto from '../../src/crypto';
const random = require('../../src/crypto/random'); import * as random from '../../src/crypto/random.js';
const util = require('../../src/util'); import util from '../../src/util.js';
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
module.exports = () => describe('basic RSA cryptography', function () { export default () => describe('basic RSA cryptography', function () {
let sinonSandbox; let sinonSandbox;
let getWebCryptoStub; let getWebCryptoStub;
let getNodeCryptoStub; let getNodeCryptoStub;

View File

@ -1,8 +1,9 @@
const BN = require('bn.js'); import BN from 'bn.js';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const armoredDSAKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- const armoredDSAKey = `-----BEGIN PGP PRIVATE KEY BLOCK-----
@ -86,7 +87,7 @@ async function generatePrivateKeyObject(options) {
} }
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
module.exports = () => { export default () => {
describe('EdDSA parameter validation (legacy format)', function() { describe('EdDSA parameter validation (legacy format)', function() {
let eddsaKey; let eddsaKey;
before(async () => { before(async () => {

View File

@ -1,9 +1,8 @@
const { expect } = require('chai'); import { expect } from 'chai';
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
export default () => describe('ASCII armor', function() {
module.exports = () => describe('ASCII armor', function() {
function getArmor(headers, signatureHeaders) { function getArmor(headers, signatureHeaders) {
return ['-----BEGIN PGP SIGNED MESSAGE-----'] return ['-----BEGIN PGP SIGNED MESSAGE-----']

View File

@ -1,9 +1,10 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const BN = require('bn.js'); import BN from 'bn.js';
const random = require('../../src/crypto/random'); import * as random from '../../src/crypto/random.js';
const util = require('../../src/util'); import util from '../../src/util.js';
let BigInteger; let BigInteger;
@ -18,7 +19,7 @@ async function getRandomBN(min, max) {
return r.mod(modulus).add(min); return r.mod(modulus).add(min);
} }
module.exports = () => describe('BigInteger interface', function() { export default () => describe('BigInteger interface', function() {
before(async () => { before(async () => {
BigInteger = await util.getBigInteger(); BigInteger = await util.getBigInteger();
}); });

View File

@ -1,14 +1,15 @@
/* globals tryTests */ /* globals tryTests */
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
const input = require('./testInputs'); import * as input from './testInputs.js';
module.exports = () => (openpgp.config.ci ? describe.skip : describe)('Brainpool Cryptography @lightweight', function () { export default () => (openpgp.config.ci ? describe.skip : describe)('Brainpool Cryptography @lightweight', function () {
let rejectCurvesVal; let rejectCurvesVal;
before(function() { before(function() {
//only x25519 crypto is fully functional in lightbuild //only x25519 crypto is fully functional in lightbuild

View File

@ -1,8 +1,8 @@
const { expect } = require('chai'); import { expect } from 'chai';
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
module.exports = () => describe('Custom configuration', function() { export default () => describe('Custom configuration', function() {
it('openpgp.readMessage', async function() { it('openpgp.readMessage', async function() {
const armoredMessage = await openpgp.encrypt({ message: await openpgp.createMessage({ text:'hello world' }), passwords: 'password' }); const armoredMessage = await openpgp.encrypt({ message: await openpgp.createMessage({ text:'hello world' }), passwords: 'password' });
const message = await openpgp.readMessage({ armoredMessage }); const message = await openpgp.readMessage({ armoredMessage });

View File

@ -1,7 +1,8 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const password = 'I am a password'; const password = 'I am a password';
@ -38,7 +39,7 @@ Xg==
} }
}; };
module.exports = () => describe('Decrypt and decompress message tests', function () { export default () => describe('Decrypt and decompress message tests', function () {
function runTest(key, test) { function runTest(key, test) {
it(`Decrypts message compressed with ${key}`, async function () { it(`Decrypts message compressed with ${key}`, async function () {

View File

@ -1,13 +1,14 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
const input = require('./testInputs'); import * as input from './testInputs.js';
module.exports = () => describe('Elliptic Curve Cryptography for NIST P-256,P-384,P-521 curves @lightweight', function () { export default () => describe('Elliptic Curve Cryptography for NIST P-256,P-384,P-521 curves @lightweight', function () {
function omnibus() { function omnibus() {
it('Omnibus NIST P-256 Test', async function () { it('Omnibus NIST P-256 Test', async function () {
const testData = input.createSomeMessage(); const testData = input.createSomeMessage();

View File

@ -1,10 +1,11 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('Elliptic Curve Cryptography for secp256k1 curve @lightweight', function () { export default () => describe('Elliptic Curve Cryptography for secp256k1 curve @lightweight', function () {
if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) { if (!openpgp.config.useIndutnyElliptic && !util.getNodeCrypto()) {
before(function() { before(function() {
this.skip(); // eslint-disable-line no-invalid-this this.skip(); // eslint-disable-line no-invalid-this

View File

@ -1,18 +1,33 @@
module.exports = () => describe('General', function () { import testX25519 from './x25519.js';
require('./util')(); import testUtil from './util.js';
require('./biginteger')(); import testBigInteger from './biginteger.js';
require('./armor')(); import testArmor from './armor.js';
require('./packet')(); import testPacket from './packet.js';
require('./signature')(); import testSignature from './signature.js';
require('./key')(); import testKey from './key.js';
require('./openpgp')(); import testOpenPGP from './openpgp.js';
require('./config')(); import testConfig from './config.js';
require('./oid')(); import testOID from './oid.js';
require('./ecc_nist')(); import testNistECC from './ecc_nist.js';
require('./ecc_secp256k1')(); import testSecp256k1 from './ecc_secp256k1.js';
require('./x25519')(); import testBrainpool from './brainpool.js';
require('./brainpool')(); import testDecompression from './decompression.js';
require('./decompression')(); import testStreaming from './streaming.js';
require('./streaming')();
});
export default () => describe('General', function () {
testX25519();
testUtil();
testBigInteger();
testArmor();
testPacket();
testSignature();
testKey();
testOpenPGP();
testConfig();
testOID();
testNistECC();
testSecp256k1();
testBrainpool();
testDecompression();
testStreaming();
});

View File

@ -1,12 +1,13 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
/* globals tryTests */ /* globals tryTests */
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
const { isAEADSupported, getPreferredAlgo } = require('../../src/key'); import { isAEADSupported, getPreferredAlgo } from '../../src/key';
const KeyID = require('../../src/type/keyid'); import KeyID from '../../src/type/keyid.js';
const priv_key_arm2 = const priv_key_arm2 =
@ -2892,7 +2893,7 @@ function versionSpecificTests() {
}); });
} }
module.exports = () => describe('Key', function() { export default () => describe('Key', function() {
let v5KeysVal; let v5KeysVal;
let aeadProtectVal; let aeadProtectVal;

View File

@ -1,9 +1,9 @@
const { expect } = require('chai'); import { expect } from 'chai';
const OID = require('../../src/type/oid'); import OID from '../../src/type/oid.js';
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('Oid tests', function() { export default () => describe('Oid tests', function() {
const p256_oid = new Uint8Array([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]); const p256_oid = new Uint8Array([0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]);
const p384_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x22]); const p384_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x22]);
const p521_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x23]); const p521_oid = new Uint8Array([0x2B, 0x81, 0x04, 0x00, 0x23]);

View File

@ -1,18 +1,19 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
/* globals tryTests, loadStreamsPolyfill */ /* globals tryTests, loadStreamsPolyfill */
const spy = require('sinon/lib/sinon/spy'); import spy from 'sinon/lib/sinon/spy';
const stream = require('@openpgp/web-stream-tools'); import * as stream from '@openpgp/web-stream-tools';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const crypto = require('../../src/crypto'); import crypto from '../../src/crypto';
const random = require('../../src/crypto/random'); import * as random from '../../src/crypto/random.js';
const util = require('../../src/util'); import util from '../../src/util.js';
const keyIDType = require('../../src/type/keyid'); import keyIDType from '../../src/type/keyid.js';
const { isAEADSupported } = require('../../src/key'); import { isAEADSupported } from '../../src/key';
const input = require('./testInputs'); import * as input from './testInputs.js';
const detectNode = () => typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; const detectNode = () => typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object';
const detectBrowser = () => typeof navigator === 'object'; const detectBrowser = () => typeof navigator === 'object';
@ -895,7 +896,7 @@ function withCompression(tests) {
}); });
} }
module.exports = () => describe('OpenPGP.js public api tests', function() { export default () => describe('OpenPGP.js public api tests', function() {
describe('readKey(s) and readPrivateKey(s) - unit tests', function() { describe('readKey(s) and readPrivateKey(s) - unit tests', function() {
it('readKey and readPrivateKey should create equal private keys', async function() { it('readKey and readPrivateKey should create equal private keys', async function() {
const key = await openpgp.readKey({ armoredKey: priv_key }); const key = await openpgp.readKey({ armoredKey: priv_key });
@ -3064,7 +3065,7 @@ XfA3pqV4mTzF
throw new Error('Was not able to successfully modify checksum'); throw new Error('Was not able to successfully modify checksum');
} }
const badBodyEncrypted = data.replace(/\n=([a-zA-Z0-9/+]{4})/, 'aaa\n=$1'); const badBodyEncrypted = data.replace(/\n=([a-zA-Z0-9/+]{4})/, 'aaa\n=$1');
loadStreamsPolyfill(); await loadStreamsPolyfill();
try { try {
for (const allowStreaming of [true, false]) { for (const allowStreaming of [true, false]) {
openpgp.config.allowUnauthenticatedStream = allowStreaming; openpgp.config.allowUnauthenticatedStream = allowStreaming;
@ -3329,9 +3330,9 @@ XfA3pqV4mTzF
const plaintext = []; const plaintext = [];
let i = 0; let i = 0;
const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); // eslint-disable-line no-new const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); // eslint-disable-line no-new
loadStreamsPolyfill(); await loadStreamsPolyfill();
const ReadableStream = useNativeStream ? global.ReadableStream : stream.ReadableStream; const GenericReadableStream = useNativeStream ? global.ReadableStream : ReadableStream;
const data = new ReadableStream({ const data = new GenericReadableStream({
pull(controller) { pull(controller) {
if (i++ < 4) { if (i++ < 4) {
const randomBytes = random.getRandomBytes(10); const randomBytes = random.getRandomBytes(10);

View File

@ -1,14 +1,15 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
const stream = require('@openpgp/web-stream-tools'); import * as stream from '@openpgp/web-stream-tools';
const stub = require('sinon/lib/sinon/stub'); import stub from 'sinon/lib/sinon/stub';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const crypto = require('../../src/crypto'); import crypto from '../../src/crypto';
const util = require('../../src/util'); import util from '../../src/util.js';
const input = require('./testInputs'); import * as input from './testInputs.js';
function stringify(array) { function stringify(array) {
if (stream.isStream(array)) { if (stream.isStream(array)) {
@ -26,7 +27,7 @@ function stringify(array) {
return result.join(''); return result.join('');
} }
module.exports = () => describe('Packet', function() { export default () => describe('Packet', function() {
const allAllowedPackets = util.constructAllowedPackets([...Object.values(openpgp).filter(packetClass => !!packetClass.tag)]); const allAllowedPackets = util.constructAllowedPackets([...Object.values(openpgp).filter(packetClass => !!packetClass.tag)]);
const armored_key = const armored_key =

View File

@ -1,14 +1,15 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
/* globals tryTests, loadStreamsPolyfill */ /* globals tryTests, loadStreamsPolyfill */
const stream = require('@openpgp/web-stream-tools'); import * as stream from '@openpgp/web-stream-tools';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
module.exports = () => describe('Signature', function() { export default () => describe('Signature', function() {
const priv_key_arm1 = const priv_key_arm1 =
['-----BEGIN PGP PRIVATE KEY BLOCK-----', ['-----BEGIN PGP PRIVATE KEY BLOCK-----',
'Version: GnuPG v1.4.11 (GNU/Linux)', 'Version: GnuPG v1.4.11 (GNU/Linux)',
@ -900,7 +901,7 @@ AkLaG/AkATpuH+DMkYDmKbDLGgD+N4yuxXBJmBfC2IBe4J1S2Gg=
date: key.keyPacket.created, date: key.keyPacket.created,
format: 'object' format: 'object'
}); });
loadStreamsPolyfill(); await loadStreamsPolyfill();
const { signatures: [sigInfo] } = await openpgp.verify({ const { signatures: [sigInfo] } = await openpgp.verify({
verificationKeys: expiredKey, verificationKeys: expiredKey,
message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }), message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }),
@ -931,7 +932,7 @@ aMsUdQBgnPAcSGVsbG8gV29ybGQgOik=
date: key.keyPacket.created, date: key.keyPacket.created,
format: 'object' format: 'object'
}); });
loadStreamsPolyfill(); await loadStreamsPolyfill();
const { signatures: [sigInfo] } = await openpgp.verify({ const { signatures: [sigInfo] } = await openpgp.verify({
verificationKeys: expiredKey, verificationKeys: expiredKey,
message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }), message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }),
@ -961,7 +962,7 @@ eSvSZutLuKKbidSYMLhWROPlwKc2GU2ws6PrLZAyCAel/lU=
date: key.keyPacket.created, date: key.keyPacket.created,
format: 'object' format: 'object'
}); });
loadStreamsPolyfill(); await loadStreamsPolyfill();
const { signatures: [sigInfo] } = await openpgp.verify({ const { signatures: [sigInfo] } = await openpgp.verify({
verificationKeys: expiredKey, verificationKeys: expiredKey,
message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }), message: await openpgp.readMessage({ armoredMessage: stream.toStream(armoredMessage) }),
@ -1454,7 +1455,7 @@ yYDnCgA=
-----END PGP MESSAGE-----`.split(''); -----END PGP MESSAGE-----`.split('');
const plaintext = 'space: \nspace and tab: \t\nno trailing space\n \ntab:\t\ntab and space:\t '; const plaintext = 'space: \nspace and tab: \t\nno trailing space\n \ntab:\t\ntab and space:\t ';
loadStreamsPolyfill(); await loadStreamsPolyfill();
const message = await openpgp.readMessage({ const message = await openpgp.readMessage({
armoredMessage: new ReadableStream({ armoredMessage: new ReadableStream({
async pull(controller) { async pull(controller) {
@ -1520,7 +1521,7 @@ hkJiXopCSWKSlQInL1devkJJUWJmTmZeugJYlpdLAagQJM0JpsCqIQZwKgAA
-----END PGP MESSAGE-----`.split(''); -----END PGP MESSAGE-----`.split('');
const plaintext = 'space: \nspace and tab: \t\nno trailing space\n \ntab:\t\ntab and space:\t '; const plaintext = 'space: \nspace and tab: \t\nno trailing space\n \ntab:\t\ntab and space:\t ';
loadStreamsPolyfill(); await loadStreamsPolyfill();
const message = await openpgp.readMessage({ const message = await openpgp.readMessage({
armoredMessage: new ReadableStream({ armoredMessage: new ReadableStream({
async pull(controller) { async pull(controller) {

View File

@ -1,15 +1,16 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
/* globals loadStreamsPolyfill */ /* globals loadStreamsPolyfill */
const stream = require('@openpgp/web-stream-tools'); import * as stream from '@openpgp/web-stream-tools';
const stub = require('sinon/lib/sinon/stub'); import stub from 'sinon/lib/sinon/stub';
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const random = require('../../src/crypto/random'); import * as random from '../../src/crypto/random.js';
const util = require('../../src/util'); import util from '../../src/util.js';
const input = require('./testInputs'); import * as input from './testInputs.js';
const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); // eslint-disable-line no-new const useNativeStream = (() => { try { new global.ReadableStream(); return true; } catch (e) { return false; } })(); // eslint-disable-line no-new
const NodeReadableStream = useNativeStream ? undefined : require('stream').Readable; const NodeReadableStream = useNativeStream ? undefined : require('stream').Readable;
@ -890,7 +891,7 @@ function tests() {
it("Don't pull entire input stream when we're not pulling decrypted stream (AEAD)", async function() { it("Don't pull entire input stream when we're not pulling decrypted stream (AEAD)", async function() {
let coresStub; let coresStub;
if (detectNode()) { if (detectNode()) {
coresStub = stub(require('os'), 'cpus'); coresStub = stub(util.nodeRequire('os'), 'cpus');
coresStub.returns(new Array(2)); coresStub.returns(new Array(2));
// Object.defineProperty(require('os'), 'cpus', { value: () => [,], configurable: true }); // Object.defineProperty(require('os'), 'cpus', { value: () => [,], configurable: true });
} else { } else {
@ -947,7 +948,7 @@ function tests() {
}); });
} }
module.exports = () => describe('Streaming', function() { export default () => describe('Streaming', function() {
let currentTest = 0; let currentTest = 0;
before(async function() { before(async function() {
@ -957,7 +958,7 @@ module.exports = () => describe('Streaming', function() {
passphrase: 'hello world' passphrase: 'hello world'
}); });
loadStreamsPolyfill(); await loadStreamsPolyfill();
}); });
beforeEach(function() { beforeEach(function() {
@ -1013,7 +1014,9 @@ module.exports = () => describe('Streaming', function() {
tests(); tests();
if (detectNode()) { if (detectNode()) {
const fs = require('fs'); const fs = util.nodeRequire('fs');
const { fileURLToPath } = util.nodeRequire('url');
const __filename = fileURLToPath(import.meta.url);
it('Node: Encrypt and decrypt text message roundtrip', async function() { it('Node: Encrypt and decrypt text message roundtrip', async function() {
dataArrived(); // Do not wait until data arrived. dataArrived(); // Do not wait until data arrived.

View File

@ -12,6 +12,6 @@ function createSomeMessage() {
return ' \t' + String.fromCodePoint(...arr).replace(/[\r\u2028\u2029]/g, '\n') + ' \t\n한국어/조선말'; return ' \t' + String.fromCodePoint(...arr).replace(/[\r\u2028\u2029]/g, '\n') + ' \t\n한국어/조선말';
} }
module.exports = { export {
createSomeMessage: createSomeMessage createSomeMessage
}; };

View File

@ -1,8 +1,7 @@
const { expect } = require('chai'); import { expect } from 'chai';
const util = require('../../src/util'); import util from '../../src/util';
export default () => describe('Util unit tests', function() {
module.exports = () => describe('Util unit tests', function() {
describe('isString', function() { describe('isString', function() {
it('should return true for type "string"', function() { it('should return true for type "string"', function() {

View File

@ -1,17 +1,19 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const nacl = require('@openpgp/tweetnacl'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); import nacl from '@openpgp/tweetnacl';
const elliptic = require('../../src/crypto/public_key/elliptic');
const signature = require('../../src/crypto/signature');
const OID = require('../../src/type/oid');
const util = require('../../src/util');
const input = require('./testInputs'); import * as elliptic from '../../src/crypto/public_key/elliptic';
import * as signature from '../../src/crypto/signature';
import OID from '../../src/type/oid';
import util from '../../src/util';
module.exports = () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cryptography (legacy format)', function () { import * as input from './testInputs';
export default () => (openpgp.config.ci ? describe.skip : describe)('X25519 Cryptography (legacy format)', function () {
const data = { const data = {
light: { light: {
id: '1ecdf026c0245830', id: '1ecdf026c0245830',

View File

@ -1,6 +1,11 @@
module.exports = () => describe('Security', function () { import testMessageSignatureBypess from './message_signature_bypass';
require('./message_signature_bypass')(); import testUnsignedSubpackets from './unsigned_subpackets';
require('./unsigned_subpackets')(); import testSubkeyTrust from './subkey_trust';
require('./subkey_trust')(); import testPreferredAlgoMismatch from './preferred_algo_mismatch';
require('./preferred_algo_mismatch')();
export default () => describe('Security', function () {
testMessageSignatureBypess();
testUnsignedSubpackets();
testSubkeyTrust();
testPreferredAlgoMismatch();
}); });

View File

@ -1,8 +1,9 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const util = require('../../src/util'); import util from '../../src/util.js';
const { readKey, readCleartextMessage, SignaturePacket } = openpgp; const { readKey, readCleartextMessage, SignaturePacket } = openpgp;
@ -101,4 +102,4 @@ async function fakeSignature() {
expect(signatures).to.have.length(0); expect(signatures).to.have.length(0);
} }
module.exports = () => it('Does not accept non-binary/text signatures', fakeSignature); export default () => it('Does not accept non-binary/text signatures', fakeSignature);

View File

@ -1,7 +1,8 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const armoredMessage = `-----BEGIN PGP MESSAGE----- const armoredMessage = `-----BEGIN PGP MESSAGE-----
Version: OpenPGP.js VERSION Version: OpenPGP.js VERSION
@ -38,7 +39,7 @@ EnxUPL95HuMKoVkf4w==
=oopr =oopr
-----END PGP PRIVATE KEY BLOCK-----`; -----END PGP PRIVATE KEY BLOCK-----`;
module.exports = () => it('Does not accept message encrypted with algo not mentioned in preferred algorithms', async function() { export default () => it('Does not accept message encrypted with algo not mentioned in preferred algorithms', async function() {
const message = await openpgp.readMessage({ armoredMessage }); const message = await openpgp.readMessage({ armoredMessage });
const privKey = await openpgp.readKey({ armoredKey: privateKeyArmor }); const privKey = await openpgp.readKey({ armoredKey: privateKeyArmor });
await expect(openpgp.decrypt({ message, decryptionKeys: [privKey] })).to.be.rejectedWith('A non-preferred symmetric algorithm was used.'); await expect(openpgp.decrypt({ message, decryptionKeys: [privKey] })).to.be.rejectedWith('A non-preferred symmetric algorithm was used.');

View File

@ -1,7 +1,9 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const { readKey, PublicKey, readCleartextMessage, createCleartextMessage, enums, PacketList, SignaturePacket } = openpgp; const { readKey, PublicKey, readCleartextMessage, createCleartextMessage, enums, PacketList, SignaturePacket } = openpgp;
@ -33,7 +35,7 @@ async function generateTestData() {
}; };
} }
module.exports = () => it('Does not trust subkeys without Primary Key Binding Signature', async function() { export default () => it('Does not trust subkeys without Primary Key Binding Signature', async function() {
// attacker only has his own private key, // attacker only has his own private key,
// the victim's public key and a signed message // the victim's public key and a signed message
const { victimPubKey, attackerPrivKey, signed } = await generateTestData(); const { victimPubKey, attackerPrivKey, signed } = await generateTestData();

View File

@ -1,7 +1,9 @@
const { use: chaiUse, expect } = require('chai'); import { use as chaiUse, expect } from 'chai';
chaiUse(require('chai-as-promised')); import chaiAsPromised from 'chai-as-promised';
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('../..'); chaiUse(chaiAsPromised);
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : await import('openpgp');
const { readKey, PrivateKey, createMessage, enums, PacketList, SignaturePacket } = openpgp; const { readKey, PrivateKey, createMessage, enums, PacketList, SignaturePacket } = openpgp;
@ -89,4 +91,4 @@ async function makeKeyValid() {
expect(await encryptFails(modifiedkey)).to.be.true; expect(await encryptFails(modifiedkey)).to.be.true;
} }
module.exports = () => it('Does not accept unsigned subpackets', makeKeyValid); export default () => it('Does not accept unsigned subpackets', makeKeyValid);

View File

@ -16,7 +16,7 @@ import {
generateSessionKey, encryptSessionKey, decryptSessionKeys, generateSessionKey, encryptSessionKey, decryptSessionKeys,
LiteralDataPacket, PacketList, CompressedDataPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, CleartextMessage, LiteralDataPacket, PacketList, CompressedDataPacket, PublicKeyPacket, PublicSubkeyPacket, SecretKeyPacket, SecretSubkeyPacket, CleartextMessage,
WebStream, NodeStream, WebStream, NodeStream,
} from '../..'; } from 'openpgp';
(async () => { (async () => {

View File

@ -1,4 +1,6 @@
const openpgp = typeof window !== 'undefined' && window.openpgp ? window.openpgp : require('..'); import * as openpgp from 'openpgp';
if (typeof window !== 'undefined' && !window.openpgp) { window.openpgp = openpgp }
(typeof window !== 'undefined' ? window : global).globalThis = (typeof window !== 'undefined' ? window : global); (typeof window !== 'undefined' ? window : global).globalThis = (typeof window !== 'undefined' ? window : global);
@ -27,9 +29,14 @@ globalThis.tryTests = function(name, tests, options) {
}; };
globalThis.loadStreamsPolyfill = function() { globalThis.loadStreamsPolyfill = function() {
require('web-streams-polyfill/es2018'); // eslint-disable-line import/no-unassigned-import return import('web-streams-polyfill');
}; };
import runWorkerTests from './worker';
import runCryptoTests from './crypto';
import runGeneralTests from './general';
import runSecurityTests from './security';
describe('Unit Tests', function () { describe('Unit Tests', function () {
openpgp.config.s2kIterationCountByte = 0; openpgp.config.s2kIterationCountByte = 0;
@ -59,8 +66,8 @@ describe('Unit Tests', function () {
}); });
} }
require('./worker')(); runWorkerTests();
require('./crypto')(); runCryptoTests();
require('./general')(); runGeneralTests();
require('./security')(); runSecurityTests();
}); });

View File

@ -1,9 +1,8 @@
/* globals tryTests */ /* globals tryTests */
const { expect } = require('chai'); import { expect } from 'chai';
/* eslint-disable no-invalid-this */ export default () => tryTests('Application Worker', tests, {
module.exports = () => tryTests('Application Worker', tests, {
if: typeof window !== 'undefined' && window.Worker && window.MessageChannel if: typeof window !== 'undefined' && window.Worker && window.MessageChannel
}); });

View File

@ -1,4 +1,6 @@
module.exports = () => describe('Web Worker', function () { import testApplicationWorker from './application_worker.js';
require('./application_worker')();
export default () => describe('Web Worker', function () {
testApplicationWorker();
}); });

View File

@ -1,8 +1,12 @@
{ {
"exclude": [
"./build/"
],
"compilerOptions": { "compilerOptions": {
"strict": true "strict": true,
"target": "es2021",
"module": "esnext",
"moduleResolution": "node",
"allowJs": true,
"paths": {
"openpgp": [ "." ]
},
} }
} }