serafim
v4.0.0
Published
A library that provides custom JSON notation for the find method of TypeORM
Maintainers
Readme
Serafim
Why Serafim?
Serafim the portuguese word for Seraph. It is also an acronym of Search Requests API for TypeORM's Find Method.
What is the purpose of this package?
This package aims to facilitate fetching custom data when using TypeORM, providing an API to make dynamic queries using JSON.
Instalation
npm install --save serafim🔒 Security release (hardening within 3.x)
3.0.0 and every 2.x release are vulnerable to prototype pollution through a
field path ({"field": "__proto__.polluted"}), to memory exhaustion from a small
filter (an AND of thirty two-way ORs is ~2 KB of JSON and 2^30 conditions), and to
filter bypasses where a client-supplied filter cancelled a server-side condition.
2.x additionally builds SQL by string concatenation and is open to SQL injection:
upgrade, do not patch around it.
This release fixes those and bounds what an untrusted expression can cost:
- Field paths are validated.
__proto__,constructorandprototypesegments, empty segments, non-string fields and paths longer thanmaxPathDepth(10) throw — ingetWhere,getRelationsandgetOrder. - The expansion is bounded by
maxConditions(100),maxValues(10000),maxDepth(64),maxPathDepth(10) andmaxRelations(16), each overridable per call:getWhere(expression, { maxConditions: 500 }). Expressions that used to be accepted may now throw — useINfor value lists, or raise the limit. - A server-side condition survives a client filter. Two conditions on the same
field are now both applied (TypeORM
And(...)) instead of the last one silently winning;null/undefined/ emptyAND()entries no longer empty out anAND(which used to return{}— every row); an emptyOR()can never match, sogetWherethrows instead of matching everything. - Stricter values. An unknown
operationthrows (including inherited names such asconstructor),searchTermmust be a scalar, andsortOrdermust be"ASC","DESC","unsorted",1or-1— normalized, since TypeORM reads a"Desc"as ascending. typeormmoved topeerDependencies, so your app's copy is the one Serafim builds operators for; a duplicated copy made TypeORM skip column transformers.- New:
getFields(expression)lists the field paths an expression references, for checking them against an allowlist.
See Security & limits for the full list, and Migrating to v3 for the behavior changes.
⚠️ Upgrading to 3.0.0 (may be breaking)
3.0.0 is a major release and may break existing code. If you already combined
conditions explicitly with AND(...) / OR(...) and passed valid inputs, the
generated queries are equivalent and you likely need no changes. Otherwise, review:
- Bare arrays are no longer accepted.
getWhere([a, b])/getRelations([a, b])now throw. Combine conditions explicitly withAND(...)(all must match) orOR(...)(any may match). A single condition can still be passed on its own. - Values are bound as query parameters (TypeORM's native
Equal,In,Like,Between, … operators) instead of being interpolated into raw SQL. This prevents SQL injection; the matched rows are unchanged for valid inputs. - Null / boolean operators were cleaned up:
NULL/IS→IS NULL,NOT→IS NOT NULL,TRUE/FALSE→IS TRUE/IS FALSE, and asearchTerm: nullis shorthand forIS NULL. These operators now ignoresearchTerm. - Invalid inputs throw instead of producing broken SQL:
INrequires a non-empty array,BETWEENrequires exactly two elements,LIKE/ILIKErequire a string.
Introduction and Usage
Given the following entities and relationships:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@Column()
password: string;
@OneToOne(() => Person)
person: Person;
@OneToOne(() => ProfilePicture)
profilePicture: ProfilePicture;
}@Entity()
export class ProfilePicture {
@PrimaryGeneratedColumn()
id: number;
@Column()
path: string;
}@Entity()
export class Person {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
surname: string;
@OneToOne(() => Address)
address: Address;
}@Entity()
export class Address {
@PrimaryGeneratedColumn()
id: number;
@Column()
address: string;
@Column()
zip: number;
}To extract custom information, you have to write custom queries, and there are two ways to do that in TypeORM. The first is to write queries using raw SQL, which uses the query method. The second way is to use the find method and specify the params. In both ways one would have to write an API, either to write custom raw SQL, either to customize the params. This package uses the latter, by translating JSON into meaningful params.
Only using TypeORM:
//frontend
const search = {
relations: {
person: {
address: true
},
profilePicture: true
},
where: [
{
person: {
address: {
state: "NY"
}
}
},
{
profilePicture: {
id: 1
}
}
],
order: {
person: {
address: {
state: "ASC"
}
}
}
}
//backend
userRepository.find({
relations: search.relations,
where: search.where,
order: search.order,
})Using Serafim:
//frontend
import { OR } from "serafim";
const search: Search = {
where: OR(
{
field: "person.address.state",
searchTerm: "NY",
},
{
field: "profilePicture.id",
searchTerm: 1
}
),
order: {
field: "person.address.state",
sortOrder: "ASC",
}
};
//backend
userRepository.find({
relations: getRelations(search.where), // search.where, not search.relations
where: getWhere(search.where),
order: getOrder(search.order),
})Conditions are never combined implicitly: pass a single condition, or group them
explicitly with AND(...) / OR(...). Passing a bare array throws.
With pure TypeORM, you need to know in advance what relations will be used in order to fetch custom data, whereas with Serafim, you just type what you need to fetch. With Serafim it is much easier as you can see!
Combining conditions (AND / OR)
A bare array is not accepted and throws: combine conditions with AND(...) (all must
match) or OR(...) (any may match). Both are first-class combinators that can be
nested (up to maxDepth, 64 levels by default):
import { AND, OR, getWhere } from "serafim";
const where = AND(
{ field: "person.address.state", searchTerm: "NY" },
OR(
{ field: "profilePicture.id", searchTerm: 1 },
{ field: "profilePicture.id", searchTerm: 2 }
)
);
userRepository.find({
relations: getRelations(where),
where: getWhere(where),
});getWhere(expression, options?) returns {} when the expression holds no condition
(undefined, null, or only empty groups), a single condition object when there is one
result, or an array of objects (an OR set) for multiple results. Inside a group, null /
undefined entries and empty AND() groups are skipped; an empty OR() can never
match, so an expression that depends on one throws. It also throws when the expansion
exceeds the limits. getRelations derives the relations
tree from the field paths referenced anywhere in the expression.
If the expression comes from a browser, check the fields it uses against an allowlist — Serafim validates that a path is well formed, not that a client may query it:
import { getFields } from "serafim";
for (const field of getFields(search.where)) {
if (!ALLOWED_FIELDS.has(field)) throw new BadRequestException(`Cannot filter by ${field}`);
}Documentation
Donations
Don't feel obligated. This package is FREE!
