npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cookiemonsterdev/casl-typeorm

v1.0.5

Published

TypeORM integration for CASL — filter queries and check permissions using ability rules

Readme

@cookiemonsterdev/casl-typeorm

TypeORM integration for CASL — query only the records a user is allowed to access.

Installation

pnpm add @cookiemonsterdev/casl-typeorm @casl/ability typeorm

Overview

@cookiemonsterdev/casl-typeorm provides two main building blocks:

  • createTypeOrmAbility — creates a CASL Ability that accepts native TypeORM FindOptionsWhere conditions, enabling both database-level filtering and instance-level permission checks.
  • accessibleBy — converts ability rules into a FindOptionsWhere array you can pass directly to TypeORM's find, findOne, or findAndCount.

Usage

1. Define an ability

Use TypeORM operators directly as conditions — the same operators you already use in find():

import { In, MoreThan, Not } from 'typeorm';
import { createTypeOrmAbility } from '@cookiemonsterdev/casl-typeorm';

// Rules are evaluated last-to-first: the last rule has the highest priority.
const ability = createTypeOrmAbility([
  { action: 'read', subject: 'Article', conditions: { published: true } },
  { action: 'read', subject: 'Article', conditions: { authorId: userId } },
  // This cannot rule is last → highest priority → overrides the can rules above
  {
    action: 'read',
    subject: 'Article',
    conditions: { status: In(['banned', 'deleted']) },
    inverted: true,
  },
]);

2. Filter database queries

import { accessibleBy } from '@cookiemonsterdev/casl-typeorm';

const where = accessibleBy(ability, 'read').ofType('Article');

if (!where) {
  // null means the user has no access to any records
  return [];
}

const articles = await articleRepository.find({ where });

where is a FindOptionsWhere<Article>[]. TypeORM treats an array as OR — each element is an AND-merged condition set. The result already encodes the full rule logic, including cannot constraints.

3. Instance-level checks

createTypeOrmAbility also wires up a runtime conditions matcher, so ability.can() works on individual entity instances:

import { subject } from '@casl/ability';

const article = await articleRepository.findOneBy({ id: 1 });

if (ability.can('read', subject('Article', article))) {
  // user is allowed
}

Relations must be loaded. If a rule condition references a nested relation (e.g. { author: { isVerified: true } }), that relation must be loaded on the entity before calling ability.can(). Accessing an unloaded relation throws an error at runtime:

// throws: Relation "author" is not loaded. Load the relation before checking ability.can().
ability.can('read', subject('Article', articleWithoutAuthor));

// correct — load the relation first
const article = await articleRepository.findOne({
  where: { id: 1 },
  relations: { author: true },
});
ability.can('read', subject('Article', article));

Using with AbilityBuilder

import { AbilityBuilder } from '@casl/ability';
import { createTypeOrmAbility, TypeOrmAbility } from '@cookiemonsterdev/casl-typeorm';
import { Not } from 'typeorm';

type Actions = 'create' | 'read' | 'update' | 'delete';
type Subjects = 'Article' | 'Comment';

function defineAbilityFor(user: User): TypeOrmAbility<[Actions, Subjects]> {
  const { can, cannot, build } = new AbilityBuilder(createTypeOrmAbility);

  if (user.isAdmin) {
    can('manage', 'all');
  } else {
    can('read', 'Article', { published: true });
    can('read', 'Article', { authorId: user.id });
    cannot('read', 'Article', { secret: Not(false) });

    can('create', 'Comment');
    can('update', 'Comment', { authorId: user.id });
  }

  return build();
}

AbilityBuilder follows the same last-wins priority: cannot defined after can overrides it.

API

createTypeOrmAbility(rules?, options?)

Creates a CASL Ability configured to use TypeORM FindOptionsWhere conditions.

| Parameter | Type | Description | | --------- | ------------------------------------ | -------------------------------------------------------------------------------- | | rules | RawRuleFrom<A, FindOptionsWhere>[] | Initial rules array | | options | AbilityOptions | Standard CASL ability options (excluding conditionsMatcher and fieldMatcher) |

Returns a TypeOrmAbility<A> instance.

accessibleBy(ability, action?)

Converts ability rules into an AccessibleRecords builder.

| Parameter | Type | Default | | --------- | ------------ | -------- | | ability | AnyAbility | — | | action | string | 'read' |

.ofType(subjectType)

Returns FindOptionsWhere<Entity>[] | null.

  • Array — use directly as the where option in find(), findOne(), etc.
  • null — user has no access; handle by returning an empty result or throwing ForbiddenError.
const where = accessibleBy(ability).ofType(Article);
// or with a string subject:
const where = accessibleBy(ability).ofType('Article');

typeormQueryMatcher(conditions)

The runtime conditions matcher used internally by createTypeOrmAbility. You can use it directly if you create a custom Ability:

import { Ability, fieldPatternMatcher } from '@casl/ability';
import { typeormQueryMatcher } from '@cookiemonsterdev/casl-typeorm';

const ability = new Ability(rules, {
  conditionsMatcher: typeormQueryMatcher,
  fieldMatcher: fieldPatternMatcher,
});

Supports: plain equality, Not, In, MoreThan, MoreThanOrEqual, LessThan, LessThanOrEqual, IsNull, Between, Like, ILike, And, Or, ArrayContains, ArrayContainedBy, ArrayOverlap.

Raw is not supported for instance-level checks — it can only be used in query conditions.

Relations must be loaded before instance-level checks. If a condition references a nested relation and that relation is null or undefined on the entity, an error is thrown. See Instance-level checks for details.

Limitations

Multi-field cannot conditions are approximated at the field level. Given:

cannot('read', 'Article', { secret: true, internal: true });

The generated condition is { secret: Not(true), internal: Not(true) } which evaluates as secret != true AND internal != true. The semantically correct form is NOT (secret = true AND internal = true) = secret != true OR internal != true. For single-field conditions, the behaviour is exact.

License

MIT © Mykhailo Toporkov