restrict-v
A lightweight, extensible set of tools for applying limitations to runtime values.
Use with security-critical applications or when accepting external arguments.
Index
- API
- Restriction - Value limitiation framework
- restrict - Restriction instance presets and factories
- DeepFreeze - Small, safe, deep property freezing class
- Project
Restriction
Usage Summary
type Predicate<T> = (...value: T[]) => boolean;
type Assertion<T> = (...value: T[]) => void;
interface PassthroughValidator<T> {
<U extends T>(value: U): U;
<U extends T[]>(...value: U): U;
}
type Conditional<T> =
| Predicate<T>
| Assertion<T>
| PassthroughValidator<T>
| Restriction<T>;
type SchemaValueType<T> =
| Conditional<T>
| Schema<T>;
type Schema<T extends SchemaTarget> = {
[key in keyof T]: SchemaValueType<T[key]>
};
class Restriction<T> {
constructor(message: string, ...conditionals: Array<Conditional<T>>);
constructor(message: string, ...schemas: Array<Schema<T>>);
constructor(
message: string,
...conditionalsOrSchemas: Array<Conditional<T> | Schema<T>>
);
constructor(...conditionals: Array<Conditional<T>>);
constructor(...schemas: Array<Schema<T>>);
constructor(...conditionalsOrSchemas: Array<Conditional<T> | Schema<T>>);
}
Restriction
instances are functions that either return the value(s) passed to them or throw a RestrictionError
.
They can be created using an optional message and a list of functions.
When a restriction instance is called, any value(s) passed will be passed to the provided functions.
If any of these functions return a falsy value or throw, the restriction will throw.
Restrictions may also be constructed with a Schema
- an Object
or Array
whose values are either Restrictions or Schemas.
Schema Restrictions will throw if a passed value's structure differs from the Schema or if any of the values fail the Schema's restrictions.
Restrictions may be combined or extended with new Conditional
functions with .and
and .or
.
Both of these methods may be used in the same way as the base constructor.
Restriction messages may be changed using the .msg
method or with restriction.message =
assignment.
import { restrict, Restriction } from 'restrict-v';
const rOddNumber = new Restriction(
"Must be an odd 'number'",
restrict.number,
(v: number) => v % 2 === 1
);
const myOddNumber = rOddNumber(41);
rOddNumber(42);
const rUserData = new Restriction(
"Must be a UserData object",
{
name: restrict.string,
age: restrict.integer
.and(
'Must be a valid age < 200',
restrict.range(1, 200)
)
}
);
rUserData({ name: 'John Smith', age: 20 });
rUserData({ name: 'John Smith', age: 2000 });
Examples
Presets and Factories
The exported restrict
object contains some preset Restriction instances and factories.
Presets are standard Restrictions; Factories create Restrictions given some input.
import { restrict } from 'restrict-v';
const int: number = restrict.integer(24);
const [ intA, intB ]: [ number, number ] = restrict.integer(11, 23);
const int: number = restrict.integer(24.42);
const int = restrict.integer("24.42");
const value = restrict.lt(15)(10);
const value = restrict.gte(15)(10);
List of Presets
Preset Message
------ -------
- restrict.string
- restrict.number
- restrict.bigint
- restrict.boolean
- restrict.null
- restrict.undefined
- restrict.symbol
- restrict.integer
- restrict.positive
- restrict.negative
- restrict.Object
- restrict.Array
List of Factories
Factory Message
------- -------
- restrict.eq(any)
- restrict.neq(any)
- restrict.gt<
T extends number | bigint
>(T)
- restrict.lt<
T extends number | bigint
>(T)
- restrict.gte<
T extends number | bigint
>(T)
- restrict.lte<
T extends number | bigint
>(T)
- restrict.range<
T extends number | bigint
>(
T, T,
lowInclusive: boolean = true,
upInclusive: boolean = false
)
- restrict.instanceof(new() => any)
- restrict.match(string | RegExp)
Custom
import { Restriction } from 'restrict-v';
const rOddNumber = new Restriction(
"Must be an odd 'number'",
restrict.number,
(v: number) => v % 2 === 1
)
const myOddNumber = rOddNumber(41);
rOddNumber(42)
Schemas
import {
restrict,
Restriction,
RestrictionTargetType,
SchemaTargetType
} from 'restrict-v';
const SITE_CREATION_TIME = 1548174793502;
const rTimeWithinSiteExistence = restrict.range(SITE_CREATION_TIME, Date.now());
const sUserData = {
name: restrict.string,
age: restrict.number,
joined: rTimeWithinSiteExistence,
credentials: {
sessionToken: restrict.match(
/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/m
)
},
history: {
lastThreeVisits: [
rTimeWithinSiteExistence,
rTimeWithinSiteExistence,
rTimeWithinSiteExistence
]
}
};
const rUserData = new Restriction(sUserData)
.and(
(v: SchemaTargetType<typeof sUserData>) =>
v.history.lastThreeVisits[2] >= v.joined &&
v.history.lastThreeVisits[2] < v.history.lastThreeVisits[1] &&
v.history.lastThreeVisits[1] < v.history.lastThreeVisits[0]
)
.msg("Must be a valid user data object");
type UserData = RestrictionTargetType<typeof rUserData>;
const scaryUnknownJSONResponse = await (await fetch(...)).json();
const trustedExpectedResponse: UserData = rExpectedResponse(
scaryUnknownJSONResponse
)
Combinations
const rNumberLike = restrict.number
.or(restrict.bigint)
.or(restrict.boolean)
.msg("Must be a 'number', 'bigint', or 'boolean'")
rNumberLike('not any of those')
restrict.number
.or(restrict.bigint)
.or(restrict.boolean)
('still not any of those')
RestrictionErrors
class RestrictionError<T> extends Error {
name: "RestrictionError";
code: "ERR_RESTRICTION";
message: string;
value: T;
root: any;
messageStack: string[];
}
DeepFreeze
DeepFreeze is a small class that deeply freezes properties and prototypes without freezing any global objects.
import { DeepFreeze } from 'restrict-v';
const deepFreeze = new DeepFreeze();
export const foo = (v: string) => v + '_bar';
deepFreeze(this);
TODO
- Allow for circular references within Schema objects
- Add a forEach factory
- Add property restriction factory method
- Create RestrictedObject class
- Add parens simplification for default-generated
.and
and .or
combination messages
Contributing
I'd like to expand this concept without introducing too much bloat.
If you have an idea that you'd like to contribute, or if you see any opportunities for better TypeScript usage, please make a pull request.
Rules:
- All API arguments must be checked independent of TypeScript compiler
typeof
, instanceof
, Restriction
, etc...
- All API objects must be deeply frozen
License
Licensed under GPL-3.0-or-later
Copyright (c) Justin Collier jpcxist@gmail.com
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the internalied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.