All Projects → ExodusMovement → Schemasafe

ExodusMovement / Schemasafe

Licence: mit
A reasonably safe JSON Schema validator with draft-04/06/07/2019-09 support.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Schemasafe

openui5-validator
A library to validate OpenUI5 fields
Stars: ✭ 17 (-74.63%)
Mutual labels:  validation, json-schema, validator
Json Schema Spec
The JSON Schema I-D sources
Stars: ✭ 2,441 (+3543.28%)
Mutual labels:  json-schema, json, validation
Swagger Parser
Swagger 2.0 and OpenAPI 3.0 parser/validator
Stars: ✭ 710 (+959.7%)
Mutual labels:  json-schema, validation, validator
Validr
A simple, fast, extensible python library for data validation.
Stars: ✭ 205 (+205.97%)
Mutual labels:  json-schema, validation, validator
Maat
Validation and transformation library powered by deductive ascending parser. Made to be extended for any kind of project.
Stars: ✭ 27 (-59.7%)
Mutual labels:  validation, json-schema, validator
Swagger Cli
Swagger 2.0 and OpenAPI 3.0 command-line tool
Stars: ✭ 321 (+379.1%)
Mutual labels:  json-schema, validation, validator
Cti Stix Validator
OASIS TC Open Repository: Validator for STIX 2.0 JSON normative requirements and best practices
Stars: ✭ 24 (-64.18%)
Mutual labels:  json, validation, validator
Govalidator
Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.
Stars: ✭ 969 (+1346.27%)
Mutual labels:  validation, validator
Brutusin Rpc
Self-describing JSON-RPC web services over HTTP, with automatic API description based on JSON-Schema
Stars: ✭ 36 (-46.27%)
Mutual labels:  json-schema, json
Val
golang JSON validation library.
Stars: ✭ 37 (-44.78%)
Mutual labels:  json, validation
Oakdex Pokedex
Ruby Gem and Node Package for comprehensive Generation 1-7 Pokedex data, including 809 Pokémon, uses JSON schemas to verify the data
Stars: ✭ 44 (-34.33%)
Mutual labels:  json-schema, json
Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+58986.57%)
Mutual labels:  json-schema, json
Spectral
A flexible JSON/YAML linter for creating automated style guides, with baked in support for OpenAPI v2 & v3.
Stars: ✭ 876 (+1207.46%)
Mutual labels:  json-schema, json
Inspector
A tiny class validation library.
Stars: ✭ 64 (-4.48%)
Mutual labels:  validation, validator
Ismailfine
A simple (but correct) library for validating email addresses. Supports mail addresses as defined in rfc5322 as well as the new Internationalized Mail Address standards (rfc653x). Based on https://github.com/jstedfast/EmailValidation
Stars: ✭ 9 (-86.57%)
Mutual labels:  validation, validator
Uvicorn Gunicorn Fastapi Docker
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.
Stars: ✭ 1,014 (+1413.43%)
Mutual labels:  json-schema, json
Grpc Dotnet Validator
Simple request message validator for grpc.aspnet
Stars: ✭ 25 (-62.69%)
Mutual labels:  validation, validator
Partial.lenses.validation
Partial Lenses Validation is a JavaScript library for validating and transforming data
Stars: ✭ 39 (-41.79%)
Mutual labels:  json, validation
Fast Xml Parser
Validate XML, Parse XML to JS/JSON and vise versa, or parse XML to Nimn rapidly without C/C++ based libraries and no callback
Stars: ✭ 1,021 (+1423.88%)
Mutual labels:  json, validator
Jsonschema Key Compression
Compress json-data based on its json-schema while still having valid json
Stars: ✭ 59 (-11.94%)
Mutual labels:  json-schema, json

@exodus/schemasafe

A code-generating JSON Schema validator that attempts to be reasonably secure.

Supports draft-04/06/07/2019-09 and the discriminator OpenAPI keyword.

Node CI Status npm codecov Total alerts

Features

  • Converts schemas to self-contained JavaScript files, can be used in the build process.
    Integrates nicely with bundlers, so one won't need to generate code in runtime, and that works with CSP.
  • Optional requireValidation: true mode enforces full validation of the input object.
    Using mode: "strong" is recommended, — it combines that option with additional schema safety checks.
  • Does not fail open on unknown or unprocessed keywords — instead throws at build time if schema was not fully understood. That is implemented by tracking processed keywords and ensuring that none remain uncovered.
  • Does not fail open on schema problems — instead throws at build time.
    E.g. it will detect mistakes like {type: "array", "maxLength": 2}.
  • Under 1700 lines of code, non-minified.
  • Uses secure code generation approach to prevent data from schema from leaking into the generated code without being JSON-wrapped.
  • 0 dependencies
  • Very fast
  • Supports JSON Schema draft-04/06/07/2019-09 and a strict subset of the discriminator OpenAPI keyword.
  • Can assign defaults and/or remove additional properties when schema allows to do that safely. Throws at build time if those options are used with schemas that don't allow to do that safely.

