Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Customizable JavaScript data validator.
I woke up on my 26th birthday at 5 am from the blows of russian missiles. They attacked the city of Kyiv, where I live, as well as the cities in which my family and friends live. Now my country is a war zone.
We fight for democratic values, freedom, for our future! Once again Ukrainians have to stand against evil, terror, against genocide. The outcome of this war will determine what path human history is taking from now on.
💛💙 Help Ukraine! We need your support! There are dozen ways to help us, just do it!
Coming soon:
There are several nice validators in the JS world (livr, joi), but no one satisfied all my needs entirely.
Another big question here is why not just use regular expressions? Regexp is an undoubtedly powerful tool, but has its own cons. I am completely tired of searching for valid regexp for any standard validation task. Most of them need almost scientific paper to describe patterns. They are totally unpredictable when faced with arbitrary inputs, hard to maintain, debug and explain.
So, that is another JS validator, describing my view for the modern validation process.
To use library you need to have node and npm installed in your machine:
>=10
>=6
Package is continuously tested on darwin, linux, win32 platforms. All active and maintenance LTS node releases are supported.
To install the library run the following command
npm i --save cottus
Commonly usage is a two steps process:
import cottus from 'cottus';
const validator = cottus.compile([
'required', { 'attributes' : {
'id' : [ 'required', 'uuid' ],
'name' : [ 'string', { 'min': 3 }, { 'max': 256 } ],
'email' : [ 'required', 'email' ],
'contacts' : [ { 'every' : {
'attributes' : {
'type' : [
'required',
{ 'enum': [ 'phone', 'facebook' ] }
],
'value' : [ 'required', 'string' ]
}
} } ]
} }
]);
try {
const valid = validator.validate(rawUserData);
console.log('Data is valid:', valid);
} catch (error) {
console.error('Validation Failed:', error);
}
Check list of available rules at reference
CottusValidationError
would be returned in case of validation failure.
There are 2 ways of identifying this error:
import { ValidationError } from 'cottus';
if (error instanceof ValidationError) {
console.error(error.prettify);
}
isValidationError
property:try {
const valid = validator.validate(rawUserData);
console.log('Data is valid:', valid);
} catch (error) {
if (error.isValidationError) {
console.error('Validation Failed:', error);
}
console.error('Unknown error occured:', error);
}
To get a pretty hierarchical tree with error codes, use:
console.error(error.prettify);
To get full error data, use:
console.error(error.hash);
if you need to gather a flat list of values into the hierarchy and validate, use the Assembler module.
Typical use case - transforming environment variables into the config:
import { Assembler } from 'cottus';
const assembler = new Assembler(cottus, schema);
const e = process.env;
const schema = {
mongo : !!e.MONGO_CONNECTION_STRING ? {
url : { $source: '{MONGO_CONNECTION_STRING}', $validate: [ 'required', 'url' ] },
db : { $source: '{MONGO_DB_NAME}', $validate: [ 'required', 'string' ] }
} : null,
redis : {
port : { $source: '{REDIS_PORT}', $validate: [ 'required', 'port' ] },
host : { $source: '{REDIS_HOST}', $validate: [ 'required', 'hostname' ] },
db : { $source: '{REDIS_DB}', $validate: [ 'integer' ] },
password : { $source: '{REDIS_PASSWORD}', $validate: [ 'string' ] },
username : { $source: '{REDIS_USER}', $validate: [ 'string' ] }
},
'administrators' : {
$source : { type: 'complex_array', prefix: 'ADMIN_' },
$validate : {
'login' : { $source: '{_LOGIN}', $validate: [ 'required', 'email' ] },
'password' : { $source: '{_PASSWORD}', $validate: [ 'string' ] },
permissions : {
$source : { type: 'simple_array', prefix: '_PERMISSIONS_' },
$validate : { 'enum': [ 'read', 'write' ] }
}
}
}
};
assembler.parse();
const config = assembler.run(process.env);
schema
should be a hierarchical object. The deepest properties can be one of the following keywords:
$source
: can be a placeholder '{REDIS_PORT}'
or an object: { type: 'complex_array', prefix: 'USER_' }
. Next types allowed:
complex_array
: array of objectssimple_array
: array of primitivesconstant
: a value$validate
: cottus schema.To check more examples, see implementation section.
cottus can be extended with new rules.
import cottus, { BaseRule } from 'cottus';
class Split extends BaseRule {
static schema = 'split';
validate(input) {
const symbol = this.params;
return input.split(symbol);
}
}
cottus.addRules([
Split
]);
now rule split
can be used in cottus schema:
const validator = cottus.compile([
'required',
{ 'split': ' ' },
{ every: 'email' }
]);
const admins = validator.validate('sig@viwjirgo.bn neho@sorcopaz.ml ta@inepad.ax');
console.log(admins);
// ['sig@viwjirgo.bn', 'neho@sorcopaz.ml', 'ta@inepad.ax']
to throw validation error from the custom rule, use predefined errors:
import { errors } from 'cottus';
const { NOT_ALLOWED_VALUE } = errors;
if (!valid) throw new NOT_ALLOWED_VALUE();
or create own error:
import { BaseError } from 'cottus';
class UnsafeNumberError extends BaseError {
message = 'The number is not within the safe range of JavaScript numbers';
code = 'UNSAFE_NUMBER';
}
Are you looking for more examples?
Validation
Custom rules
Assembler
Make the changes to the code and tests. Then commit to your branch. Be sure to follow the commit message conventions. Read Contributing Guidelines for details.
FAQs
customizable JavaScript data validator
We found that cottus demonstrated a not healthy version release cadence and project activity because the last version was released 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.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.