diff --git a/commitlint.config.js b/commitlint.config.js index dd1f77d703..37772496a0 100644 --- a/commitlint.config.js +++ b/commitlint.config.js @@ -8,4 +8,4 @@ module.exports = { 'subject-case': [0], 'subject-full-stop': [0], }, -}; +} diff --git a/packages/aa/test/index.spec.js b/packages/aa/test/index.spec.js index 8d11df2148..2dc6f6220f 100644 --- a/packages/aa/test/index.spec.js +++ b/packages/aa/test/index.spec.js @@ -1,12 +1,12 @@ -const path = require('path'); -const test = require('ava'); -const { loadCanonicalNameMap } = require('../src/index.js'); +const path = require('path') +const test = require('ava') +const { loadCanonicalNameMap } = require('../src/index.js') test('project 1', async t => { - const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '1') }); + const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '1') }) // normalize results to be relative const normalizedMapEntries = Array.from(canonicalNameMap.entries()).sort() - .map(([packagePath,canonicalName])=>[path.relative(__dirname,packagePath), canonicalName]) + .map(([packagePath,canonicalName]) => [path.relative(__dirname,packagePath), canonicalName]) t.deepEqual(normalizedMapEntries, [ [ 'projects/1', @@ -14,7 +14,7 @@ test('project 1', async t => { ], [ 'projects/1/node_modules/aaa', - 'aaa' + 'aaa', ], [ 'projects/1/node_modules/bbb', @@ -28,10 +28,10 @@ test('project 1', async t => { }) test('project 2', async t => { - const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '2') }); + const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '2') }) // normalize results to be relative const normalizedMapEntries = Array.from(canonicalNameMap.entries()).sort() - .map(([packagePath,canonicalName])=>[path.relative(__dirname,packagePath), canonicalName]) + .map(([packagePath,canonicalName]) => [path.relative(__dirname,packagePath), canonicalName]) t.deepEqual(normalizedMapEntries, [ [ 'projects/2', @@ -52,15 +52,15 @@ test('project 2', async t => { [ 'projects/2/node_modules/good_dep', 'good_dep', - ] + ], ]) }) test('project 3', async t => { - const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '3') }); + const canonicalNameMap = await loadCanonicalNameMap({ rootDir: path.join(__dirname, 'projects', '3') }) // normalize results to be relative const normalizedMapEntries = Array.from(canonicalNameMap.entries()).sort() - .map(([packagePath,canonicalName])=>[path.relative(__dirname,packagePath), canonicalName]) + .map(([packagePath,canonicalName]) => [path.relative(__dirname,packagePath), canonicalName]) t.deepEqual(normalizedMapEntries, [ [ 'projects/3', @@ -83,4 +83,4 @@ test('project 3', async t => { 'evil_dep', ], ]) -}) \ No newline at end of file +}) diff --git a/packages/allow-scripts/src/setup.js b/packages/allow-scripts/src/setup.js index 25345efce1..924f45a912 100755 --- a/packages/allow-scripts/src/setup.js +++ b/packages/allow-scripts/src/setup.js @@ -62,8 +62,8 @@ function writeRcFileContent({file, entry}) { let binsBlockedMemo /** - * - * @param {Object} args + * + * @param {Object} args * @param {boolean} noMemoization - turn off memoization, make a fresh lookup * @returns {boolean} */ @@ -141,15 +141,15 @@ function editPackageJson () { } else { console.log('@lavamoat/allow-scripts: Added dependency @lavamoat/preinstall-always-fail.') } - + if(FEATURE.bins) { // no motivation to fix lint here, there's a better implementation of this in a neighboring branch - // eslint-disable-next-line node/global-require + // eslint-disable-next-line n/global-require const packageJson = require(addInstallParentDir('package.json')) if(!packageJson.scripts) { packageJson.scripts = {} } - // If you think `node ` is redundant below, be aware that `./cli.js` won't work on Windows, + // If you think `node ` is redundant below, be aware that `./cli.js` won't work on Windows, // but passing a unix-style path to node on Windows works fine. packageJson.scripts['allow-scripts'] = 'node ./node_modules/@lavamoat/allow-scripts/src/cli.js --experimental-bins' console.log('@lavamoat/allow-scripts: Adding allow-scripts as a package.json script with direct path.') diff --git a/packages/allow-scripts/src/whichbin.js b/packages/allow-scripts/src/whichbin.js index a1d406dee2..409f6b8ec4 100755 --- a/packages/allow-scripts/src/whichbin.js +++ b/packages/allow-scripts/src/whichbin.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -/* eslint-disable node/shebang */ +/* eslint-disable n/shebang */ // @ts-check const path = require('path') @@ -22,7 +22,7 @@ async function start () { } console.error(`-lavamoat--allow-scripts--------------------------------------------------- -There's no policy for the '${binName}' bin script. +There's no policy for the '${binName}' bin script. You can allow this script to run by adding it to lavamoat->allowBins in package.json Add a line like this in allowBins: @@ -34,10 +34,10 @@ Add a line like this in allowBins: ${currentBinCandidates.map(c => c.fullLinkPath).join('\n')} `) } - + console.error(`After you're done configuring, run allow-scripts again. ---------------------------------------------------------------------------`) process.exit(42) - + } diff --git a/packages/allow-scripts/test/index.spec.js b/packages/allow-scripts/test/index.spec.js index cdffb6716c..05a9e3e668 100644 --- a/packages/allow-scripts/test/index.spec.js +++ b/packages/allow-scripts/test/index.spec.js @@ -18,7 +18,7 @@ test('cli - auto command', (t) => { let projectRoot = path.join(__dirname, 'projects', '1') // delete any existing package.json - fs.rmSync(path.join(projectRoot, PACKAGE_JSON), { force: true }); + fs.rmSync(path.join(projectRoot, PACKAGE_JSON), { force: true }) // npm init -y spawnSync('npm', ['init', '-y'], realisticEnvOptions(projectRoot)) @@ -35,8 +35,8 @@ test('cli - auto command', (t) => { // assert its contents t.deepEqual(packageJsonContents.lavamoat, { allowScripts: { - 'bbb>evil_dep': false - } + 'bbb>evil_dep': false, + }, }) }) @@ -44,7 +44,7 @@ test('cli - auto command with experimental bins', (t) => { // set up the directories let projectRoot = path.join(__dirname, 'projects', '1') - fs.rmSync(path.join(projectRoot, PACKAGE_JSON), { force: true }); + fs.rmSync(path.join(projectRoot, PACKAGE_JSON), { force: true }) // npm init -y spawnSync('npm', ['init', '-y'], realisticEnvOptions(projectRoot)) @@ -65,8 +65,8 @@ test('cli - auto command with experimental bins', (t) => { karramba: 'node_modules/bbb/index.js', }, allowScripts: { - 'bbb>evil_dep': false - } + 'bbb>evil_dep': false, + }, }) }) @@ -78,7 +78,7 @@ test('cli - run command - good dep at the root', (t) => { // the force option is only here to stop rm complaining if target is missing fs.rmSync(path.join(projectRoot, 'node_modules', '.bin'), { recursive: true, - force: true + force: true, }) // run the "run" command @@ -111,7 +111,7 @@ test('cli - run command - good dep at the root with experimental bins', (t) => { // the force option is only here to stop rm complaining if target is missing fs.rmSync(path.join(projectRoot, 'node_modules', '.bin'), { recursive: true, - force: true + force: true, }) // run the "run" command @@ -151,7 +151,7 @@ test('cli - run command - good dep as a sub dep', (t) => { fs.rmSync(path.join(projectRoot, 'node_modules', 'bbb', '.goodscriptworked'), { force: true }) fs.rmSync(path.join(projectRoot, 'node_modules', '.bin'), { recursive: true, - force: true + force: true, }) // generate the bin link @@ -186,7 +186,7 @@ test('cli - run command - good dep as a sub dep with experimental bins', (t) => fs.rmSync(path.join(projectRoot, 'node_modules', 'bbb', '.goodscriptworked'), { force: true }) fs.rmSync(path.join(projectRoot, 'node_modules', '.bin'), { recursive: true, - force: true + force: true, }) // run the "run" command let result = spawnSync(ALLOW_SCRIPTS_BIN, ['run', '--experimental-bins'], realisticEnvOptions(projectRoot)) @@ -197,10 +197,10 @@ test('cli - run command - good dep as a sub dep with experimental bins', (t) => t.assert(fs.existsSync(path.join(projectRoot, 'node_modules', 'bbb', 'node_modules', '.bin', 'good')), 'Expected a nested bin script to be installed in bbb/node_modules/.bin') const errarr = result.stderr.toString().split('\n') - t.assert(errarr.every(line=>!line.includes('you shall not pass')), 'Should not have run the parent script from the nested package postinstall') - t.assert(errarr.some(line=>line.includes(`"good": "node_modules/`)), 'Expected to see instructions on how to enable a bin script1') - t.assert(errarr.some(line=>line.includes(`node_modules/good_dep/cli.sh`)), 'Expected to see instructions on how to enable a bin script2') - t.assert(errarr.some(line=>line.includes(`node_modules/aaa/shouldntrun.sh`)), 'Expected to see instructions on how to enable a bin script3') + t.assert(errarr.every(line => !line.includes('you shall not pass')), 'Should not have run the parent script from the nested package postinstall') + t.assert(errarr.some(line => line.includes('"good": "node_modules/')), 'Expected to see instructions on how to enable a bin script1') + t.assert(errarr.some(line => line.includes('node_modules/good_dep/cli.sh')), 'Expected to see instructions on how to enable a bin script2') + t.assert(errarr.some(line => line.includes('node_modules/aaa/shouldntrun.sh')), 'Expected to see instructions on how to enable a bin script3') // assert the output t.deepEqual(result.stdout.toString().split('\n'), [ 'installing bin scripts', diff --git a/packages/browserify/test/arguments.spec.js b/packages/browserify/test/arguments.spec.js index c3b91b7c1e..623e548357 100644 --- a/packages/browserify/test/arguments.spec.js +++ b/packages/browserify/test/arguments.spec.js @@ -1,7 +1,7 @@ const test = require('ava') const { - runScenario + runScenario, } = require('./util') const { createScenarioFromScaffold, runAndTestScenario } = require('lavamoat-core/test/util') @@ -18,8 +18,8 @@ test('arguments - lavamoat command aliases work - advanced', async (t) => { p: '', pp: true, d: true, - dp: true - } + dp: true, + }, }) await runAndTestScenario(t, scenario, runScenario) }) @@ -31,9 +31,9 @@ test('arguments - invalid lavamoat commands fail', async (t) => { }, opts: { z: true, - c: true + c: true, }, expectedFailure: true, }) await runAndTestScenario(t, scenario, runScenario) -}) \ No newline at end of file +}) diff --git a/packages/browserify/test/basic.spec.js b/packages/browserify/test/basic.spec.js index fb67924064..5682adf453 100644 --- a/packages/browserify/test/basic.spec.js +++ b/packages/browserify/test/basic.spec.js @@ -4,13 +4,13 @@ const { createBundleFromEntry, evalBundle, createBundleForScenario, - runScenario + runScenario, } = require('./util') const { createScenarioFromScaffold, autoConfigForScenario, - runAndTestScenario + runAndTestScenario, } = require('lavamoat-core/test/util') test('basic - browserify bundle doesnt inject global', async (t) => { @@ -43,7 +43,7 @@ test('basic - lavamoat policy and bundle', async (t) => { }, defineTwo: () => { module.exports = () => location.href - } + }, }) await autoConfigForScenario({ scenario }) const { bundleForScenario } = await createBundleForScenario({ scenario }) @@ -65,7 +65,7 @@ test('basic - lavamoat bundle without prelude', async (t) => { defineTwo: () => { module.exports = () => location.href }, - opts: { includePrelude: false } + opts: { includePrelude: false }, }) await autoConfigForScenario({ scenario }) @@ -73,7 +73,9 @@ test('basic - lavamoat bundle without prelude', async (t) => { let didCallLoadBundle = false const testGlobal = { - LavaPack: { loadBundle: () => { didCallLoadBundle = true } } + LavaPack: { loadBundle: () => { + didCallLoadBundle = true + } }, } evalBundle(bundleForScenario, testGlobal) diff --git a/packages/browserify/test/factor.spec.js b/packages/browserify/test/factor.spec.js index a4d3d72c12..329a255f9e 100644 --- a/packages/browserify/test/factor.spec.js +++ b/packages/browserify/test/factor.spec.js @@ -1,11 +1,11 @@ const test = require('ava') const { fillInFileDetails, - functionToString + functionToString, } = require('lavamoat-core/test/util') const { createBundleForScenario, - runScenario + runScenario, } = require('./util') // eslint-disable-next-line ava/no-skip-test @@ -26,22 +26,22 @@ test.skip('package factor bundle', async (t) => { '@lavamoat/lavapack': '*', 'through2': '*', 'vinyl-buffer': '*', - } + }, })}`, }, './node_modules/a/package.json': { content: `${JSON.stringify({ - dependencies: {} + dependencies: {}, })}`, }, './node_modules/b/package.json': { content: `${JSON.stringify({ - dependencies: {} + dependencies: {}, })}`, }, './node_modules/c/package.json': { content: `${JSON.stringify({ - dependencies: {} + dependencies: {}, })}`, }, './node_modules/b/index.js': { @@ -51,14 +51,14 @@ test.skip('package factor bundle', async (t) => { importMap: {}, content: functionToString(() => { module.exports = global.three - }) + }), }, './src/12.js': { packageName: '$root$', importMap: {}, content: functionToString(() => { module.exports = 10 - }) + }), }, './src/1.js': { // src/1.js @@ -66,29 +66,29 @@ test.skip('package factor bundle', async (t) => { importMap: { a: './node_modules/a/index.js', b: './node_modules/b/index.js', - './10': './src/10.js' + './10': './src/10.js', }, content: functionToString(() => { const testResult = require('a') * require('b') * require('./10') console.log(JSON.stringify(testResult, null, 2)) }), - entry: true + entry: true, }, './src/10.js': { packageName: '$root$', importMap: { - './12': './src/12.js' + './12': './src/12.js', }, content: functionToString(() => { module.exports = require('./12') - }) + }), }, './node_modules/a/index.js': { packageName: 'a', importMap: {}, content: functionToString(() => { module.exports = global.two - }) + }), }, './src/2.js': { // src/2.js @@ -102,44 +102,44 @@ test.skip('package factor bundle', async (t) => { const testResult = require('b') * require('c') * require('./11') console.log(JSON.stringify(testResult, null, 2)) }), - entry: true + entry: true, }, './src/11.js': { packageName: '$root$', importMap: { - './12': './src/12.js' + './12': './src/12.js', }, content: functionToString(() => { module.exports = require('./12') - }) + }), }, './node_modules/c/index.js': { packageName: 'c', importMap: {}, content: functionToString(() => { module.exports = global.four - }) - } + }), + }, }), entries: ['./src/1.js', './src/2.js'], config: { resources: { c: { globals: { - four: true - } + four: true, + }, }, a: { globals: { - two: true - } + two: true, + }, }, b: { globals: { - three: true - } - } - } + three: true, + }, + }, + }, }, opts: { // TODO: this breaks when enabled (for some reason) @@ -150,7 +150,7 @@ test.skip('package factor bundle', async (t) => { three: 3, four: 4, }, - type: 'factor' + type: 'factor', } const { bundleForScenario: rawOutput } = await createBundleForScenario({ scenario }) @@ -160,7 +160,7 @@ test.skip('package factor bundle', async (t) => { t.deepEqual(relativeNames, [ 'common.js', 'src/1.js', - 'src/2.js' + 'src/2.js', ], 'relative filenames are as expected') const testResult1 = await runScenario({ scenario, bundle: vinylBundles['common.js'] + vinylBundles['src/1.js'] }) diff --git a/packages/browserify/test/generatePolicy.spec.js b/packages/browserify/test/generatePolicy.spec.js index 980d215731..7d8f5cd189 100644 --- a/packages/browserify/test/generatePolicy.spec.js +++ b/packages/browserify/test/generatePolicy.spec.js @@ -1,16 +1,16 @@ const test = require('ava') const { - autoConfigForScenario + autoConfigForScenario, } = require('./util') const { - createScenarioFromScaffold + createScenarioFromScaffold, } = require('lavamoat-core/test/util') test('generatePolicy - empty policy', async (t) => { const scenario = createScenarioFromScaffold({ defineEntry: () => {}, - defaultPolicy: false + defaultPolicy: false, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { resources: {} }, 'policy matches expected') @@ -18,8 +18,10 @@ test('generatePolicy - empty policy', async (t) => { test('generatePolicy - basic policy', async (t) => { const scenario = createScenarioFromScaffold({ - defineOne: () => { module.exports = global.two }, - defaultPolicy: false + defineOne: () => { + module.exports = global.two + }, + defaultPolicy: false, }) const policy = await autoConfigForScenario({ scenario }) @@ -27,10 +29,10 @@ test('generatePolicy - basic policy', async (t) => { resources: { one: { globals: { - two: true - } - } - } + two: true, + }, + }, + }, }) }) @@ -42,17 +44,17 @@ test('generatePolicy - ignore various refs', async (t) => { const globalRefs = [typeof globalThis, typeof self, typeof window] global.xyz }, - defaultPolicy: false + defaultPolicy: false, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { resources: { one: { globals: { - xyz: true - } - } - } + xyz: true, + }, + }, + }, }) }) @@ -63,7 +65,7 @@ test('generatePolicy - policy ignores global refs', async (t) => { const href = window.location.href const xhr = new window.XMLHttpRequest() }, - defaultPolicy: false + defaultPolicy: false, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { @@ -71,10 +73,10 @@ test('generatePolicy - policy ignores global refs', async (t) => { one: { globals: { 'location.href': true, - XMLHttpRequest: true - } - } - } + XMLHttpRequest: true, + }, + }, + }, }) }) @@ -83,11 +85,11 @@ test('generatePolicy - policy ignores global refs when properties are not access defineOne: () => { typeof window !== undefined }, - defaultPolicy: false + defaultPolicy: false, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { - resources: {} + resources: {}, }) }) @@ -98,12 +100,12 @@ test('generatePolicy - policy ignores global refs accessed with allowlist items' }, defaultPolicy: false, expectedResult: { - resources: {} - } + resources: {}, + }, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { - resources: {} + resources: {}, }) }) @@ -124,25 +126,25 @@ test('generatePolicy - policy endows "process" properly', async (t) => { // must include browserify so we know to find the builtin deps devDependencies: { 'browserify': '^16.2.3', - } + }, })}`, - } - } + }, + }, }) const policy = await autoConfigForScenario({ scenario }) t.deepEqual(policy, { resources: { one: { packages: { - 'browserify>process': true - } + 'browserify>process': true, + }, }, 'browserify>process': { globals: { clearTimeout: true, - setTimeout: true - } - } - } + setTimeout: true, + }, + }, + }, }) -}) \ No newline at end of file +}) diff --git a/packages/browserify/test/globalRef.spec.js b/packages/browserify/test/globalRef.spec.js index 5e92ea9396..66856e9acc 100644 --- a/packages/browserify/test/globalRef.spec.js +++ b/packages/browserify/test/globalRef.spec.js @@ -1,10 +1,10 @@ const test = require('ava') const { - runScenario + runScenario, } = require('./util') const { createScenarioFromScaffold, - runAndTestScenario + runAndTestScenario, } = require('lavamoat-core/test/util') test('globalRef - has only the expected global circular refs', async (t) => { @@ -22,8 +22,8 @@ test('globalRef - has only the expected global circular refs', async (t) => { 'window', 'self', 'global', - 'globalThis' - ].sort() + 'globalThis', + ].sort(), }) await runAndTestScenario(t, scenario, runScenario) }) @@ -33,10 +33,18 @@ test('globalRef - globalRef - check default containment', async (t) => { name: 'globalRef - check default containment', defineOne: () => { const testResults = {} - try { testResults.objCheckThis = this.Object === Object } catch (_) { } - try { testResults.objCheckSelf = self.Object === Object } catch (_) { } - try { testResults.objCheckGlobal = global.Object === Object } catch (_) { } - try { testResults.thisIsExports = exports === this } catch (_) { } + try { + testResults.objCheckThis = this.Object === Object + } catch (_) { } + try { + testResults.objCheckSelf = self.Object === Object + } catch (_) { } + try { + testResults.objCheckGlobal = global.Object === Object + } catch (_) { } + try { + testResults.thisIsExports = exports === this + } catch (_) { } module.exports = testResults }, expectedResult: { @@ -44,7 +52,7 @@ test('globalRef - globalRef - check default containment', async (t) => { objCheckSelf: true, objCheckGlobal: true, thisIsExports: true, - } + }, }) await runAndTestScenario(t, scenario, runScenario) }) @@ -56,25 +64,41 @@ test('globalRef - ensure endowments are accessible on globals', async (t) => { const testResults = {} testResults.contextHasPostMessage = typeof postMessage !== 'undefined' testResults.selfHasPostMessage = !!self.postMessage - try { testResults.checkThis = this.postMessage === postMessage } catch (err) { checkThis = err.message } - try { testResults.checkSelf = self.postMessage === postMessage } catch (err) { checkSelf = err.message } - try { testResults.checkWindow = window.postMessage === postMessage } catch (err) { checkWindow = err.message } - try { testResults.checkGlobal = global.postMessage === postMessage } catch (err) { checkGlobal = err.message } + try { + testResults.checkThis = this.postMessage === postMessage + } catch (err) { + checkThis = err.message + } + try { + testResults.checkSelf = self.postMessage === postMessage + } catch (err) { + checkSelf = err.message + } + try { + testResults.checkWindow = window.postMessage === postMessage + } catch (err) { + checkWindow = err.message + } + try { + testResults.checkGlobal = global.postMessage === postMessage + } catch (err) { + checkGlobal = err.message + } module.exports = testResults }, config: { resources: { '$root$': { packages: { - one: true - } + one: true, + }, }, one: { globals: { - postMessage: true - } - } - } + postMessage: true, + }, + }, + }, }, expectedResult: { // "this" is module.exports @@ -83,11 +107,13 @@ test('globalRef - ensure endowments are accessible on globals', async (t) => { checkWindow: true, checkGlobal: true, contextHasPostMessage: true, - selfHasPostMessage: true + selfHasPostMessage: true, }, context: { - postMessage: () => { throw new Error('this should never be called') } - } + postMessage: () => { + throw new Error('this should never be called') + }, + }, }) await runAndTestScenario(t, scenario, runScenario) }) diff --git a/packages/browserify/test/globalWrites.spec.js b/packages/browserify/test/globalWrites.spec.js index dd5edb1607..5515917aaa 100644 --- a/packages/browserify/test/globalWrites.spec.js +++ b/packages/browserify/test/globalWrites.spec.js @@ -1,10 +1,10 @@ const test = require('ava') const { createScenarioFromScaffold, - runAndTestScenario + runAndTestScenario, } = require('lavamoat-core/test/util') const { - runScenario + runScenario, } = require('./util') // here we are providing an endowments only to a module deep in a dep graph @@ -25,25 +25,25 @@ test('globalWrites - two deps should be able to read each others globals', async resources: { '$root$': { packages: { - two: true - } + two: true, + }, }, two: { globals: { - xyz: 'write' + xyz: 'write', }, packages: { - three: true - } + three: true, + }, }, three: { globals: { - xyz: true - } - } - } + xyz: true, + }, + }, + }, }, - expectedResult: true + expectedResult: true, }) await runAndTestScenario(t, scenario, runScenario) }) diff --git a/packages/browserify/test/globals.spec.js b/packages/browserify/test/globals.spec.js index 45abd740ed..f2fe3885c2 100644 --- a/packages/browserify/test/globals.spec.js +++ b/packages/browserify/test/globals.spec.js @@ -1,10 +1,10 @@ const test = require('ava') const { runScenario, - createBrowserifyScenarioFromScaffold + createBrowserifyScenarioFromScaffold, } = require('./util') const { - runAndTestScenario + runAndTestScenario, } = require('lavamoat-core/test/util.js') // TODO: this should be resolving to a browserify dependency @@ -19,11 +19,11 @@ test('globals - process is properly injected', async (t) => { resources: { one: { packages: { - 'browserify>process': true - } - } - } - } + 'browserify>process': true, + }, + }, + }, + }, }) await runAndTestScenario(t, scenario, runScenario) -}) \ No newline at end of file +}) diff --git a/packages/browserify/test/lavamoatNode.spec.js b/packages/browserify/test/lavamoatNode.spec.js index 60e7bc332a..cc315e0940 100644 --- a/packages/browserify/test/lavamoatNode.spec.js +++ b/packages/browserify/test/lavamoatNode.spec.js @@ -1,5 +1,5 @@ const test = require('ava') -const { execSync } = require('child_process'); +const { execSync } = require('child_process') const path = require('path') const { evalBundle, @@ -8,16 +8,16 @@ const { test('lavamoat-node compat - bundle works under lavamoat node', (t) => { let bundle try { - bundle = execSync("./test/fixtures/secureBundling/run.sh", - { - cwd: path.resolve(__dirname, '../'), - maxBuffer: 8192 * 10000 - }) + bundle = execSync('./test/fixtures/secureBundling/run.sh', + { + cwd: path.resolve(__dirname, '../'), + maxBuffer: 8192 * 10000, + }) } catch (err) { // eslint-disable-next-line ava/assertion-arguments return t.fail(err.stderr.toString()) } t.pass('bundling works under lavamoat node') const testResult = evalBundle(bundle.toString(), { console }) - t.is(testResult.value, "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", 'bundle works as expected') + t.is(testResult.value, 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', 'bundle works as expected') }) diff --git a/packages/browserify/test/policy.spec.js b/packages/browserify/test/policy.spec.js index e78c19dce6..669eec1f3c 100644 --- a/packages/browserify/test/policy.spec.js +++ b/packages/browserify/test/policy.spec.js @@ -16,9 +16,9 @@ const { test('policy - default policy path is generated with autoconfig if path is not specified', async (t) => { const scenario = createScenarioFromScaffold({ opts: { - writeAutoPolicy: true + writeAutoPolicy: true, }, - contextName: 'browserify' + contextName: 'browserify', }) const { policyDir } = await prepareBrowserifyScenarioOnDisk({ scenario }) const expectedPath = path.join(policyDir, 'policy.json') @@ -45,12 +45,12 @@ test('Policy is applied if not specified and already exists at default path', as resources: { three: { packages: { - two: true - } - } - } + two: true, + }, + }, + }, }, - expectedResult: 30 + expectedResult: 30, }) await runAndTestScenario(t, scenario, runScenario) }) @@ -59,8 +59,8 @@ test('Policy - Applies writeAutoPolicyDebug plugin option and dumps module objec const scenario = createScenarioFromScaffold({ opts: { writeAutoPolicy: true, - writeAutoPolicyDebug: true - } + writeAutoPolicyDebug: true, + }, }) const { policyDir } = await prepareBrowserifyScenarioOnDisk({ scenario }) const expectedPath = path.join(policyDir, 'policy-debug.json') @@ -76,7 +76,7 @@ test('Policy - watchify listens for policy file changes', async (t) => { const scenario = createScenarioFromScaffold({ opts: { writeAutoPolicy: true, - } + }, }) const { projectDir, policyDir } = await prepareBrowserifyScenarioOnDisk({ scenario }) await runBrowserify({ scenario }) @@ -137,4 +137,4 @@ test('Policy - watchify listens for policy file changes', async (t) => { // t.false(configFileString.includes('"three": 12345678'), 'original policy should not have updated content') // t.true(updatedPolicyFileString.includes('"three": 12345678'), 'policy should be updated') -// }) \ No newline at end of file +// }) diff --git a/packages/browserify/test/sourcemaps.js b/packages/browserify/test/sourcemaps.js index 2500ba9cc5..25c06febec 100644 --- a/packages/browserify/test/sourcemaps.js +++ b/packages/browserify/test/sourcemaps.js @@ -1,103 +1,103 @@ -const { SourceMapConsumer } = require('source-map'); +const { SourceMapConsumer } = require('source-map') const validate = require('sourcemap-validator') -const { fromSource: extractSourceMap } = require('convert-source-map'); +const { fromSource: extractSourceMap } = require('convert-source-map') const { explore } = require('source-map-explorer') -const { codeFrameColumns } = require('@babel/code-frame'); +const { codeFrameColumns } = require('@babel/code-frame') module.exports = { verifySourceMaps } async function verifySourceMaps({ bundle }) { // basic sanity checking - validate(bundle); + validate(bundle) // our custom sample checking - await verifySamples(bundle); + await verifySamples(bundle) // generate a sourcemap explorer because its stricter than some other validations - await verifyWithSourceExplorer(bundle); + await verifyWithSourceExplorer(bundle) } async function verifyWithSourceExplorer (bundle) { let result try { - result = await explore({ code: Buffer.from(bundle, 'utf8') }); + result = await explore({ code: Buffer.from(bundle, 'utf8') }) } catch (resultWithError) { if (resultWithError.errors) { resultWithError.errors.forEach((exploreError) => { // throw the first throw exploreError.error - }); + }) } else { - throw resultWithError; + throw resultWithError } } } async function verifySamples (bundle) { const sourcemap = extractSourceMap(bundle).toObject() - const consumer = await new SourceMapConsumer(sourcemap); + const consumer = await new SourceMapConsumer(sourcemap) - const hasContentsOfAllSources = consumer.hasContentsOfAllSources(); + const hasContentsOfAllSources = consumer.hasContentsOfAllSources() if (!hasContentsOfAllSources) { - console.warn('SourcemapValidator - missing content of some sources...'); + console.warn('SourcemapValidator - missing content of some sources...') } - let sampleCount = 0; + let sampleCount = 0 - const buildLines = bundle.split('\n'); - const targetString = 'module.exports'; + const buildLines = bundle.split('\n') + const targetString = 'module.exports' const matchesPerLine = buildLines.map((line) => indicesOf(targetString, line), - ); - const errors = []; + ) + const errors = [] matchesPerLine.forEach((matchIndices, lineIndex) => { matchIndices.forEach((matchColumn) => { - sampleCount += 1; - const position = { line: lineIndex + 1, column: matchColumn }; - const result = consumer.originalPositionFor(position); + sampleCount += 1 + const position = { line: lineIndex + 1, column: matchColumn } + const result = consumer.originalPositionFor(position) // warn if source content is missing if (!result.source) { const location = { start: { line: position.line, column: position.column + 1 }, - }; + } const codeSample = codeFrameColumns(bundle, location, { - message: `missing source for position`, + message: 'missing source for position', highlightCode: true, - }); + }) errors.push( `missing source for position, in bundle\n${codeSample}`, - ); - return; + ) + return } - const sourceContent = consumer.sourceContentFor(result.source); - const sourceLines = sourceContent.split('\n'); - const sourceLine = sourceLines[result.line - 1]; + const sourceContent = consumer.sourceContentFor(result.source) + const sourceLines = sourceContent.split('\n') + const sourceLine = sourceLines[result.line - 1] // this sometimes includes the whole line though we tried to match somewhere in the middle - const portion = sourceLine.slice(result.column); - const foundValidSource = portion.includes(targetString); + const portion = sourceLine.slice(result.column) + const foundValidSource = portion.includes(targetString) if (!foundValidSource) { const location = { start: { line: result.line + 1, column: result.column + 1 }, - }; + } const codeSample = codeFrameColumns(sourceContent, location, { message: `expected to see ${JSON.stringify(targetString)}`, highlightCode: true, - }); + }) errors.push( `Sourcemap seems invalid, ${result.source}\n${codeSample}`, - ); + ) } - }); - }); + }) + }) // error if any errors collected if (errors.length) { - throw new Error(`Sourcemap validation encountered ${errors.length} errors:\n${errors.join('\n')}`); + throw new Error(`Sourcemap validation encountered ${errors.length} errors:\n${errors.join('\n')}`) } } function indicesOf(substring, string) { - const a = []; - let i = -1; + const a = [] + let i = -1 while ((i = string.indexOf(substring, i + 1)) >= 0) { - a.push(i); + a.push(i) } - return a; + return a } diff --git a/packages/browserify/test/util.js b/packages/browserify/test/util.js index 3cbb4a3ae1..2dc4c63103 100644 --- a/packages/browserify/test/util.js +++ b/packages/browserify/test/util.js @@ -30,7 +30,7 @@ module.exports = { runBrowserify, bundleAsync, prepareBrowserifyScenarioOnDisk, - createBrowserifyScenarioFromScaffold + createBrowserifyScenarioFromScaffold, } async function copyFolder(from, to, opts = {skip: []}) { @@ -114,7 +114,7 @@ function createWatchifyBundler (pluginOpts) { [watchify, { poll: true }], // add lavamoat after watchify [lavamoatPlugin, pluginOpts], - ] + ], }) return bundler } @@ -191,7 +191,7 @@ async function prepareBrowserifyScenarioOnDisk ({ scenario }) { // copy browserify build runner const paths = { normal: `${__dirname}/fixtures/runBrowserify.js`, - factor: `${__dirname}/fixtures/runBrowserifyBundleFactor.js` + factor: `${__dirname}/fixtures/runBrowserifyBundleFactor.js`, } await fs.copyFile(runBrowserifyPath, path.join(projectDir, 'runBrowserify.js')) return { projectDir, policyDir } @@ -207,7 +207,7 @@ async function createBundleForScenario ({ scenario.dir = projectDir policy = policyDir } else { - policy = path.join(scenario.dir, `/lavamoat/browserify/`) + policy = path.join(scenario.dir, '/lavamoat/browserify/') } const { output: { stdout: bundle, stderr } } = await runBrowserify({ scenario, bundleWithPrecompiledModules }) diff --git a/packages/core/lib/strict-scope-terminator.js b/packages/core/lib/strict-scope-terminator.js index 686341069a..2641151ccd 100644 --- a/packages/core/lib/strict-scope-terminator.js +++ b/packages/core/lib/strict-scope-terminator.js @@ -9,18 +9,18 @@ // globalThis, // immutableObject, // } from './commons.js'; -const { freeze, create, getOwnPropertyDescriptors } = Object; -const immutableObject = freeze(create(null)); +const { freeze, create, getOwnPropertyDescriptors } = Object +const immutableObject = freeze(create(null)) // import { assert } from './error/assert.js'; const assert = { fail: (msg) => { - throw new Error(msg); - } + throw new Error(msg) + }, } // const { details: d, quote: q } = assert; -const d = (strings, args) => strings.join() + args.join(); +const d = (strings, args) => strings.join() + args.join() const q = (arg) => arg /** @@ -34,13 +34,12 @@ const alwaysThrowHandler = new Proxy( immutableObject, freeze({ get(_shadow, prop) { - // eslint-disable-next-line @endo/no-polymorphic-call assert.fail( d`Please report unexpected scope handler trap: ${q(String(prop))}`, - ); + ) }, }), -); +) /* * scopeProxyHandlerProperties @@ -50,24 +49,24 @@ const alwaysThrowHandler = new Proxy( */ const scopeProxyHandlerProperties = { get(_shadow, _prop) { - return undefined; + return undefined }, set(_shadow, prop, _value) { // We should only hit this if the has() hook returned true matches the v8 // ReferenceError message "Uncaught ReferenceError: xyz is not defined" - throw new ReferenceError(`${String(prop)} is not defined`); + throw new ReferenceError(`${String(prop)} is not defined`) }, has(_shadow, prop) { // we must at least return true for all properties on the realm globalThis - return prop in globalThis; + return prop in globalThis }, // note: this is likely a bug of safari // https://bugs.webkit.org/show_bug.cgi?id=195534 getPrototypeOf() { - return null; + return null }, // Chip has seen this happen single stepping under the Chrome/v8 debugger. @@ -75,15 +74,14 @@ const scopeProxyHandlerProperties = { // TODO report as bug to v8 or Chrome, and record issue link here. getOwnPropertyDescriptor(_target, prop) { // Coerce with `String` in case prop is a symbol. - const quotedProp = q(String(prop)); - // eslint-disable-next-line @endo/no-polymorphic-call + const quotedProp = q(String(prop)) console.warn( `getOwnPropertyDescriptor trap on scopeTerminatorHandler for ${quotedProp}`, new TypeError().stack, - ); - return undefined; + ) + return undefined }, -}; +} // The scope handler's prototype is a proxy that throws if any trap other // than get/set/has are run (like getOwnPropertyDescriptors, apply, @@ -93,12 +91,12 @@ const strictScopeTerminatorHandler = freeze( alwaysThrowHandler, getOwnPropertyDescriptors(scopeProxyHandlerProperties), ), -); +) const strictScopeTerminator = new Proxy( immutableObject, strictScopeTerminatorHandler, -); +) module.exports = { alwaysThrowHandler, diff --git a/packages/core/test/builtin.spec.js b/packages/core/test/builtin.spec.js index aac775c077..9218da247f 100644 --- a/packages/core/test/builtin.spec.js +++ b/packages/core/test/builtin.spec.js @@ -1,16 +1,21 @@ +/* eslint-disable n/prefer-global/buffer */ const test = require('ava') const { createScenarioFromScaffold, runScenario, - runAndTestScenario + runAndTestScenario, } = require('./util.js') test('builtin - basic access', async (t) => { const scenario = createScenarioFromScaffold({ defineOne: () => { let abc = null; let xyz = null - try { abc = require('abc') } catch (_) {} - try { xyz = require('xyz') } catch (_) {} + try { + abc = require('abc') + } catch (_) {} + try { + xyz = require('xyz') + } catch (_) {} module.exports = { abc, xyz } }, @@ -19,15 +24,15 @@ test('builtin - basic access', async (t) => { one: { builtin: { abc: true, - xyz: false - } - } - } + xyz: false, + }, + }, + }, }, expectedResult: { abc: 123, xyz: null }, builtin: { - abc: 123 - } + abc: 123, + }, }) await runAndTestScenario(t, scenario, runScenario) @@ -42,18 +47,18 @@ test('builtin - access via paths', async (t) => { resources: { one: { builtin: { - 'abc.xyz': true - } - } - } + 'abc.xyz': true, + }, + }, + }, }, expectedResult: { xyz: 123 }, builtin: { abc: { xyz: 123, - ijk: 456 - } - } + ijk: 456, + }, + }, }) await runAndTestScenario(t, scenario, runScenario) @@ -67,7 +72,7 @@ test('builtin - paths soft-bindings preserve "this" but allow override', async ( module.exports = { overrideCheck: two.overrideCheck(Buffer.from([1, 2, 3])), thisCheck: two.thisCheck(), - classCheck: two.classCheck() + classCheck: two.classCheck(), } }, @@ -94,29 +99,33 @@ test('builtin - paths soft-bindings preserve "this" but allow override', async ( resources: { one: { builtin: { - 'buffer.Buffer.from': true - } + 'buffer.Buffer.from': true, + }, }, two: { builtin: { // these paths are carefully constructed to try and split the fn from its parent 'buffer.Buffer.prototype.slice': true, 'thisChecker.check': true, - 'someClass.SomeClass': true - } - } - } + 'someClass.SomeClass': true, + }, + }, + }, }, expectedResult: { overrideCheck: true, thisCheck: true, - classCheck: true + classCheck: true, }, builtin: { buffer: require('buffer'), - thisChecker: (() => { const parent = {}; parent.check = function () { return this === parent }; return parent })(), - someClass: { SomeClass: class SomeClass {} } - } + thisChecker: (() => { + const parent = {}; parent.check = function () { + return this === parent + }; return parent + })(), + someClass: { SomeClass: class SomeClass {} }, + }, }) await runAndTestScenario(t, scenario, runScenario) diff --git a/packages/core/test/circularDeps.spec.js b/packages/core/test/circularDeps.spec.js index f318d18d51..958f5cf481 100644 --- a/packages/core/test/circularDeps.spec.js +++ b/packages/core/test/circularDeps.spec.js @@ -1,7 +1,7 @@ const test = require('ava') const { createScenarioFromScaffold, - runScenario + runScenario, } = require('./util') test('circularDeps - multi-module circular deps dont inf loop', async (t) => { @@ -17,14 +17,14 @@ test('circularDeps - multi-module circular deps dont inf loop', async (t) => { module.exports = 42 }, config: { - resources: { - three: { - packages: { - one: true, - } - } - } - } + resources: { + three: { + packages: { + one: true, + }, + }, + }, + }, }) const testResult = await runScenario({ scenario }) diff --git a/packages/core/test/generatePolicy.spec.js b/packages/core/test/generatePolicy.spec.js index 3d798f92fd..9deb1f13a1 100644 --- a/packages/core/test/generatePolicy.spec.js +++ b/packages/core/test/generatePolicy.spec.js @@ -12,10 +12,10 @@ test('generatePolicy - basic config', async (t) => { resources: { test: { globals: { - 'location.href': true - } - } - } + 'location.href': true, + }, + }, + }, }, 'config matched expected') }) @@ -35,11 +35,11 @@ test('generatePolicy - config with debugInfo', async (t) => { content: '(function () {\n location.href\n })()', importMap: {}, packageName: 'test', - moduleInitializer: undefined + moduleInitializer: undefined, }, globals: { - 'location.href': 'read' - } + 'location.href': 'read', + }, }, 'config matched expected') }) @@ -55,10 +55,10 @@ test('generatePolicy - ignore various refs', async (t) => { resources: { test: { globals: { - nonIgnoredGlobal: true - } - } - } + nonIgnoredGlobal: true, + }, + }, + }, }, 'config matched expected') }) @@ -73,10 +73,10 @@ test('generatePolicy - config ignores global refs', async (t) => { test: { globals: { 'location.href': true, - XMLHttpRequest: true - } - } - } + XMLHttpRequest: true, + }, + }, + }, }, 'config matches expected') }) @@ -86,7 +86,7 @@ test('generatePolicy - config ignores global refs when properties are not access }) t.deepEqual(config, { - resources: {} + resources: {}, }, 'config matches expected') }) @@ -96,7 +96,7 @@ test('generatePolicy - config ignores global refs accessed with whitelist items' }) t.deepEqual(config, { - resources: {} + resources: {}, }, 'config matches expected') }) @@ -106,7 +106,7 @@ test('generatePolicy - config ignores newer intrinsics', async (t) => { }) t.deepEqual(config, { - resources: {} + resources: {}, }, 'config matches expected') }) diff --git a/packages/core/test/globals.spec.js b/packages/core/test/globals.spec.js index 9ba2cb67d9..b62cd6e80c 100644 --- a/packages/core/test/globals.spec.js +++ b/packages/core/test/globals.spec.js @@ -1,7 +1,7 @@ const test = require('ava') const { createScenarioFromScaffold, - runScenario + runScenario, } = require('./util') test('globals - ensure global property this-value unwrapped', async (t) => { @@ -10,7 +10,7 @@ test('globals - ensure global property this-value unwrapped', async (t) => { defineOne: () => { module.exports = { direct: globalThis.xyz, - indirect: Reflect.getOwnPropertyDescriptor(globalThis, 'xyz').get() + indirect: Reflect.getOwnPropertyDescriptor(globalThis, 'xyz').get(), } }, context: { @@ -19,22 +19,22 @@ test('globals - ensure global property this-value unwrapped', async (t) => { // debugger return (this === scenario.globalThis || this === scenario.vmContext) - } + }, }, config: { resources: { one: { globals: { - xyz: true - } - } - } + xyz: true, + }, + }, + }, }, }) const testResult = await runScenario({ scenario }) t.deepEqual(testResult, { direct: true, - indirect: false + indirect: false, }, 'expected result, did not error') }) @@ -59,28 +59,28 @@ test('globals - ensure window.document getter behavior support', async (t) => { // node vm weird, sometimes calls with vm context instead of vm global this if (this !== scenario.globalThis && this !== scenario.vmContext) { // chrome: Uncaught TypeError: Illegal invocation - throw new TypeError("'get document' called on an object that does not implement interface Window") + throw new TypeError('\'get document\' called on an object that does not implement interface Window') } return { location: { - href: 'beepboop.bong' - } + href: 'beepboop.bong', + }, } - } + }, }, config: { resources: { one: { globals: { - document: true - } + document: true, + }, }, two: { globals: { - 'document.location.href': true - } - } - } + 'document.location.href': true, + }, + }, + }, }, }) const testResult = await runScenario({ scenario }) @@ -95,8 +95,8 @@ test('globals - ensure circular refs on package compartment global', async (t) = console.log(JSON.stringify(testResult, null, 2)) }, kernelArgs: { - globalThisRefs: ['xyz', 'globalThis'] - } + globalThisRefs: ['xyz', 'globalThis'], + }, }) const testResult = await runScenario({ scenario }) t.is(testResult, true, 'xyz references globalThis') @@ -117,18 +117,18 @@ test('globals - ensure setTimeout calls dont trigger illegal invocation', async resources: { one: { globals: { - setTimeout: true - } - } - } + setTimeout: true, + }, + }, + }, }, context: { setTimeout () { if (this !== scenario.globalThis && this !== scenario.vmContext) { // chrome: Uncaught TypeError: Illegal invocation - throw new TypeError("'setTimeout' called on an object that does not implement interface Window") + throw new TypeError('\'setTimeout\' called on an object that does not implement interface Window') } - } + }, }, }) const testResult = await runScenario({ scenario }) @@ -157,16 +157,18 @@ test('globals - endowing bind on a function', async (t) => { } }, context: { - abc: function () { return this } + abc: function () { + return this + }, }, config: { resources: { one: { globals: { - 'abc.bind': true - } + 'abc.bind': true, + }, }, - } + }, }, }) const testResult = await runScenario({ scenario }) @@ -195,10 +197,10 @@ test('globals - endowing properties on the globalThis prototype chain', async (t resources: { one: { globals: { - 'abc': true - } + 'abc': true, + }, }, - } + }, }, }) const testResult = await runScenario({ scenario }) @@ -212,16 +214,18 @@ test('globals - explicitly disallowing properties on the globalThis', async (t) module.exports = globalThis.abc() }, context: { - abc: function () { return 42 } + abc: function () { + return 42 + }, }, config: { resources: { one: { globals: { - 'abc': false - } + 'abc': false, + }, }, - } + }, }, }) await t.throwsAsync(runScenario({ scenario }), { message: 'globalThis.abc is not a function' }) @@ -234,26 +238,28 @@ test('globals - explicitly disallowing properties on the globalThis via override module.exports = globalThis.abc() }, context: { - abc: function () { return 42 } + abc: function () { + return 42 + }, }, config: { resources: { one: { globals: { - 'abc': true - } - } - } + 'abc': true, + }, + }, + }, }, configOverride: { resources: { one: { globals: { - 'abc': false - } - } - } - } + 'abc': false, + }, + }, + }, + }, }) await t.throwsAsync(runScenario({ scenario }), { message: 'globalThis.abc is not a function' }) }) @@ -263,7 +269,7 @@ test('globals - nested property true.false.true', async (t) => { // When this behavior changes, update /docs/policy.md const shared = { context: { - a: { ok: 42, b: { c: ()=>42, notOk:41 }}, + a: { ok: 42, b: { c: () => 42, notOk:41 }}, }, config: { resources: { @@ -272,9 +278,9 @@ test('globals - nested property true.false.true', async (t) => { 'a': true, 'a.b': false, 'a.b.c':true, - } + }, }, - } + }, }, } const handlesAccess = createScenarioFromScaffold({ @@ -284,9 +290,9 @@ test('globals - nested property true.false.true', async (t) => { a_ok: !!globalThis.a.ok, a_b_notOk: !!globalThis.a.b.notOk, a_b_c: globalThis.a.b.c(), - }; + } }, - ...shared + ...shared, }) const testResult = await runScenario({ scenario: handlesAccess }) @@ -301,8 +307,8 @@ test('globals - nested property false.true', async (t) => { 'use strict' const shared = { context: { - a: { b: { c: ()=>42, notOk:41 }}, - x: { notOk:41, y: ()=>42 }, + a: { b: { c: () => 42, notOk:41 }}, + x: { notOk:41, y: () => 42 }, }, config: { resources: { @@ -311,10 +317,10 @@ test('globals - nested property false.true', async (t) => { 'a.b': false, 'a.b.c':true, 'x': false, - 'x.y': true - } + 'x.y': true, + }, }, - } + }, }, } const handlesAccess = createScenarioFromScaffold({ @@ -326,9 +332,9 @@ test('globals - nested property false.true', async (t) => { x_notOk: !!globalThis.x.notOk, a_b_notOk: !!globalThis.a.b.notOk, a_b_c: globalThis.a.b.c(), - }; + } }, - ...shared + ...shared, }) const testResult = await runScenario({ scenario: handlesAccess }) @@ -343,7 +349,7 @@ test.failing('globals - nested property true.false', async (t) => { // When this behavior changes, update /docs/policy.md const shared = { context: { - a: { ok: 42, b: { c: ()=>42, notOk:41 }}, + a: { ok: 42, b: { c: () => 42, notOk:41 }}, }, config: { resources: { @@ -351,9 +357,9 @@ test.failing('globals - nested property true.false', async (t) => { globals: { 'a': true, 'a.b': false, - } + }, }, - } + }, }, } const handlesAccess = createScenarioFromScaffold({ @@ -362,9 +368,9 @@ test.failing('globals - nested property true.false', async (t) => { a: !!globalThis.a, a_ok: !!globalThis.a.ok, a_b: !!globalThis.a.b, - }; + } }, - ...shared + ...shared, }) const testResult = await runScenario({ scenario: handlesAccess }) @@ -386,33 +392,33 @@ test('globals - firefox addon chrome api lazy getter works', async (t) => { function exportLazyGetter(object, prop, getter) { let redefine = value => { if (value === undefined) { - delete object[prop]; + delete object[prop] } else { Object.defineProperty(object, prop, { enumerable: true, configurable: true, writable: true, value, - }); + }) } - getter = null; + getter = null - return value; - }; + return value + } Object.defineProperty(object, prop, { enumerable: true, configurable: true, get: function() { - return redefine(getter.call(this)); + return redefine(getter.call(this)) }, set: function(value) { - redefine(value); - } - }); + redefine(value) + }, + }) } exportLazyGetter(globalThis, 'chrome', () => 'xyz') }, @@ -420,16 +426,16 @@ test('globals - firefox addon chrome api lazy getter works', async (t) => { resources: { one: { globals: { - 'chrome': true - } + 'chrome': true, + }, }, - } + }, }, context: { chrome: { - runtime: 'xyz' - } - } + runtime: 'xyz', + }, + }, }) const testResult = await runScenario({ scenario }) t.is(testResult, 'xyz', 'expected result, did not error') diff --git a/packages/core/test/makeGetEndowmentsForConfig.spec.js b/packages/core/test/makeGetEndowmentsForConfig.spec.js index 8959ea03d5..77fbb54182 100644 --- a/packages/core/test/makeGetEndowmentsForConfig.spec.js +++ b/packages/core/test/makeGetEndowmentsForConfig.spec.js @@ -11,13 +11,13 @@ test('getEndowmentsForConfig', (t) => { const getEndowmentsForConfig = prepareTest() const sourceGlobal = { namespace: { - stringValue: 'yabbadabbadoo' - } + stringValue: 'yabbadabbadoo', + }, } const config = { globals: { - 'namespace.stringValue.includes': true - } + 'namespace.stringValue.includes': true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) t.is(sourceGlobal.namespace.stringValue.includes('dab'), true) @@ -30,8 +30,8 @@ test('getEndowmentsForConfig - siblings', (t) => { const config = { globals: { 'Buffer.from': true, - 'Buffer.isBuffer': true - } + 'Buffer.isBuffer': true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) { @@ -40,7 +40,7 @@ test('getEndowmentsForConfig - siblings', (t) => { t.is(typeof resultProp.value, 'function') t.deepEqual(resultProp, { ...sourceProp, - value: resultProp.value + value: resultProp.value, }, 'prop descriptor matches (except value)') } { @@ -49,18 +49,20 @@ test('getEndowmentsForConfig - siblings', (t) => { t.is(typeof resultProp.value, 'function') t.deepEqual(resultProp, { ...sourceProp, - value: resultProp.value + value: resultProp.value, }, 'prop descriptor matches (except value)') } }) test('getEndowmentsForConfig - getter', (t) => { const getEndowmentsForConfig = prepareTest() - const sourceGlobal = { get abc () { return { xyz: 42 } } } + const sourceGlobal = { get abc () { + return { xyz: 42 } + } } const config = { globals: { - 'abc.xyz': true - } + 'abc.xyz': true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) { @@ -72,7 +74,7 @@ test('getEndowmentsForConfig - getter', (t) => { enumerable, configurable, value: resultProp.value, - writable: true + writable: true, }, 'prop descriptor matches (except value)') } }) @@ -84,12 +86,12 @@ test('getEndowmentsForConfig - ensure window.document getter behavior support', const sourceGlobal = { get xyz() { return this - } + }, } const config = { globals: { - xyz: true - } + xyz: true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) @@ -110,12 +112,12 @@ test('getEndowmentsForConfig - specify unwrap to', (t) => { const sourceGlobal = { get xyz() { return this - } + }, } const config = { globals: { - xyz: true - } + xyz: true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config, unwrapTo) const getter = Reflect.getOwnPropertyDescriptor(resultGlobal, 'xyz').get @@ -137,12 +139,12 @@ test('getEndowmentsForConfig - specify unwrap from, unwrap to', (t) => { const sourceGlobal = { get xyz() { return this - } + }, } const config = { globals: { - xyz: true - } + xyz: true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config, unwrapTo, unwrapFrom) const getter = Reflect.getOwnPropertyDescriptor(resultGlobal, 'xyz').get @@ -161,12 +163,14 @@ test('getEndowmentsForConfig - endowing bind of a function', async (t) => { 'use strict' const getEndowmentsForConfig = prepareTest() const sourceGlobal = { - abc: function () { return this } + abc: function () { + return this + }, } const config = { globals: { - 'abc.bind': true - } + 'abc.bind': true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) @@ -185,12 +189,14 @@ test('getEndowmentsForConfig - ensure setTimeout calls dont trigger illegal invo // compartment.globalThis.document would error because 'this' value is not window const getEndowmentsForConfig = prepareTest() const sourceGlobal = { - setTimeout () { return this } + setTimeout () { + return this + }, } const config = { globals: { - setTimeout: true - } + setTimeout: true, + }, } const resultGlobal = getEndowmentsForConfig(sourceGlobal, config) t.is(resultGlobal.setTimeout(), sourceGlobal) diff --git a/packages/core/test/mergePolicy.spec.js b/packages/core/test/mergePolicy.spec.js index bdc328ad89..38f94a8bc5 100644 --- a/packages/core/test/mergePolicy.spec.js +++ b/packages/core/test/mergePolicy.spec.js @@ -8,28 +8,28 @@ testMerge('merge with resources', { globals: { abc: true, xyz: false, - 'a.b.c': true + 'a.b.c': true, }, builtin: { derp: true, - qwerty: false - } - } - } + qwerty: false, + }, + }, + }, }, { resources: { babel: { globals: { def: true, ghi: false, - 'a.b': true + 'a.b': true, }, builtin: { derp: true, - qwerty: false - } - } - } + qwerty: false, + }, + }, + }, }, { resources: { babel: { @@ -38,14 +38,14 @@ testMerge('merge with resources', { xyz: false, def: true, ghi: false, - 'a.b': true + 'a.b': true, }, builtin: { derp: true, - qwerty: false - } - } - } + qwerty: false, + }, + }, + }, }) testMerge('overrides to disallow', { @@ -55,27 +55,27 @@ testMerge('overrides to disallow', { abc: true, xyz: false, 'a.b': true, - 'q.w.e': true + 'q.w.e': true, }, builtin: { derp: true, - qwerty: false - } - } - } + qwerty: false, + }, + }, + }, }, { resources: { babel: { globals: { abc: false, 'a.b.c': false, // this is not supported - 'q.w': false + 'q.w': false, }, builtin: { derp: false, - } - } - } + }, + }, + }, }, { resources: { babel: { diff --git a/packages/core/test/scenarios/autogen.js b/packages/core/test/scenarios/autogen.js index fb5fc397cd..ed02266914 100644 --- a/packages/core/test/scenarios/autogen.js +++ b/packages/core/test/scenarios/autogen.js @@ -15,9 +15,9 @@ module.exports = [ // eslint-disable-next-line module.exports.check = (target) => target.hasOwnProperty('Number') }, - expectedResult: true + expectedResult: true, }) await autoConfigForScenario({ scenario }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/basic.js b/packages/core/test/scenarios/basic.js index b42a6024a3..74d1909e21 100644 --- a/packages/core/test/scenarios/basic.js +++ b/packages/core/test/scenarios/basic.js @@ -8,9 +8,11 @@ module.exports = [ module.exports = require('two')(5) }, defineTwo: () => { - module.exports = function (n) { return n * 111 } + module.exports = function (n) { + return n * 111 + } }, - expectedResult: 555 + expectedResult: 555, }) return scenario }, @@ -27,7 +29,7 @@ module.exports = [ // dummy testResult to make sure everything worked module.exports = 123 }, - expectedResult: 123 + expectedResult: 123, }) return scenario }, @@ -36,12 +38,14 @@ module.exports = [ name: 'basic - Function constructor for constructing constructor functions', defineOne: () => { const abc = new Function('this.value = this.derp()') - abc.prototype.derp = function() { return 123 } + abc.prototype.derp = function() { + return 123 + } const xyz = new abc() module.exports = xyz.value }, - expectedResult: 123 + expectedResult: 123, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/config.js b/packages/core/test/scenarios/config.js index a1d4343b66..c59f292180 100644 --- a/packages/core/test/scenarios/config.js +++ b/packages/core/test/scenarios/config.js @@ -52,12 +52,12 @@ module.exports = [ resources: { one: { globals: { - 'globalThis.__proto__': true - } - } - } + 'globalThis.__proto__': true, + }, + }, + }, }, - expectedFailure: true + expectedFailure: true, }) return scenario }, @@ -68,12 +68,12 @@ module.exports = [ resources: { one: { packages: { - two: false - } - } - } + two: false, + }, + }, + }, }, - expectedFailure: true + expectedFailure: true, }) return scenario }, @@ -146,13 +146,13 @@ module.exports = [ resourcessssss: { three: { packages: { - two: true - } - } - } + two: true, + }, + }, + }, }, expectedFailure: true, - defaultPolicy: false + defaultPolicy: false, }) return scenario }, @@ -163,13 +163,13 @@ module.exports = [ resources: { three: { packagesssss: { - two: true - } - } - } + two: true, + }, + }, + }, }, expectedFailure: true, - defaultPolicy: false + defaultPolicy: false, }) return scenario }, @@ -180,16 +180,16 @@ module.exports = [ resources: { three: { packages: { - two: true + two: true, }, globalsss: { - console: true - } - } - } + console: true, + }, + }, + }, }, expectedFailure: true, - defaultPolicy: false + defaultPolicy: false, }) return scenario }, @@ -200,16 +200,16 @@ module.exports = [ resources: { three: { packages: { - two: true + two: true, }, globals: { - console: false - } - } - } + console: false, + }, + }, + }, }, expectedFailure: true, - defaultPolicy: false + defaultPolicy: false, }) return scenario }, @@ -220,39 +220,39 @@ module.exports = [ resources: { '$root$': { packages: { - two: true - } + two: true, + }, }, one: { packages: { - two: true - } + two: true, + }, }, two: { packages: { - three: true - } - } - } + three: true, + }, + }, + }, }, configOverride: { resources: { '$root$': { packages: { - two: true - } + two: true, + }, }, two: { packages: { - three: true + three: true, }, globals: { - console: 'write' - } - } - } - } + console: 'write', + }, + }, + }, + }, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/endowments.js b/packages/core/test/scenarios/endowments.js index db73cfba38..883284bee5 100644 --- a/packages/core/test/scenarios/endowments.js +++ b/packages/core/test/scenarios/endowments.js @@ -23,23 +23,23 @@ module.exports = [ testCheck: (target) => { // console.log(`Test Check: target: ${target} testObj: ${testObj}`) return target === testObj - } + }, }, config: { resources: { one: { globals: { - testCheck: true - } + testCheck: true, + }, }, two: { globals: { - testGet: true - } - } - } + testGet: true, + }, + }, + }, }, - expectedResult: true + expectedResult: true, }) return scenario }, @@ -49,7 +49,7 @@ module.exports = [ defineEntry: () => { const testResult = { root: Date.now(), - non: require('one') + non: require('one'), } // standard test result serialization console.log(JSON.stringify(testResult, null, 2)) @@ -67,8 +67,8 @@ module.exports = [ // more recent than 2020-01-01T00:00:00.000Z return time > 1577836800000 } - } + }, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/exportsDefense.js b/packages/core/test/scenarios/exportsDefense.js index 31722e9a03..29ffbcc263 100644 --- a/packages/core/test/scenarios/exportsDefense.js +++ b/packages/core/test/scenarios/exportsDefense.js @@ -13,7 +13,7 @@ module.exports = [ defineTwo: () => { module.exports = { xyz: 1 } }, - expectedResult: 2 + expectedResult: 2, }) return scenario }, @@ -29,7 +29,7 @@ module.exports = [ defineTwo: () => { module.exports = { xyz: 1 } }, - expectedResult: 1 + expectedResult: 1, }) return scenario }, @@ -42,10 +42,10 @@ module.exports = [ defineTwo: () => { module.exports = undefined }, - expectedResult: null + expectedResult: null, }) return scenario - } + }, // async () => { // const scenario = createScenarioFromScaffold({ // name: 'exportsDefense - indirectly imported package should be readOnly', diff --git a/packages/core/test/scenarios/globalRef.js b/packages/core/test/scenarios/globalRef.js index dec27caca9..083295efa4 100644 --- a/packages/core/test/scenarios/globalRef.js +++ b/packages/core/test/scenarios/globalRef.js @@ -6,16 +6,22 @@ module.exports = [ name: 'globalRef - check default containment', defineOne: () => { const testResults = {} - try { testResults.objCheckThis = this.Object === Object } catch (_) { } - try { testResults.objCheckGlobal = globalThis.Object === Object } catch (_) { } - try { testResults.thisIsExports = exports === this } catch (_) { } + try { + testResults.objCheckThis = this.Object === Object + } catch (_) { } + try { + testResults.objCheckGlobal = globalThis.Object === Object + } catch (_) { } + try { + testResults.thisIsExports = exports === this + } catch (_) { } module.exports = testResults }, expectedResult: { objCheckThis: false, objCheckGlobal: true, - thisIsExports: true - } + thisIsExports: true, + }, }) return scenario }, @@ -40,12 +46,14 @@ module.exports = [ } catch (e) { error = e // This works if the window reference is available - if (typeof window === 'object') g = window + if (typeof window === 'object') { + g = window + } } // test webpack result against globalThis module.exports = { match: g === globalThis, type: typeof g, error: error && error.message } }, - expectedResult: { match: true, type: 'object' } + expectedResult: { match: true, type: 'object' }, }) return scenario }, @@ -55,8 +63,8 @@ module.exports = [ defineOne: () => { module.exports = function () {} instanceof globalThis.Function }, - expectedResult: true + expectedResult: true, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/globalWrites.js b/packages/core/test/scenarios/globalWrites.js index 45746247a5..2e4c09af23 100644 --- a/packages/core/test/scenarios/globalWrites.js +++ b/packages/core/test/scenarios/globalWrites.js @@ -18,26 +18,26 @@ module.exports = [ resources: { one: { packages: { - two: true - } + two: true, + }, }, two: { globals: { - xyz: 'write' + xyz: 'write', }, packages: { - three: true - } + three: true, + }, }, three: { globals: { - xyz: true - } - } - } + xyz: true, + }, + }, + }, }, - expectedResult: true + expectedResult: true, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/moduleExports.js b/packages/core/test/scenarios/moduleExports.js index 274a4b6e79..0747a9184d 100644 --- a/packages/core/test/scenarios/moduleExports.js +++ b/packages/core/test/scenarios/moduleExports.js @@ -13,8 +13,8 @@ module.exports = [ module.exports = {} }, expectedResult: { - xyz: 42 - } + xyz: 42, + }, }) return scenario }, @@ -26,7 +26,7 @@ module.exports = [ two.xyz = 42 module.exports = { xyz: two.xyz, - call: two() + call: two(), } }, defineTwo: () => { @@ -34,8 +34,8 @@ module.exports = [ }, expectedResult: { xyz: 42, - call: 100 - } + call: 100, + }, }) return scenario }, @@ -48,7 +48,7 @@ module.exports = [ module.exports = { abc: new ModernClass().abc, jkl: ModernClass.jkl, - xyz: ModernClass.xyz + xyz: ModernClass.xyz, } }, defineTwo: () => { @@ -63,8 +63,8 @@ module.exports = [ expectedResult: { abc: 123, jkl: 101, - xyz: 42 - } + xyz: 42, + }, }) return scenario }, @@ -81,7 +81,7 @@ module.exports = [ } module.exports = { abc: new NewClass().abc, - jkl: NewClass.jkl + jkl: NewClass.jkl, } }, defineTwo: () => { @@ -95,8 +95,8 @@ module.exports = [ }, expectedResult: { abc: 456, - jkl: 101 - } + jkl: 101, + }, }) return scenario }, @@ -110,7 +110,7 @@ module.exports = [ defineTwo: () => { module.exports = [1, 2, 3] }, - expectedResult: true + expectedResult: true, }) return scenario }, @@ -126,7 +126,7 @@ module.exports = [ defineTwo: () => { module.exports = { xyz: () => ({}) } }, - expectedResult: 123 + expectedResult: 123, }) return scenario }, @@ -142,28 +142,28 @@ module.exports = [ }, defineTwo: () => { module.exports = { - get: () => globalThis.get() + get: () => globalThis.get(), } }, config: { resources: { one: { globals: { - check: true - } + check: true, + }, }, two: { globals: { - get: true - } - } - } + get: true, + }, + }, + }, }, context: { get: () => testObj, - check: (target) => target === testObj + check: (target) => target === testObj, }, - expectedResult: true + expectedResult: true, }) return scenario }, @@ -179,32 +179,32 @@ module.exports = [ }, defineOne: () => { module.exports = { - get: () => globalThis.get() + get: () => globalThis.get(), } }, config: { resources: { '$root$': { packages: { - one: true + one: true, }, globals: { - check: true - } + check: true, + }, }, one: { globals: { - get: true - } - } - } + get: true, + }, + }, + }, }, context: { get: () => testObj, - check: (target) => target === testObj + check: (target) => target === testObj, }, - expectedResult: true + expectedResult: true, }) return scenario - } + }, ] diff --git a/packages/core/test/scenarios/scuttle.js b/packages/core/test/scenarios/scuttle.js index 465834ebec..74a7c4656c 100644 --- a/packages/core/test/scenarios/scuttle.js +++ b/packages/core/test/scenarios/scuttle.js @@ -21,8 +21,8 @@ module.exports = [ scuttleGlobalThis: { enabled: true, exceptions: ['WebAssembly', 'process', '/[0-9]+/', 'Set', 'Reflect', 'Object', 'console', 'Array', 'RegExp', 'Date', 'Math'], - } - } + }, + }, }) await autoConfigForScenario({ scenario }) return scenario @@ -34,8 +34,8 @@ module.exports = [ opts: { scuttleGlobalThis: { enabled: true, - exceptions: ['WebAssembly', 'process', '/[0-9]+/', /*'Set', 'Reflect', 'Object', 'console', 'Array', 'RegExp', 'Date', 'Math'*/], - } + exceptions: ['WebAssembly', 'process', '/[0-9]+/' /*'Set', 'Reflect', 'Object', 'console', 'Array', 'RegExp', 'Date', 'Math'*/], + }, }, expectedFailure: true, expectedFailureMessageRegex: /SES_UNHANDLED_REJECTION|inaccessible under scuttling mode./, diff --git a/packages/core/test/scenarios/security.js b/packages/core/test/scenarios/security.js index 98a91f94a5..bc8f4f16db 100644 --- a/packages/core/test/scenarios/security.js +++ b/packages/core/test/scenarios/security.js @@ -9,10 +9,14 @@ module.exports = [ module.exports = { objectXyz: 'xyz' in Object, protoXyz: 'xyz' in Object.prototype } }, defineTwo: () => { - try { Object.xyz = 123 } catch (_) { } - try { Object.protoype.xyz = 123 } catch (_) { } + try { + Object.xyz = 123 + } catch (_) { } + try { + Object.protoype.xyz = 123 + } catch (_) { } }, - expectedResult: { objectXyz: false, protoXyz: false } + expectedResult: { objectXyz: false, protoXyz: false }, }) return scenario }, @@ -23,12 +27,14 @@ module.exports = [ module.exports = typeof require('two') === 'function' }, defineTwo: () => { - try { module.exports = setTimeout } catch (_) {} + try { + module.exports = setTimeout + } catch (_) {} }, - expectedResult: false + expectedResult: false, }) return scenario - } + }, // async () => { // const scenario = createScenarioFromScaffold({ // name: 'security - prevent module exports shallow mutation', diff --git a/packages/core/test/scenarios/transforms.js b/packages/core/test/scenarios/transforms.js index 83da721b00..ae7c2d629c 100644 --- a/packages/core/test/scenarios/transforms.js +++ b/packages/core/test/scenarios/transforms.js @@ -13,7 +13,7 @@ module.exports = [ const importString = 'import x from "y"' module.exports = { comment, importString } }, - testType: 'truthy' + testType: 'truthy', }) return scenario }, @@ -34,7 +34,7 @@ module.exports = [ module.exports = SubError /* eslint-enable */ }, - testType: 'truthy' + testType: 'truthy', }) return scenario }, @@ -54,8 +54,8 @@ module.exports = [ function SuperClass () {} module.exports = SuperClass }, - testType: 'truthy' + testType: 'truthy', }) return scenario - } + }, ] diff --git a/packages/core/test/util.js b/packages/core/test/util.js index 405d53099e..24ae614b3d 100644 --- a/packages/core/test/util.js +++ b/packages/core/test/util.js @@ -19,7 +19,7 @@ module.exports = { createHookedConsole, fillInFileDetails, functionToString, - runAndTestScenario + runAndTestScenario, } async function generatePolicyFromFiles ({ files, ...opts }) { @@ -33,7 +33,7 @@ async function generatePolicyFromFiles ({ files, ...opts }) { }, isBuiltin: () => false, includeDebugInfo: false, - ...opts + ...opts, }) return config @@ -42,7 +42,7 @@ async function generatePolicyFromFiles ({ files, ...opts }) { function createScenarioFromScaffold ({ name = 'template scenario', expectedResult = { - value: 'this is module two' + value: 'this is module two', }, testType = 'deepEqual', checkPostRun = async (t, result, err, scenario) => { @@ -99,13 +99,13 @@ function createScenarioFromScaffold ({ function _defineTwo () { module.exports = { - value: 'this is module two' + value: 'this is module two', } } function _defineThree () { module.exports = { - value: 'this is module three' + value: 'this is module three', } } @@ -116,9 +116,9 @@ function createScenarioFromScaffold ({ importMap: { one: 'node_modules/one/index.js', two: 'node_modules/two/index.js', - three: 'node_modules/three/index.js' + three: 'node_modules/three/index.js', }, - entry: true + entry: true, }, 'package.json': { content: `${JSON.stringify({ @@ -128,7 +128,7 @@ function createScenarioFromScaffold ({ three: '1.0.0', }, devDependencies: { - } + }, }, null, 2)}`, }, 'node_modules/one/index.js': { @@ -136,46 +136,46 @@ function createScenarioFromScaffold ({ content: `(${defineOne || _defineOne}).call(this)`, importMap: { two: 'node_modules/two/index.js', - three: 'node_modules/three/index.js' - } + three: 'node_modules/three/index.js', + }, }, 'node_modules/one/package.json': { content: `${JSON.stringify({ dependencies: { two: '1.0.0', three: '1.0.0', - } + }, }, null, 2)}`, }, 'node_modules/two/index.js': { packageName: 'two', content: `(${defineTwo || _defineTwo}).call(this)`, importMap: { - three: 'node_modules/three/index.js' - } + three: 'node_modules/three/index.js', + }, }, 'node_modules/two/package.json': { content: `${JSON.stringify({ dependencies: { three: '1.0.0', - } + }, }, null, 2)}`, }, 'node_modules/three/index.js': { packageName: 'three', content: `(${defineThree || _defineThree}).call(this)`, importMap: { - one: 'node_modules/one/index.js' - } + one: 'node_modules/one/index.js', + }, }, 'node_modules/three/package.json': { content: `${JSON.stringify({ dependencies: { one: '1.0.0', - } + }, }, null, 2)}`, }, - ...files + ...files, }) let _config @@ -185,15 +185,15 @@ function createScenarioFromScaffold ({ one: { packages: { two: true, - three: true - } + three: true, + }, }, two: { packages: { - three: true - } - } - } + three: true, + }, + }, + }, }, config) } else { _config = config @@ -203,10 +203,10 @@ function createScenarioFromScaffold ({ resources: { one: { packages: { - five: true - } - } - } + five: true, + }, + }, + }, }, configOverride) return { @@ -233,7 +233,9 @@ function createScenarioFromScaffold ({ function createHookedConsole () { let hasResolved = false let resolve - const firstLogEventPromise = new Promise(_resolve => { resolve = _resolve }) + const firstLogEventPromise = new Promise(_resolve => { + resolve = _resolve + }) const hookedLog = (message) => { if (hasResolved) { throw new Error(`console.log called multiple times. got "${message}"`) @@ -269,8 +271,8 @@ async function runScenario ({ builtin, kernelArgs = {}, opts = {}, - beforeCreateKernel = () => {} -} = scenario + beforeCreateKernel = () => {}, + } = scenario const lavamoatConfig = mergeDeep(config, configOverride) const kernelSrc = generateKernel(opts) const { hookedConsole, firstLogEventPromise } = createHookedConsole() @@ -296,7 +298,7 @@ async function runScenario ({ type: moduleRecord.type, file: moduleRecord.file, deps: moduleRecord.importMap, - moduleInitializer: moduleRecord.moduleInitializer + moduleInitializer: moduleRecord.moduleInitializer, } // append the source or prepare the precompiledInitializer const intializerSource = `(function(exports, require, module, __filename, __dirname){\n${applySourceTransforms(moduleRecord.content)}\n})` @@ -371,7 +373,9 @@ function moduleDataForBuiltin (builtinObj, name) { file: name, package: name, type: 'builtin', - moduleInitializer: (_, _2, module) => { module.exports = builtinObj[name] } + moduleInitializer: (_, _2, module) => { + module.exports = builtinObj[name] + }, } } @@ -423,10 +427,10 @@ async function createConfigForTest (testFn, opts = {}) { file: './entry.js', packageName: '$root$', importMap: { - test: './node_modules/test/index.js' + test: './node_modules/test/index.js', }, content: 'require("test")', - entry: true + entry: true, }, { // non-entry type: 'js', @@ -434,7 +438,7 @@ async function createConfigForTest (testFn, opts = {}) { file: './node_modules/test/index.js', packageName: 'test', importMap: {}, - content: `(${testFn})()` + content: `(${testFn})()`, }] const policy = await generatePolicyFromFiles({ files, ...opts }) return policy @@ -448,7 +452,9 @@ async function autoConfigForScenario ({ scenario, opts = {} }) { function convertOptsToArgs ({ scenario }) { const { entries } = scenario - if (entries.length !== 1) throw new Error('LavaMoat - invalid entries') + if (entries.length !== 1) { + throw new Error('LavaMoat - invalid entries') + } const firstEntry = entries[0] return [firstEntry] } diff --git a/packages/lavapack/src/pack.js b/packages/lavapack/src/pack.js index c64326654a..0a3e341e12 100644 --- a/packages/lavapack/src/pack.js +++ b/packages/lavapack/src/pack.js @@ -15,7 +15,7 @@ const assert = require('assert') const JSONStream = require('JSONStream') const through = require('through2') const umd = require('umd') -// eslint-disable-next-line node/prefer-global/buffer +// eslint-disable-next-line n/prefer-global/buffer const { Buffer } = require('buffer') const combineSourceMap = require('combine-source-map') const convertSourceMap = require('convert-source-map') diff --git a/packages/lavapack/test/index.spec.js b/packages/lavapack/test/index.spec.js index 10ab7a8c50..a5e21de1c4 100644 --- a/packages/lavapack/test/index.spec.js +++ b/packages/lavapack/test/index.spec.js @@ -8,7 +8,7 @@ const pack = require('../src') test('dummy test', (t) => { pack({ - includePrelude: false + includePrelude: false, }) t.pass('no error thrown') }) @@ -27,7 +27,7 @@ test('sourcemap test', async (t) => { pipe( packStream, concat(resolve), - callback + callback, ) // add modules @@ -37,9 +37,9 @@ test('sourcemap test', async (t) => { source: 'require(\'./log.js\'); require(\'./util.js\')', deps: { './log.js': '2', - './util.js': '3' + './util.js': '3', }, - entry: true + entry: true, }, { id: '2', sourceFile: 'log.js', diff --git a/packages/lavapack/test/runtimeEcma.spec.js b/packages/lavapack/test/runtimeEcma.spec.js index 1ef1444181..d0407f01e5 100644 --- a/packages/lavapack/test/runtimeEcma.spec.js +++ b/packages/lavapack/test/runtimeEcma.spec.js @@ -2,7 +2,7 @@ const test = require('ava') const fs = require('node:fs') const espree = require('espree') -const ECMA_VERSION = 2020; +const ECMA_VERSION = 2020 test('runtime.js parses as ECMA 2020', (t) => { const code = fs.readFileSync(require.resolve('../src/runtime.js'), 'utf8') diff --git a/packages/lavapack/test/sourcemaps.spec.js b/packages/lavapack/test/sourcemaps.spec.js index a6d2f85a2a..1970ae3467 100644 --- a/packages/lavapack/test/sourcemaps.spec.js +++ b/packages/lavapack/test/sourcemaps.spec.js @@ -20,11 +20,13 @@ test.skip('sourcemaps - adjust maps for wrapper', async (t) => { filename: './foo.js', // inline sourcemaps with sources included url: 'inline', - includeSources: true - } + includeSources: true, + }, }) - if (result.error) t.ifError(result.error) + if (result.error) { + t.ifError(result.error) + } // ensure minification worked t.true(indicesOf('\n', fooSource).length > 1) @@ -34,12 +36,14 @@ test.skip('sourcemaps - adjust maps for wrapper', async (t) => { const wrappedSourceMeta = wrapIntoModuleInitializer(result.code) await validateSourcemaps(t, wrappedSourceMeta) - }) +}) function indicesOf (substring, string) { const result = [] let index = -1 - while ((index = string.indexOf(substring, index + 1)) >= 0) result.push(index) + while ((index = string.indexOf(substring, index + 1)) >= 0) { + result.push(index) + } return result } @@ -68,7 +72,9 @@ async function validateSourcemaps (t, sourceMeta) { const sourceContent = consumer.sourceContentFor(result.source) const sourceLines = sourceContent.split('\n') const line = sourceLines[result.line - 1] - if (!line.includes(targetSlug)) t.fail(`could not find target "${targetSlug}" in source`) + if (!line.includes(targetSlug)) { + t.fail(`could not find target "${targetSlug}" in source`) + } }) }) t.true(true, 'sourcemaps look ok') diff --git a/packages/node/test/arguments.spec.js b/packages/node/test/arguments.spec.js index 07b15bfedc..e4b6309a5e 100644 --- a/packages/node/test/arguments.spec.js +++ b/packages/node/test/arguments.spec.js @@ -12,8 +12,8 @@ test.skip('arguments - lavamoat command aliases work - autoconfig', async (t) => }, expectedResult: 5, opts: { - ar: true - } + ar: true, + }, }) const testResult = await runScenario({ scenario }) scenario.checkResult(t, testResult, scenario) @@ -27,8 +27,8 @@ test.skip('arguments - lavamoat command aliases work - advanced', async (t) => { expectedResult: 5, opts: { d: true, - dp: true - } + dp: true, + }, }) const testResult = await runScenario({ scenario }) scenario.checkResult(t, testResult, scenario) @@ -42,9 +42,9 @@ test.skip('arguments - invalid lavamoat commands fail', async (t) => { }, opts: { z: true, - c: true + c: true, }, - expectedFailure: true + expectedFailure: true, }) await runAndTestScenario(t, scenario, runScenario) }) diff --git a/packages/node/test/envConfig.spec.js b/packages/node/test/envConfig.spec.js index c78d8147fa..c2e2bb447e 100644 --- a/packages/node/test/envConfig.spec.js +++ b/packages/node/test/envConfig.spec.js @@ -8,7 +8,7 @@ test('envConfig - intrinsic prototype mutating package running in unfrozen realm const two = require('two') module.exports = { one: Function.prototype.xyz, - two + two, } }, defineTwo: () => { @@ -17,15 +17,15 @@ test('envConfig - intrinsic prototype mutating package running in unfrozen realm module.exports = Function.prototype.xyz }, expectedResult: { - two: 'Hello' + two: 'Hello', }, config: { resources: { two: { - env: 'unfrozen' - } - } - } + env: 'unfrozen', + }, + }, + }, }) const testResult = await runScenario({ scenario }) scenario.checkResult(t, testResult, scenario) @@ -38,7 +38,7 @@ test('envConfig - module.exports from the same Realm as its Compartment', async module.exports = { one: module.exports instanceof Object, two: two.isSameRealm, - cross: two.defaultExportsObj instanceof Object + cross: two.defaultExportsObj instanceof Object, } }, defineTwo: () => { @@ -46,21 +46,21 @@ test('envConfig - module.exports from the same Realm as its Compartment', async const isSameRealm = defaultExportsObj instanceof Object module.exports = { defaultExportsObj, - isSameRealm + isSameRealm, } }, expectedResult: { one: true, two: true, - cross: false + cross: false, }, config: { resources: { two: { - env: 'unfrozen' - } - } - } + env: 'unfrozen', + }, + }, + }, }) const testResult = await runScenario({ scenario }) scenario.checkResult(t, testResult, scenario) diff --git a/packages/node/test/globals.spec.js b/packages/node/test/globals.spec.js index adeafac14e..fb2de765a1 100644 --- a/packages/node/test/globals.spec.js +++ b/packages/node/test/globals.spec.js @@ -14,8 +14,8 @@ test('globals - has only the expected global circular refs', async (t) => { }, expectedResult: [ 'global', - 'globalThis' - ] + 'globalThis', + ], }) const testResult = await runScenario({ scenario }) t.is(Array.isArray(testResult), true) @@ -28,16 +28,22 @@ test('globalRef - globalRef - check default containment', async (t) => { name: 'globalRef - check default containment', defineOne: () => { const testResults = {} - try { testResults.objCheckThis = this.Object === Object } catch (_) { } - try { testResults.objCheckGlobal = global.Object === Object } catch (_) { } - try { testResults.thisIsExports = exports === this } catch (_) { } + try { + testResults.objCheckThis = this.Object === Object + } catch (_) { } + try { + testResults.objCheckGlobal = global.Object === Object + } catch (_) { } + try { + testResults.thisIsExports = exports === this + } catch (_) { } module.exports = testResults }, expectedResult: { objCheckThis: false, objCheckGlobal: true, - thisIsExports: true - } + thisIsExports: true, + }, }) const testResult = await runScenario({ scenario }) scenario.checkResult(t, testResult, scenario) diff --git a/packages/node/test/index.spec.js b/packages/node/test/index.spec.js index 83cb2620bd..5be3c7f648 100644 --- a/packages/node/test/index.spec.js +++ b/packages/node/test/index.spec.js @@ -8,8 +8,8 @@ test('parseForPolicy - resolutions', async (t) => { const resolutions = { a: { fs: `${projectRoot}/fake-fs.js`, - b: `${projectRoot}/fake-b.js` - } + b: `${projectRoot}/fake-b.js`, + }, } const policy1 = await parseForPolicy({ entryId, projectRoot }) @@ -17,18 +17,18 @@ test('parseForPolicy - resolutions', async (t) => { resources: { a: { builtin: { - 'fs.deleteEntireHardDrive': true + 'fs.deleteEntireHardDrive': true, }, packages: { - b: true - } + b: true, + }, }, b: { 'builtin': { - 'http': true - } - } - } + 'http': true, + }, + }, + }, }) const policy2 = await parseForPolicy({ entryId, projectRoot, policyOverride: { resolutions } }) @@ -37,10 +37,10 @@ test('parseForPolicy - resolutions', async (t) => { resources: { a: { packages: { - '$root$': true - } + '$root$': true, + }, }, - } + }, }, 'policy resources do not include data on packages not parsed due to resolutions') }) @@ -53,20 +53,20 @@ test('parseForPolicy - require a userspace package with a builtin name', async ( resources: { a: { packages: { - events: true - } + events: true, + }, }, b: { builtin: { - 'events.EventEmitter': true - } + 'events.EventEmitter': true, + }, }, events: { globals: { - console: true - } - } - } + console: true, + }, + }, + }, }) }) @@ -75,23 +75,23 @@ test('parseForPolicy - indirectly used packages are included in parent\'s allowl const entryId = `${projectRoot}/index.js` const policy = await parseForPolicy({ entryId, projectRoot }) t.deepEqual(policy, { - resources: { a: { builtin: { crypto: true } } } + resources: { a: { builtin: { crypto: true } } }, }) }) test('parseForPolicy - find node:-prefixed builtins', async (t) => { - const projectRoot = `${__dirname}/projects/6`; - const entryId = `${projectRoot}/index.js`; - const policy = await parseForPolicy({ entryId, projectRoot }); + const projectRoot = `${__dirname}/projects/6` + const entryId = `${projectRoot}/index.js` + const policy = await parseForPolicy({ entryId, projectRoot }) t.deepEqual(policy, { resources: { a: { builtin: { - 'node:events.EventEmitter': true - } - } - } - }); + 'node:events.EventEmitter': true, + }, + }, + }, + }) }) // run lavamoat-node @@ -100,12 +100,12 @@ test('execute - resolutions', async (t) => { const entryId = './index.js' const { output } = await runLavamoat({ cwd: projectRoot, - args: [entryId] + args: [entryId], }) t.deepEqual(output.stdout.split('\n'), [ 'fake-fs called', 'value: 42', - '' + '', ], 'should not have any standard output') }) @@ -114,11 +114,11 @@ test('execute - keccak with native modules', async (t) => { const entryId = './index.js' const { output } = await runLavamoat({ cwd: projectRoot, - args: [entryId] + args: [entryId], }) t.deepEqual(output.stdout.split('\n'), [ 'keccak256: 5cad7cf49f610ec53189e06d3c8668789441235613408f8fabcb4ad8dad94db5', - '' + '', ], 'should not have any standard output') }) @@ -127,10 +127,10 @@ test('execute - core modules and buffers', async (t) => { const entryId = './index.js' const { output } = await runLavamoat({ cwd: projectRoot, - args: [entryId] + args: [entryId], }) t.deepEqual(output.stdout.split('\n'), [ 'sha256: fb1520a08f1bc43831d0000dc76f6b0f027bafd36c55b1f43fc54c60c2f831da', - '' + '', ], 'should not have any standard output') }) diff --git a/packages/node/test/runScenarios.spec.js b/packages/node/test/runScenarios.spec.js index 9bead18cb8..adb0df4f1d 100644 --- a/packages/node/test/runScenarios.spec.js +++ b/packages/node/test/runScenarios.spec.js @@ -5,7 +5,9 @@ const { runAndTestScenario } = require('lavamoat-core/test/util') test('Run scenarios', async (t) => { for await (const scenario of loadScenarios()) { - if (!(Object.keys(scenario.context).length === 0 && scenario.context.constructor === Object)) continue + if (!(Object.keys(scenario.context).length === 0 && scenario.context.constructor === Object)) { + continue + } console.log(`Running Node Scenario: ${scenario.name}`) await runAndTestScenario(t, scenario, ({ scenario }) => runScenario({ scenario })) } diff --git a/packages/node/test/util.js b/packages/node/test/util.js index 6bd0f91df5..0ec4a5f616 100644 --- a/packages/node/test/util.js +++ b/packages/node/test/util.js @@ -3,7 +3,7 @@ const execFile = util.promisify(require('child_process').execFile) const { prepareScenarioOnDisk } = require('lavamoat-core/test/util.js') module.exports = { runLavamoat, - runScenario + runScenario, } function setOptToArgs(args, key, value) { @@ -26,7 +26,9 @@ function setOptToArgs(args, key, value) { function convertOptsToArgs ({ scenario }) { const { entries, opts } = scenario - if (entries.length !== 1) throw new Error('LavaMoat - invalid entries') + if (entries.length !== 1) { + throw new Error('LavaMoat - invalid entries') + } const firstEntry = entries[0] const args = [firstEntry] Object diff --git a/packages/node/test/waysToRun.spec.js b/packages/node/test/waysToRun.spec.js index 6ef50ef470..5769816b79 100644 --- a/packages/node/test/waysToRun.spec.js +++ b/packages/node/test/waysToRun.spec.js @@ -12,7 +12,7 @@ test('use lavamoat cli', async (t) => { const output = await execFile(lavamoatPath, [entryPath], { cwd: projectRoot }) t.deepEqual(output.stdout.split('\n'), [ 'keccak256: 5cad7cf49f610ec53189e06d3c8668789441235613408f8fabcb4ad8dad94db5', - '' + '', ], 'should return expected output') }) @@ -23,7 +23,7 @@ test('use lavamoat programmatically', async (t) => { await runLava({ entryPath, projectRoot, - debugMode: true + debugMode: true, }) // TODO: add means to endow entry with new references and pass a callback to assert it's been called. diff --git a/packages/perf/build.js b/packages/perf/build.js index 28b4880520..2ae013bb66 100644 --- a/packages/perf/build.js +++ b/packages/perf/build.js @@ -47,9 +47,11 @@ function performBundle () { bundler.bundle(), fs.createWriteStream(destPath), (err, bundle) => { - if (err) return reject(err) + if (err) { + return reject(err) + } resolve(bundle) - } + }, ) }) -} \ No newline at end of file +} diff --git a/packages/perf/endo.js b/packages/perf/endo.js index 1a36c40ee8..956b34a513 100644 --- a/packages/perf/endo.js +++ b/packages/perf/endo.js @@ -5,7 +5,7 @@ const crypto = require('crypto') require('ses') lockdown() -const rawModules = {}; +const rawModules = {} const syntheticModulesCompartment = new Compartment( {}, {}, @@ -14,24 +14,24 @@ const syntheticModulesCompartment = new Compartment( resolveHook: moduleSpecifier => moduleSpecifier, importHook: async moduleSpecifier => { const ns = - rawModules[moduleSpecifier].default || rawModules[moduleSpecifier]; + rawModules[moduleSpecifier].default || rawModules[moduleSpecifier] const staticModuleRecord = Object.freeze({ imports: [], exports: Array.from(new Set(Object.keys(ns).concat(['default']))), execute: moduleExports => { - Object.assign(moduleExports, ns); - moduleExports.default = ns; + Object.assign(moduleExports, ns) + moduleExports.default = ns }, - }); - return staticModuleRecord; + }) + return staticModuleRecord }, }, -); +) const addToCompartment = async (name, nsObject) => { - rawModules[name] = nsObject; - return (await syntheticModulesCompartment.import(name)).namespace; -}; + rawModules[name] = nsObject + return (await syntheticModulesCompartment.import(name)).namespace +} main().catch((err) => { @@ -40,14 +40,14 @@ main().catch((err) => { }) async function main () { - const { makeReadPowers } = await import('@endo/compartment-mapper/node-powers.js'); + const { makeReadPowers } = await import('@endo/compartment-mapper/node-powers.js') const { importLocation } = await import('@endo/compartment-mapper') - const { transforms } = await import('ses/tools.js'); + const { transforms } = await import('ses/tools.js') const { evadeHtmlCommentTest, evadeImportExpressionTest, applyTransforms, - } = transforms; + } = transforms const modules = { stream: await addToCompartment('stream', require('stream')), @@ -76,7 +76,7 @@ async function main () { moduleTransforms: { 'cjs': makeSesModuleTransform('cjs'), 'mjs': makeSesModuleTransform('mjs'), - } + }, }, ) @@ -105,7 +105,7 @@ async function main () { evadeHtmlCommentTest, evadeImportExpressionTest, (src) => { - const someDirectEvalPattern = /(^|[^.])\beval(\s*\()/g; + const someDirectEvalPattern = /(^|[^.])\beval(\s*\()/g return src.replaceAll(someDirectEvalPattern, '$1(0,eval)(') }, ]) diff --git a/packages/survey/src/downloadPackage.js b/packages/survey/src/downloadPackage.js index edd6597f27..31e7492a99 100644 --- a/packages/survey/src/downloadPackage.js +++ b/packages/survey/src/downloadPackage.js @@ -4,7 +4,7 @@ const { promises: fs } = require('fs') const { resolve } = require('path') module.exports = { - downloadPackage + downloadPackage, } diff --git a/packages/survey/src/execTest.js b/packages/survey/src/execTest.js index bdbbc0f064..3ea861b58c 100644 --- a/packages/survey/src/execTest.js +++ b/packages/survey/src/execTest.js @@ -6,11 +6,13 @@ const { spawn, exec: execCb } = require('child_process') const exec = promisify(execCb) -const makeTempDir = async () => { return await fs.mkdtemp(path.join(os.tmpdir(), 'lavamoat-survey-')) } -const mitmPath = new URL("../mitm", `file://${__filename}`).pathname; +const makeTempDir = async () => { + return await fs.mkdtemp(path.join(os.tmpdir(), 'lavamoat-survey-')) +} +const mitmPath = new URL('../mitm', `file://${__filename}`).pathname module.exports = { - execTest + execTest, } execTest({ @@ -23,7 +25,7 @@ execTest({ // 4. run tests (lavamoat gen-and-run) async function execTest ({ gitRepo, gitRef }) { const projectDir = await makeTempDir() - console.log(`running lavamoat exec test`) + console.log('running lavamoat exec test') console.log(`${gitRepo} #${gitRef ? gitRef : ''} in ${projectDir}`) await prepareRepo({ projectDir, gitRepo, gitRef }) await installDependencies({ projectDir }) @@ -33,18 +35,20 @@ async function execTest ({ gitRepo, gitRef }) { async function prepareRepo ({ projectDir, gitRepo, gitRef }) { await exec(`git clone ${gitRepo} .`, { cwd: projectDir }) - if (gitRef) await exec(`git checkout ${gitRef}`, { cwd: projectDir }) + if (gitRef) { + await exec(`git checkout ${gitRef}`, { cwd: projectDir }) + } console.log(`repo prepared ${projectDir}`) } async function installDependencies ({ projectDir }) { - const { stdout, stderr } = await exec(`yarn install`, { cwd: projectDir }) - console.log(`deps installed`) + const { stdout, stderr } = await exec('yarn install', { cwd: projectDir }) + console.log('deps installed') } async function runPlainTests ({ projectDir }) { - const { stdout, stderr } = await exec(`yarn run test`, { cwd: projectDir }) - console.log(`tests passed directly`) + const { stdout, stderr } = await exec('yarn run test', { cwd: projectDir }) + console.log('tests passed directly') } async function runLavamoatTests ({ projectDir }) { @@ -59,7 +63,7 @@ async function mitmExec(arg, args, opts) { const child = spawn(arg, args, { env: { ...env, PATH: `${mitmPath}:${env.PATH}` }, stdio: 'inherit', - ...opts - }); - return new Promise(resolve => child.on('exit', resolve)); -} \ No newline at end of file + ...opts, + }) + return new Promise(resolve => child.on('exit', resolve)) +} diff --git a/packages/survey/src/getTopPackages.js b/packages/survey/src/getTopPackages.js index f9134ba0f9..3d3d57cc95 100644 --- a/packages/survey/src/getTopPackages.js +++ b/packages/survey/src/getTopPackages.js @@ -7,7 +7,7 @@ const pLimit = require('p-limit') const concurrencyLimit = pLimit(8) module.exports = { - getTopPackages + getTopPackages, } const npmDependentsScraper = createScraper({ @@ -66,11 +66,13 @@ function createScraper ({ buildUrl, entrySelector, packagesPerPage, maxResults } return downloadTopPackages async function downloadTopPackages (count) { - if (maxResults !== undefined) count = Math.max(count, maxResults) + if (maxResults !== undefined) { + count = Math.max(count, maxResults) + } const pagesRequired = Math.ceil(count / packagesPerPage) const pageResults = await Promise.all(Array(pagesRequired).fill().map(async (_, index) => { return concurrencyLimit( - () => downloadPage(index) + () => downloadPage(index), ) }), { concurrency: 8 }) return pageResults.flat().slice(0, count) @@ -81,7 +83,9 @@ function createScraper ({ buildUrl, entrySelector, packagesPerPage, maxResults } const url = buildUrl({ page, offset }) const res = await fetch(url) const content = await res.text() - if (res.status !== 200) throw new Error(`Error fetching "${url}":\n${content}`) + if (res.status !== 200) { + throw new Error(`Error fetching "${url}":\n${content}`) + } const $ = cheerio.load(content) const rows = $(entrySelector) const packages = [].map.call(rows, (item) => $(item).text()) diff --git a/packages/survey/src/index.js b/packages/survey/src/index.js index 572be1413a..5fd3df6e7c 100644 --- a/packages/survey/src/index.js +++ b/packages/survey/src/index.js @@ -46,14 +46,18 @@ async function start () { // const packages = ['relay-compiler'] const allConfigs = { resources: {} } await Promise.all(packages.map(async (packageName) => { - if (parseBlacklist.includes(packageName)) return + if (parseBlacklist.includes(packageName)) { + return + } const config = await concurrencyLimit(() => loadPolicy(packageName)) if (!config || !config.resources) { console.warn(`config for "${packageName}" is broken`) return } // skip if empty - if (!config.resources[packageName]) return + if (!config.resources[packageName]) { + return + } allConfigs.resources[packageName] = config.resources[packageName] })) await writeConfig('_all', allConfigs) @@ -120,7 +124,7 @@ async function writeConfig (packageName, config) { } function getPolicyPath (packageName) { - const policyDir = path.resolve(__dirname, `../results/`) + const policyDir = path.resolve(__dirname, '../results/') const policyPath = `${policyDir}/${packageName}.json` return policyPath -} \ No newline at end of file +} diff --git a/packages/survey/src/load.js b/packages/survey/src/load.js index 73b7eb92d0..7fa87ec135 100644 --- a/packages/survey/src/load.js +++ b/packages/survey/src/load.js @@ -5,7 +5,7 @@ const { downloadPackage } = require('./downloadPackage.js') const { fileExists } = require('./util.js') module.exports = { - loadPackage + loadPackage, } diff --git a/packages/survey/src/parseForPolicy.js b/packages/survey/src/parseForPolicy.js index 93b3cd698c..22ab055588 100644 --- a/packages/survey/src/parseForPolicy.js +++ b/packages/survey/src/parseForPolicy.js @@ -32,14 +32,18 @@ async function parseForPolicy ({ packageDir, entryId, rootPackageName }) { // we also want to gracefully handle resolution failures const shouldResolve = (requestedName, parentSpecifier) => { const looksLikePackage = !(requestedName.startsWith('.') || requestedName.startsWith('/')) - if (looksLikePackage) return false + if (looksLikePackage) { + return false + } // attempt to resolve let resolved try { resolved = resolveHook(requestedName, parentSpecifier) } catch (err) { // ignore modules that cant be resolved - if (err.code === 'MODULE_NOT_FOUND') return false + if (err.code === 'MODULE_NOT_FOUND') { + return false + } throw err } const extension = path.extname(resolved).slice(1) @@ -58,18 +62,22 @@ async function parseForPolicy ({ packageDir, entryId, rootPackageName }) { } // dont include empty config - if (Object.keys(environment).length === 0) return { resources: {} } + if (Object.keys(environment).length === 0) { + return { resources: {} } + } return { resources: { [rootPackageName]: { - environment - } - } + environment, + }, + }, } function visitorFn (moduleRecord) { - if (!moduleRecord.ast) return + if (!moduleRecord.ast) { + return + } const { primordialMutations, strictModeViolations, dynamicRequires } = inspectSesCompat(moduleRecord.ast) const serializableResults = {} if (primordialMutations.length) { diff --git a/packages/survey/src/prepareHook.js b/packages/survey/src/prepareHook.js index 62826ce182..ef422817aa 100644 --- a/packages/survey/src/prepareHook.js +++ b/packages/survey/src/prepareHook.js @@ -4,14 +4,14 @@ // environment PATH. // this has been borrowed and modified from https://github.com/agoric/ses-shim -const fs = require('fs'); -const path = require('path'); +const fs = require('fs') +const path = require('path') -const node = process.env.NVM_BIN ? `${process.env.NVM_BIN}/node` : process.argv[0]; +const node = process.env.NVM_BIN ? `${process.env.NVM_BIN}/node` : process.argv[0] const npxPath = path.resolve(node, '../npx') const lavamoat = require.resolve('lavamoat/src/index.js') -const lockdown = new URL('../src/lockdown.cjs', `file://${__filename}`).pathname; -const mitm = new URL('../mitm/node', `file://${__filename}`).pathname; +const lockdown = new URL('../src/lockdown.cjs', `file://${__filename}`).pathname +const mitm = new URL('../mitm/node', `file://${__filename}`).pathname const script = `#!/bin/sh set -xueo pipefail @@ -29,7 +29,7 @@ else echo "unknown, running with lavamoat" ${node} ${lavamoat} --writeAutoConfigAndRun "$@" fi -`; +` /* /home/xyz/.nvm/versions/node/v12.16.1/bin/node \ @@ -38,5 +38,5 @@ fi /home/xyz/.yarn/bin/yarn.js 'run test' */ -fs.writeFileSync(mitm, script, 'utf-8'); -fs.chmodSync(mitm, 0o755); +fs.writeFileSync(mitm, script, 'utf-8') +fs.chmodSync(mitm, 0o755) diff --git a/packages/survey/src/util.js b/packages/survey/src/util.js index d419b50f7b..3737ca4aa1 100644 --- a/packages/survey/src/util.js +++ b/packages/survey/src/util.js @@ -7,7 +7,9 @@ async function fileExists (path) { await fs.access(path) return true } catch (err) { - if (err.code === 'ENOENT') return false + if (err.code === 'ENOENT') { + return false + } throw err } -} \ No newline at end of file +} diff --git a/packages/tofu/test/findGlobals.spec.js b/packages/tofu/test/findGlobals.spec.js index 8903b53ded..97e074cb06 100644 --- a/packages/tofu/test/findGlobals.spec.js +++ b/packages/tofu/test/findGlobals.spec.js @@ -84,7 +84,7 @@ test('destructuring.js - ES2015 variable destructuring', (t) => { test('detect.js - check locals and globals', (t) => { t.deepEqual( detect(read('detect.js')), - ['w', 'foo', 'process', 'console', 'AAA', 'BBB', 'CCC', 'xyz', 'ZZZ', 'BLARG', 'RAWR'].sort() + ['w', 'foo', 'process', 'console', 'AAA', 'BBB', 'CCC', 'xyz', 'ZZZ', 'BLARG', 'RAWR'].sort(), ) }) // test('detect.js - check variable names', (t) => { @@ -164,4 +164,4 @@ test('try_catch.js - the exception in a try catch block is a local', (t) => { test('BigInt - sees global property primordials like BigInt', (t) => { t.deepEqual(detect('BigInt(123)'), ['BigInt']) -}) \ No newline at end of file +}) diff --git a/packages/tofu/test/inspectEsmImports.spec.js b/packages/tofu/test/inspectEsmImports.spec.js index 0254248305..88a3ca9b65 100644 --- a/packages/tofu/test/inspectEsmImports.spec.js +++ b/packages/tofu/test/inspectEsmImports.spec.js @@ -5,7 +5,7 @@ const { parse, inspectEsmImports } = require('../src/index') testInspect('esm - basic', {}, ` import fs from 'fs' `, { - esmImports: ['fs'] + esmImports: ['fs'], }) // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import @@ -35,8 +35,8 @@ testInspect('esm - full set', {}, ` 'package07.export8', 'package08', 'package09', - 'package09' - ] + 'package09', + ], }) function testInspect (label, opts, fn, expectedResultObj) { @@ -56,13 +56,15 @@ function testInspect (label, opts, fn, expectedResultObj) { } t.deepEqual(resultSorted, expectedSorted) - }) + }) } function sortBy (key) { return (a, b) => { const vA = a[key]; const vB = b[key] - if (vA === vB) return 0 + if (vA === vB) { + return 0 + } return vA > vB ? 1 : -1 } } diff --git a/packages/tofu/test/inspectGlobals.spec.js b/packages/tofu/test/inspectGlobals.spec.js index c21301a6dc..72385d5b7f 100644 --- a/packages/tofu/test/inspectGlobals.spec.js +++ b/packages/tofu/test/inspectGlobals.spec.js @@ -8,14 +8,17 @@ test('fnToCodeBlock utility works', (t) => { }) t.is(src, '(() => {\n 1 + 2 + 3\n })()') - }) +}) testInspect('detects global reads', {}, () => { const x = xyz - (function (a) { return a })(abc) + // eslint-disable-next-line no-unexpected-multiline + (function (a) { + return a + })(abc) }, { xyz: 'read', - abc: 'read' + abc: 'read', }) testInspect('doesnt detect "this"', {}, () => { @@ -27,105 +30,107 @@ testInspect('doesnt detect properties on "this"', {}, () => { }, {}) testInspect('detects reads on globalRefs', { - globalRefs: ['zzz'] + globalRefs: ['zzz'], }, () => { const x = zzz.abc }, { - abc: 'read' + abc: 'read', }) testInspect('detects reads on multiple globalRefs', { - globalRefs: ['a', 'b', 'c'] + globalRefs: ['a', 'b', 'c'], }, () => { const x = a.x + b.y * c.z }, { x: 'read', y: 'read', - z: 'read' + z: 'read', }) testInspect('detects implicit global writes', {}, () => { xyz = true }, { - xyz: 'write' + xyz: 'write', }) testInspect('detects implicit global writes with mixed usage', {}, () => { z = xyz - xyz = (function (a) { return a })(abc) + xyz = (function (a) { + return a + })(abc) }, { xyz: 'write', abc: 'read', - z: 'write' + z: 'write', }) testInspect('detects assignment to property on globalRefs', { - globalRefs: ['zzz'] + globalRefs: ['zzz'], }, () => { zzz.abc = true }, { - abc: 'write' + abc: 'write', }) testInspect('never suggest access to full globalRef', { - globalRefs: ['zzz'] + globalRefs: ['zzz'], }, () => { const x = zzz }, {}) testInspect('detects combined globalRef assignment and reads', { - globalRefs: ['zzz'] + globalRefs: ['zzz'], }, () => { zzz.abc = xyz.abc }, { abc: 'write', - 'xyz.abc': 'read' + 'xyz.abc': 'read', }) testInspect('not picking up assignments to non-global matching globalRef name', { - globalRefs: ['xyz'] + globalRefs: ['xyz'], }, () => { const xyz = {} xyz.abc }, {}) testInspect('elevating computed property lookups to globalRef 1', { - globalRefs: ['abc'] + globalRefs: ['abc'], }, () => { const key = 'hello' abc.xyz[key] }, { - xyz: 'read' + xyz: 'read', }) testInspect('elevating computed property lookups to globalRef 2', { - globalRefs: ['abc'] + globalRefs: ['abc'], }, () => { const key = 'hello' abc.xyz.ijk[key] }, { - 'xyz.ijk': 'read' + 'xyz.ijk': 'read', }) testInspect('picking up mixed explicit and computed property lookups', { - globalRefs: ['window'] + globalRefs: ['window'], }, () => { const key = 'hello' window.location[key] window.location.href }, { - location: 'read' + location: 'read', }) testInspect('not picking up js language features', { - globalRefs: ['window'] + globalRefs: ['window'], }, () => { Object window.Object }, {}) testInspect('ignore globalRef without property lookup', { - globalRefs: ['window'] + globalRefs: ['window'], }, () => { typeof window === undefined }, {}) @@ -137,26 +142,26 @@ testInspect('get granular platform api', {}, () => { }, { 'document.createElement': 'read', 'location.href': 'read', - 'navigator.userAgent': 'read' + 'navigator.userAgent': 'read', }) testInspect('get granular platform api when nested under global', { - globalRefs: ['window'] + globalRefs: ['window'], }, () => { window.location.href }, { - 'location.href': 'read' + 'location.href': 'read', }) testInspect('take platform api, up to computed', { - globalRefs: ['window'] + globalRefs: ['window'], }, () => { const key = 'hello' document.body.children[key] window.location.href[key] }, { 'document.body.children': 'read', - 'location.href': 'read' + 'location.href': 'read', }) testInspect('raise globals to highest used', {}, () => { @@ -166,94 +171,94 @@ testInspect('raise globals to highest used', {}, () => { document.body.children.indexOf }, { location: 'read', - 'document.body.children': 'read' + 'document.body.children': 'read', }) testInspect('correctly finds deep "process.env" reference', {}, () => { process.env.READABLE_STREAM === 'disable' }, { - 'process.env.READABLE_STREAM': 'read' + 'process.env.READABLE_STREAM': 'read', }) testInspect('read access to object implies write access to properties', {}, () => { const x = location location.href = 'website' }, { - location: 'read' + location: 'read', }) testInspect('object destructuring', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { const { abc } = globalThis const xyz = globalThis.xyz }, { abc: 'read', - xyz: 'read' + xyz: 'read', }) testInspect('object destructuring with branching', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { const { y: { z }, w } = globalThis.x }, { 'x.y.z': 'read', - 'x.w': 'read' + 'x.w': 'read', }) testInspect('array destructuring', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { const [one, two, three] = globalThis.snakes }, { 'snakes.0': 'read', 'snakes.1': 'read', - 'snakes.2': 'read' + 'snakes.2': 'read', }) testInspect('complex mixed destructuring', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { const [ { name: primaryThingName }, { name: secondaryThingName, ...secondaryThingProps }, - { name: [...tertiaryThingName] } + { name: [...tertiaryThingName] }, ] = globalThis.things }, { 'things.0.name': 'read', 'things.1': 'read', - 'things.2.name': 'read' + 'things.2.name': 'read', }) testInspect('paths stop at computed props', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { const key = Math.random() const { b, c } = globalThis[key].a const { [key]: y, z } = globalThis.x }, { - x: 'read' + x: 'read', }) testInspect('new intrinsics like BigInt are ignored', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { BigInt(123) }, {}) testInspect('object destructuring 2', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { - const { source: { location: { npm: { filePath, iconPath }, }, }, } = manifest + const { source: { location: { npm: { filePath, iconPath } } } } = manifest }, { 'manifest.source.location.npm.filePath': 'read', 'manifest.source.location.npm.iconPath': 'read', }) testInspect('optional chaining', { - globalRefs: ['globalThis'] + globalRefs: ['globalThis'], }, () => { - manifest.source?.location?.npm?.filePath; + manifest.source?.location?.npm?.filePath }, { 'manifest.source.location.npm.filePath': 'read', }) @@ -273,13 +278,15 @@ function testInspect (label, opts, fn, expectedResultObj) { } t.deepEqual(resultSorted, expectedSorted) - }) + }) } function sortBy (key) { return (a, b) => { const vA = a[key]; const vB = b[key] - if (vA === vB) return 0 + if (vA === vB) { + return 0 + } return vA > vB ? 1 : -1 } } diff --git a/packages/tofu/test/inspectImports.spec.js b/packages/tofu/test/inspectImports.spec.js index 7a4a9657c5..974d3e7fe1 100644 --- a/packages/tofu/test/inspectImports.spec.js +++ b/packages/tofu/test/inspectImports.spec.js @@ -6,26 +6,26 @@ testInspect('cjs - basic', {}, () => { const fs = require('fs') module.exports = fs }, { - cjsImports: ['fs'] + cjsImports: ['fs'], }) testInspect('cjs - shadowed require', {}, () => { const require = () => {} require('fs') }, { - cjsImports: [] + cjsImports: [], }) testInspect('cjs - include even if require result not stored in variable', {}, () => { require('fs').readFileSync }, { - cjsImports: ['fs.readFileSync'] + cjsImports: ['fs.readFileSync'], }) testInspect('cjs - include even if declared var is unused', {}, () => { const rfs = require('fs').readFileSync }, { - cjsImports: ['fs.readFileSync'] + cjsImports: ['fs.readFileSync'], }) // testInspect('cjs - require rename', {}, () => { @@ -42,22 +42,22 @@ testInspect('cjs - basic destructure', {}, () => { }, { cjsImports: [ 'fs.readFileSync', - 'fs.createReadStream' - ] + 'fs.createReadStream', + ], }) testInspect('cjs - basic member', {}, () => { const rfs = require('fs').readFileSync rfs() }, { - cjsImports: ['fs.readFileSync'] + cjsImports: ['fs.readFileSync'], }) testInspect('cjs - mixed destructuring and member', {}, () => { const { constructor: { name: [bigEff] } } = require('fs').readFileSync bigEff() }, { - cjsImports: ['fs.readFileSync.constructor.name.0'] + cjsImports: ['fs.readFileSync.constructor.name.0'], }) testInspect('cjs - usage basic', {}, () => { @@ -67,17 +67,18 @@ testInspect('cjs - usage basic', {}, () => { }, { cjsImports: [ 'fs.readFileSync', - 'fs.createReadStream' - ] + 'fs.createReadStream', + ], }) testInspect('cjs - usage advanced', {}, () => { + // eslint-disable-next-line n/prefer-global/process const { sourceUrl: url } = require('process').release url.includes('v12') }, { cjsImports: [ - 'process.release.sourceUrl.includes' - ] + 'process.release.sourceUrl.includes', + ], }) function testInspect (label, opts, fn, expectedResultObj) { @@ -97,13 +98,15 @@ function testInspect (label, opts, fn, expectedResultObj) { } t.deepEqual(resultSorted, expectedSorted) - }) + }) } function sortBy (key) { return (a, b) => { const vA = a[key]; const vB = b[key] - if (vA === vB) return 0 + if (vA === vB) { + return 0 + } return vA > vB ? 1 : -1 } } diff --git a/packages/tofu/test/inspectPrimordialAssignments.spec.js b/packages/tofu/test/inspectPrimordialAssignments.spec.js index c0c49175fc..8845e73ba1 100644 --- a/packages/tofu/test/inspectPrimordialAssignments.spec.js +++ b/packages/tofu/test/inspectPrimordialAssignments.spec.js @@ -10,56 +10,56 @@ test('inspectPrimordialAssignments - basic', (t) => { 'hello world' `) t.deepEqual(results, []) - }) +}) test('inspectPrimordialAssignments - assignment to toString on prototype', (t) => { const results = inspectPrimordialAssignmentsTest(` MyClass.prototype.toString = () => 'hello' `) t.deepEqual(results, []) - }) +}) test('inspectPrimordialAssignments - assignment to toString', (t) => { const results = inspectPrimordialAssignmentsTest(` exports.toString = () => 'hello' `) t.deepEqual(results, []) - }) +}) test('inspectPrimordialAssignments - assignment to frozen primordial', (t) => { const results = inspectPrimordialAssignmentsTest(` Array.prototype.bogoSort = () => 'hello' `) t.is(results.length, 1) - }) +}) test('inspectPrimordialAssignments - primordial potential false positive - instrinsic', (t) => { const results = inspectPrimordialAssignmentsTest(` window.Array === Array `) t.deepEqual(results, []) - }) +}) test('inspectPrimordialAssignments - primordial potential false positive - keyword', (t) => { const results = inspectPrimordialAssignmentsTest(` const args = Array.prototype.slice.call(arguments) `) t.deepEqual(results, []) - }) +}) test('inspectPrimordialAssignments - primordial modify property', (t) => { const results = inspectPrimordialAssignmentsTest(` Object.keys.extra = 'hello' `) t.is(results.length, 1) - }) +}) test('inspectPrimordialAssignments - primordial Error modify property', (t) => { const results = inspectPrimordialAssignmentsTest(` Error.prepareStackTrace = () => {} `) t.is(results.length, 1) - }) +}) test('inspectPrimordialAssignments - ensure shadowed references not counted - simple', (t) => { const results = inspectPrimordialAssignmentsTest(` @@ -67,7 +67,7 @@ test('inspectPrimordialAssignments - ensure shadowed references not counted - si Promise.all = () => {} `) t.is(results.length, 0) - }) +}) test('inspectPrimordialAssignments - ensure shadowed references not counted - complex', (t) => { const results = inspectPrimordialAssignmentsTest(` @@ -81,4 +81,4 @@ test('inspectPrimordialAssignments - ensure shadowed references not counted - co })() `) t.is(results.length, 1) - }) +}) diff --git a/packages/tofu/test/inspectSesCompat.spec.js b/packages/tofu/test/inspectSesCompat.spec.js index 1d7f88f7e0..7bb3ec325b 100644 --- a/packages/tofu/test/inspectSesCompat.spec.js +++ b/packages/tofu/test/inspectSesCompat.spec.js @@ -6,7 +6,7 @@ const { parse, inspectSesCompat } = require('../src/index') function inspectSesCompatTest (code) { const ast = parse(code, { sourceType: 'module', - errorRecovery: true + errorRecovery: true, }) return inspectSesCompat(ast) } @@ -16,49 +16,49 @@ test('inspectSesCompat - allowed primordial assignment', (t) => { Error.stackTraceLimit = 42 `) t.deepEqual(results.primordialMutations, []) - }) +}) test('inspectSesCompat - disallowed primordial assignment', (t) => { const results = inspectSesCompatTest(` Error.xyz = 42 `) t.is(results.primordialMutations.length, 1) - }) +}) test('inspectSesCompat - strict mode - reserved word', (t) => { const results = inspectSesCompatTest(` const package = 'lavamoat' `) t.is(results.strictModeViolations.length, 1) - }) +}) test('inspectSesCompat - strict mode - deleting a variable', (t) => { const results = inspectSesCompatTest(` delete xyz `) t.is(results.strictModeViolations.length, 1) - }) +}) test('inspectSesCompat - strict mode - octal literals', (t) => { const results = inspectSesCompatTest(` let x = 010 `) t.is(results.strictModeViolations.length, 1) - }) +}) test('inspectSesCompat - strict mode - escaped octal literals', (t) => { const results = inspectSesCompatTest(` let x = \\010 `) t.is(results.strictModeViolations.length, 1) - }) +}) test('inspectSesCompat - strict mode - "with" keyword', (t) => { const results = inspectSesCompatTest(` with (Math) { x = cos(2) } `) t.is(results.strictModeViolations.length, 1) - }) +}) // test('inspectSesCompat - assignment to undeclared globals', (t) => { // const results = inspectSesCompatTest(` diff --git a/packages/tofu/test/util.spec.js b/packages/tofu/test/util.spec.js index 1d51f4c2e7..4f8b06d6b6 100644 --- a/packages/tofu/test/util.spec.js +++ b/packages/tofu/test/util.spec.js @@ -1,51 +1,51 @@ const test = require('ava') -const { utils: { mergePolicy, mergeConfigEntire, objToMap, mapToObj } } = require('../src/index') +const { utils: { mergePolicy, objToMap, mapToObj } } = require('../src/index') const testMergePartial = test.macro( (t, configA, configB, expectedResultObj) => { const result = mergePolicy(objToMap(configA), objToMap(configB)) const resultObj = mapToObj(result) t.deepEqual(resultObj, expectedResultObj) - } + }, ) test('upgrades reads to writes', testMergePartial, { abc: 'write', - xyz: 'read' + xyz: 'read', }, { abc: 'read', - xyz: 'write' + xyz: 'write', }, { abc: 'write', - xyz: 'write' + xyz: 'write', }) test('adds new packages', testMergePartial, { abc: 'write', - xyz: 'read' + xyz: 'read', }, { def: 'read', - ghi: 'write' + ghi: 'write', }, { abc: 'write', xyz: 'read', def: 'read', - ghi: 'write' + ghi: 'write', }) test('dedupe overlapping', testMergePartial, { - 'abc.xyz': 'read' + 'abc.xyz': 'read', }, { - abc: 'read' + abc: 'read', }, { - abc: 'read' + abc: 'read', }) test('non-overlapping', testMergePartial, { - abc: 'read' + abc: 'read', }, { - 'xyz.jkl': 'write' + 'xyz.jkl': 'write', }, { abc: 'read', - 'xyz.jkl': 'write' + 'xyz.jkl': 'write', }) diff --git a/packages/viz/bin/index.js b/packages/viz/bin/index.js index dc1f121889..565ddcbdbd 100755 --- a/packages/viz/bin/index.js +++ b/packages/viz/bin/index.js @@ -192,4 +192,4 @@ async function getDirectories (filepath) { return dirEntries .filter(entry => entry.isDirectory()) .map(dir => dir.name) -} \ No newline at end of file +} diff --git a/packages/viz/src/graphs/DepGraph.js b/packages/viz/src/graphs/DepGraph.js index ada64582d3..0246160f9a 100644 --- a/packages/viz/src/graphs/DepGraph.js +++ b/packages/viz/src/graphs/DepGraph.js @@ -392,7 +392,7 @@ class DepGraph extends React.Component { } renderSelectedNodeCode (selectedModule) { - // eslint-disable-next-line node/global-require + // eslint-disable-next-line n/global-require require('codemirror/mode/javascript/javascript') const { policyData } = this.props const { debug: { debugInfo } } = policyData