diff --git a/HISTORY.md b/HISTORY.md index 3f65ada3..a2aded28 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file. ## unreleased +* Changed + * Hardened JSON imports (via [#1132]) + ## 3.8.3 - 2023-12-01 * Build diff --git a/src/_helpers.ts b/src/_helpers.ts index bb10cc73..82462721 100644 --- a/src/_helpers.ts +++ b/src/_helpers.ts @@ -17,7 +17,7 @@ SPDX-License-Identifier: Apache-2.0 Copyright (c) OWASP Foundation. All Rights Reserved. */ -import { existsSync } from 'fs' +import { existsSync, readFileSync } from 'fs' import { dirname, isAbsolute, join } from 'path' export interface PackageDescription { @@ -32,7 +32,7 @@ export function getPackageDescription (path: string): PackageDescription | undef try { return { path: packageJson, - packageJson: require(packageJson) + packageJson: loadJsonFile(packageJson) } } catch { return undefined @@ -47,3 +47,10 @@ export function getPackageDescription (path: string): PackageDescription | undef } return undefined } + +export function loadJsonFile (path: string): any { + return JSON.parse(readFileSync(path, 'utf8')) + // may be replaced by `require(f, { with: { type: "json" } })` + // as soon as this spec is properly implemented. + // see https://github.com/tc39/proposal-import-attributes +} diff --git a/src/plugin.ts b/src/plugin.ts index ad60b146..7febdc5f 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -23,7 +23,7 @@ import * as normalizePackageJson from 'normalize-package-data' import { join as joinPath, resolve } from 'path' import { Compilation, type Compiler, sources } from 'webpack' -import { getPackageDescription } from './_helpers' +import { getPackageDescription, loadJsonFile } from './_helpers' import { Extractor } from './extractor' type WebpackLogger = Compilation['logger'] @@ -334,7 +334,7 @@ export class CycloneDxWebpackPlugin { * #makeTools (builder: CDX.Builders.FromNodePackageJson.ToolBuilder, logger: WebpackLogger): Generator { /* eslint-disable-next-line @typescript-eslint/no-var-requires */ - const packageJsonPaths = ['../package.json'] + const packageJsonPaths = [resolve(module.path, '..', 'package.json')] const libs = [ '@cyclonedx/cyclonedx-library' @@ -355,8 +355,7 @@ export class CycloneDxWebpackPlugin { for (const packageJsonPath of packageJsonPaths) { logger.log('try to build new Tool from PkgPath', packageJsonPath) - /* eslint-disable-next-line @typescript-eslint/no-var-requires */ - const packageJson = require(packageJsonPath) + const packageJson = loadJsonFile(packageJsonPath) normalizePackageJson(packageJson, w => { logger.debug('normalizePackageJson from PkgPath', packageJsonPath, 'caused:', w) }) const tool = builder.makeTool(packageJson) if (tool !== undefined) {