![Malicious npm Package Typosquats react-login-page to Deploy Keylogger](https://cdn.sanity.io/images/cgdhsj6q/production/007b21d9cf9e03ae0bb3f577d1bd59b9d715645a-1024x1024.webp?w=400&fit=max&auto=format)
Research
Security News
Malicious npm Package Typosquats react-login-page to Deploy Keylogger
Socket researchers unpack a typosquatting package with malicious code that logs keystrokes and exfiltrates sensitive data to a remote server.
@humanwhocodes/config-array
Advanced tools
Package description
The @humanwhocodes/config-array package is designed to manage and process arrays of configuration objects. It allows for the easy manipulation and conditional application of configurations based on specific criteria. This package is particularly useful for tools that need to load and use multiple configurations, possibly with overrides or environment-specific settings.
Loading and processing configuration arrays
This feature allows for loading configurations from multiple sources, including JavaScript and JSON files. The configurations are processed and can be accessed programmatically.
const { ConfigArray } = require('@humanwhocodes/config-array');
const config = new ConfigArray({
files: ['./config1.js', './config2.json'],
baseDirectory: process.cwd()
});
config.load().then(() => {
console.log('Configurations loaded');
});
Conditional configuration
This demonstrates how to add conditional configurations based on criteria such as the environment. It allows for dynamic selection of configurations at runtime.
const { ConfigArray } = require('@humanwhocodes/config-array');
const config = new ConfigArray();
config.add({
name: 'development',
criteria: { env: 'development' },
options: { debug: true }
});
config.add({
name: 'production',
criteria: { env: 'production' },
options: { debug: false, optimize: true }
});
const envConfig = config.find({ env: process.env.NODE_ENV });
console.log(envConfig.options);
Cosmiconfig is a package that searches for and loads configuration for your program. It supports various file formats and locations, making it flexible for different use cases. Compared to @humanwhocodes/config-array, cosmiconfig focuses more on the discovery and loading of configuration files rather than processing an array of configurations.
The 'config' package is used for organizing hierarchical configurations for your app deployments. It lets you define a set of default parameters and extend them for different deployment environments (development, qa, staging, production, etc.). While it provides a robust solution for managing configurations across environments, it does not offer the same level of granularity or conditional logic for individual configuration objects as @humanwhocodes/config-array.
Readme
If you find this useful, please consider supporting my work with a donation.
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
In 2019, I submitted an ESLint RFC proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born.
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in files
and ignores
properties on each config object. Here's an example:
export default [
// match all JSON files
{
name: "JSON Handler",
files: ["**/*.json"],
handler: jsonHandler
},
// match only package.json
{
name: "package.json Handler",
files: ["package.json"],
handler: packageJsonHandler
}
];
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just package.json
in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for foo.json
, only the first config object matches so handler
is equal to jsonHandler
; when you retrieve a configuration for package.json
, handler
is equal to packageJsonHandler
(because both config objects match, the second one wins).
You can install the package using npm or Yarn:
npm install @humanwhocodes/config-array --save
# or
yarn add @humanwhocodes/config-array
First, import the ConfigArray
constructor:
import { ConfigArray } from "@humanwhocodes/config-array";
// or using CommonJS
const { ConfigArray } = require("@humanwhocodes/config-array");
When you create a new instance of ConfigArray
, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
const configFilename = path.resolve(process.cwd(), "my.config.js");
const { default: rawConfigs } = await import(configFilename);
const configs = new ConfigArray(rawConfigs, {
// the path to match filenames from
basePath: process.cwd(),
// additional items in each config
schema: mySchema
});
This example reads in an object or array from my.config.js
and passes it into the ConfigArray
constructor as the first argument. The second argument is an object specifying the basePath
(the directoy in which my.config.js
is found) and a schema
to define the additional properties of a config object beyond files
, ignores
, and name
.
The schema
option is required for you to use additional properties in config objects. The schema is object that follows the format of an ObjectSchema
. The schema specifies both validation and merge rules that the ConfigArray
instance needs to combine configs when there are multiple matches. Here's an example:
const configFilename = path.resolve(process.cwd(), "my.config.js");
const { default: rawConfigs } = await import(configFilename);
const mySchema = {
// define the handler key in configs
handler: {
required: true,
merge(a, b) {
if (!b) return a;
if (!a) return b;
},
validate(value) {
if (typeof value !== "function") {
throw new TypeError("Function expected.");
}
}
}
};
const configs = new ConfigArray(rawConfigs, {
// the path to match filenames from
basePath: process.cwd(),
// additional items in each config
schema: mySchema
});
Config arrays can be multidimensional, so it's possible for a config array to contain another config array, such as:
export default [
// JS config
{
files: ["**/*.js"],
handler: jsHandler
},
// JSON configs
[
// match all JSON files
{
name: "JSON Handler",
files: ["**/*.json"],
handler: jsonHandler
},
// match only package.json
{
name: "package.json Handler",
files: ["package.json"],
handler: packageJsonHandler
}
],
// filename must match all patterns in subarray
{
files: [ ["*.test.*", "*.js"] ],
handler: jsTestHandler
}
];
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
If the files
array contains an item that is an array of strings, then all patterns must match in order for the config to match. In the preceding examples, both *.test.*
and *.js
must match in order for the config object to be used.
Config arrays can also include config functions. A config function accepts a single parameter, context
(defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
export default [
// JS config
{
files: ["**/*.js"],
handler: jsHandler
},
// JSON configs
function (context) {
return [
// match all JSON files
{
name: context.name + " JSON Handler",
files: ["**/*.json"],
handler: jsonHandler
},
// match only package.json
{
name: context.name + " package.json Handler",
files: ["package.json"],
handler: packageJsonHandler
}
];
}
];
When a config array is normalized, each function is executed and replaced in the config array with the return value.
Note: Config functions cannot be async. This will be added in a future version.
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
To normalize a config array, call the normalize()
method and pass in a context object:
await configs.normalize({
name: "MyApp"
});
The normalize()
method returns a promise, so be sure to use the await
operator. The config array instance is normalized in-place, so you don't need to create a new variable.
Important: Once a ConfigArray
is normalized, it cannot be changed further. You can, however, create a new ConfigArray
and pass in the normalized instance to create an unnormalized copy.
To get the config for a file, use the getConfig()
method on a normalized config array and pass in the filename to get a config for:
// pass in absolute filename
const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json"));
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
A few things to keep in mind:
files
, ignores
, or name
properties; the only properties on the object will be the other configuration options specified.getConfig()
with the same filename will return in a fast lookup rather than another calculation.The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
Apache 2.0
FAQs
Unknown package
The npm package @humanwhocodes/config-array receives a total of 24,373,290 weekly downloads. As such, @humanwhocodes/config-array popularity was classified as popular.
We found that @humanwhocodes/config-array demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers unpack a typosquatting package with malicious code that logs keystrokes and exfiltrates sensitive data to a remote server.
Security News
The JavaScript community has launched the e18e initiative to improve ecosystem performance by cleaning up dependency trees, speeding up critical parts of the ecosystem, and documenting lighter alternatives to established tools.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.