Installation

npm install --save @exodus/schemasafe

Usage

Simply pass a schema to compile it:

const { validator } = require('@exodus/schemasafe')

const validate = validator({
  type: 'object',
  required: ['hello'],
  properties: {
    hello: {
      type: 'string'
    }
  }
})

console.log('should be valid', validate({ hello: 'world' }))
console.log('should not be valid', validate({}))

Or use the parser API (running in strong mode by default):

const { parser } = require('.')

const parse = parser({
  $schema: 'https://json-schema.org/draft/2019-09/schema',
  type: 'object',
  required: ['hello'],
  properties: {
    hello: {
      pattern: '^[a-z]+$',
      type: 'string'
    }
  },
  additionalProperties: false
})

console.log(parse('{"hello": "world" }')) // { valid: true, value: { hello: 'world' } }
console.log(parse('{}')) // { valid: false }

Parser API is recommended, because this way you can avoid handling unvalidated JSON objects in non-string form at all in your code.

Options

See options documentation for the full list of supported options.

Custom formats

@exodus/schemasafe supports the formats specified in JSON schema v4 (such as date-time). If you want to add your own custom formats pass them as the formats options to the validator:

const validate = validator({
  type: 'string',
  format: 'no-foo'
}, {
  formats: {
    'no-foo': (str) => !str.includes('foo'),
  }
})
console.log(validate('test')) // true
console.log(validate('foo')) // false

const parse = parser({
  $schema: 'https://json-schema.org/draft/2019-09/schema',
  type: 'string',
  format: 'only-a'
}, {
  formats: {
    'only-a': /^a+$/,
  }
})
console.log(parse('"aa"')) // { valid: true, value: 'aa' }
console.log(parse('"ab"')) // { valid: false }

External schemas

You can pass in external schemas that you reference using the $ref attribute as the schemas option

const ext = {
  type: 'string'
}

const schema = {
  $ref: 'ext#' // references another schema called ext
}

// pass the external schemas as an option
const validate = validator(schema, { schemas: { ext: ext }})

console.log(validate('hello')) // true
console.log(validate(42)) // false

schemas can be either an object as shown above, a Map, or plain array of schemas (given that those have corresponding $id set at top level inside schemas themselves).

Enabling errors shows information about the source of the error

When the includeErrors option is set to true, @exodus/schemasafe also outputs:

  • keywordLocation: a JSON pointer string as an URI fragment indicating which sub-schema failed, e.g. #/properties/item/type
  • instanceLocation: a JSON pointer string as an URI fragment indicating which property of the object failed validation, e.g. #/item
const schema = {
  type: 'object',
  required: ['hello'],
  properties: {
    hello: {
      type: 'string'
    }
  }
}
const validate = validator(schema, { includeErrors: true })

validate({ hello: 100 });
console.log(validate.errors)
// [ { keywordLocation: '#/properties/hello/type', instanceLocation: '#/hello' } ]

Or, similarly, with parser API:

const schema = {
  $schema: 'https://json-schema.org/draft/2019-09/schema',
  type: 'object',
  required: ['hello'],
  properties: {
    hello: {
      type: 'string',
      pattern: '^[a-z]+$',
    }
  },
  additionalProperties: false,
}
const parse = parser(schema, { includeErrors: true })

console.log(parse('{ "hello": 100 }'));
// { valid: false,
//   error: 'JSON validation failed for type at #/hello',
//   errors: [ { keywordLocation: '#/properties/hello/type', instanceLocation: '#/hello' } ]
// }

Only the first error is reported by default unless allErrors option is also set to true in addition to includeErrors.

See Error handling for more information.

Generate Modules

See the doc/samples directory to see how @exodus/schemasafe compiles the draft/2019-09 test suite.

To compile a validator function to an IIFE, call validate.toModule():

const { validator } = require('@exodus/schemasafe')

const schema = {
  type: 'string',
  format: 'hex'
}

// This works with custom formats as well.
const formats = {
  hex: (value) => /^0x[0-9A-Fa-f]*$/.test(value),
}

const validate = validator(schema, { formats })

console.log(validate.toModule())
/** Prints:
 * (function() {
 * 'use strict'
 * const format0 = (value) => /^0x[0-9A-Fa-f]*$/.test(value);
 * return (function validate(data) {
 *   if (data === undefined) data = null
 *   if (!(typeof data === "string")) return false
 *   if (!format0(data)) return false
 *   return true
 * })})();
 */

Performance

@exodus/schemasafe uses code generation to turn a JSON schema into javascript code that is easily optimizeable by v8 and extremely fast.

See Performance for information on options that might affect performance both ways.

Previous work

This is based on a heavily rewritten version of the amazing (but outdated) is-my-json-valid by @mafintosh.

Compared to is-my-json-valid, @exodus/schemasafe adds security-first design, many new features, newer spec versions support, slimmer and more maintainable code, 0 dependencies, self-contained JS module generation, fixes bugs and adds better test coverage, and drops support for outdated Node.js versions.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].