When you write access control checks, tests usually look deceptively calm. A manager tries to edit an order from their own branch and passes. A blocked user knocks on the same endpoint and gets rejected. Green checkmarks light up, and the release ships to production. Then you discover that one extra space in the condition parser exposed private tasks to the whole dev team, or two empty undefined values happily matched as "the same document owner."
Access control only looks like a couple of if statements from the outside. Once you move conditions out of controllers into a dedicated engine, issues surface that rarely cross your mind when reading docs. You run into conflicting policies, a third state between "allowed" and "denied," properties inherited from JavaScript prototypes, and debug logs overwritten by the very next request.
A great way to look under the hood is the two-year real-world experience of Vasiliy Novosad's three-person web studio. They build custom CRM and ERP systems in TypeScript and Node.js and extracted their permission checks into a synchronous ABAC engine called @via-profit/ability (current version 3.8.3, MIT license, zero runtime dependencies). Below, we'll unpack how this engine works and five specific security holes they caught and patched along the way.
From Scattered RBAC to Synchronous ABAC Without Database Queries
Almost every project with permissions starts with RBAC (Role-Based Access Control). You have admin, manager, and accountant, with privileges like order.update tied to each role. As long as business logic stays simple, this works great. Trouble starts when access depends on the properties of a specific object.
Take a real CRM task: a manager can edit an order, but only in their own branch, while the order is still open and the total is under 500,000. An administrator can do more, and a blocked user can do nothing. You need to check this both on the server before saving to the database and on the client so you don't show an unusable button. If you leave these checks inside handler code, you get a familiar mess:
// A condition that quickly spreads across the codebase
const canUpdate =
user.privileges.includes("order.update") &&
user.branchId === order.branchId &&
order.total < 500_000 &&
order.status !== "completed";
One controller checks all four conditions, the next checks only the privilege, and the frontend checks the privilege and status. Formally, all three places guard the same order.update action, yet three different rules live in production. The moment the business raises the amount limit or adds an active subscription check, half your endpoints will forget to update.
This is where ABAC (Attribute-Based Access Control) comes in—controlling access based on attributes of the user, the resource, and the environment. Roles don't disappear; they simply become one attribute among others. The main shift is moving every condition out of scattered controllers into a single declarative configuration that runs identically on the server and in the browser.
Mature tools like CASL, Casbin, and Cedar already exist, but for a small studio's needs, the team wanted a compact synchronous engine with no dependencies and one strict rule at the door: the application prepares the data, and the policy only compares it. The server fetches the user from a trusted session, loads the order from the database, computes the subscription flag ahead of time, and hands ready-made objects to the engine.
Policies themselves cannot execute arbitrary code. There are no custom functions, database calls, loops, or date math inside them. If access depends on a subscription, the app passes a boolean hasActiveSubscription flag; if it depends on the current time, it passes a prepared value. That keeps every check synchronous and reproducible: the same policies, strategy, inputs, and engine version always produce the exact same answer.
Early on, the team tried both async checks and a decision cache, then removed both. Without network or database I/O, Promise added nothing, and a cache key required serializing input objects on every call. Today, the engine only caches policy lookups by permission key (up to 1024 keys) and re-evaluates attributes on every call.
Here is how a basic setup looks with @via-profit/ability@3.8.3:
import {
ability,
AbilityResolver,
DenyOverridesStrategy,
} from "@via-profit/ability";
const policies = ability`
@name "Менеджер своего филиала"
permit permission.order.update if all:
env.user.roles contains 'manager'
order.branchId equals env.user.branchId
order.total < 500000
order.status not equals 'completed'
env.hasActiveSubscription equals true
@name "Блокировка пользователя"
deny permission.order.update if all:
env.user.blocked equals true
`;
const resolver = new AbilityResolver(policies, DenyOverridesStrategy);
// Attributes of the target object being acted upon
const resource = {
order: { branchId: 7, total: 120_000, status: "draft" },
};
// Trusted environment assembled by the server itself
const environment = {
user: { roles: ["manager"], branchId: 7, blocked: false },
hasActiveSubscription: true,
};
// Returns true if access is allowed
resolver.resolve("order.update", resource, environment).isAllowed();
// On the server before writing: throws AbilityError on denial
resolver.enforce("order.update", resource, environment);
Notice the path prefixes. Inside the policy text, you write permission.order.update, while the resolver call only needs order.update. Anything without a prefix (order.total, order.status) is read from the second argument, resource. Anything starting with env. is read strictly from the third argument, environment. That split prevents a classic bug where a client slips blocked: false or a fake role into the request body: the server must build environment from the session and database without mixing in user input.
From JSON to a Text DSL: Unified Pipeline and the Dotted-String Trap
To keep policies separate from code, you need to store them in a database and send them over the network. The first attempt in early v2 (commit 4d6f769 from April 23, 2025) used JSON with numeric codes—for example, 1 meant permit in effect and AND in compareMethod:
{
"action": "order.update",
"effect": 1,
"compareMethod": 1,
"ruleSet": [
{
"compareMethod": 1,
"rules": [{ "matches": ["order.authorId", "=", "user.id"] }]
}
]
}
Storing that config in a database was easy, but editing it by hand and reading it in code reviews was painful. Worse, standard JSON.parse() only checks valid JSON syntax. If an unknown operator sneaks in or nesting gets scrambled, the parser stays silent, and without a separate validation schema, a broken rule reaches your access checks.
So the engine gained a compact DSL (Domain-Specific Language). It stripped away noisy JSON boilerplate and covered standard checks for numbers, strings, arrays, and logical groups:
| Category | Operators and Constructs | Policy Example |
|---|---|---|
| Comparison | equals, not equals, <, <=, >, >= | order.total < 500000 |
| Arrays | contains, not contains, contains all, contains any, in, not in | env.user.roles contains 'manager' |
| Strings | starts with, ends with | file.path starts with '/public/' |
| Presence | is defined, is not defined, is null, is not null | user.token is defined |
| Logical groups | if all:, if any:, all of:, any of:, except any of: | permit permission.order.update if all: |
| Metadata | @name, @tags | @name "Branch check" |
Rather than dropping JSON, the team funneled both formats into one processing pipeline. The text DSL passes through AbilityDSLLexer and AbilityDSLParser, while serialized configs go through AbilityJSONParser. Both paths produce the same AbilityPolicy[] array. From there, the resolver selects policies by permission key, evaluates the condition tree (AbilityRule and AbilityRuleSet), hands matches to the strategy, and builds the final AbilityResult.
DSL ─► AbilityDSLLexer ─► tokens ─► AbilityDSLParser ─► AbilityPolicy[]
JSON ─► AbilityJSONParser ──────────────────────────────► AbilityPolicy[]
│
filter policies by permission
▼
evaluate condition tree
▼
strategy ─► AbilityResult
In practice, you write rules in readable DSL and pass compact JSON between the server, database, and client via AbilityJSONParser:
import { AbilityJSONParser } from "@via-profit/ability";
const readPolicies = ability`
permit permission.order.read if all:
order.status equals 'published'
`;
// Serialize to a string for the DB or client transport
const payload = JSON.stringify(AbilityJSONParser.toJSON(readPolicies));
const restored = AbilityJSONParser.parse(JSON.parse(payload));
const jsonResolver = new AbilityResolver(restored, DenyOverridesStrategy);
const allowed = jsonResolver
.resolve("order.read", { order: { status: "published" } })
.isAllowed(); // true
Still, building a custom DSL immediately surfaced a subtle pitfall: dotted strings. In the early model, the engine could treat any string containing a dot as an object property path. That sounds reasonable until you compare a version '1.2.3' or a domain 'api.example.com'. The meaning of an expression ended up depending on the string's content.
The fix was a strict syntactic split. A literal in the DSL is always quoted (document.version equals '1.2.3'), while a field path is written without quotes (document.ownerId equals env.user.id). Inside the rule model, an explicit resourceType: 'value' | 'path' field records this choice at parse time, so the resolver never has to guess. And if the text has an empty group, a typo in an operator, or a malformed annotation, the parser immediately throws AbilityDSLSyntaxError with the exact line, column, and context snippet.
Hole #1: The Parser Indentation Bug and the Power of Negative Tests
The nastiest vulnerability in the engine's history came from a gap between how humans read indented text and how the parser assembled it. It was fixed on October 27, 2026 in commit 4f4c9aa (fix(dsl): evaluate nested groups instead of flattening them).
Look at a standard bug-tracker rule. An administrator can edit an issue, or a programmer can edit it, but only if the issue is still open and they are the assignee or creator:
permit permission.issue.update if any:
env.user.roles contains 'administrator'
all of:
env.user.roles contains 'programmer'
issue.isClosed equals false
any of:
issue.isAssignee equals true
issue.isCreator equals true
To a developer's eyes, this is crystal clear. The inner any of: block is indented under all of:, so the boolean formula is administrator OR (programmer AND issue is open AND (assignee OR creator)).
The old parser, however, ignored indentation depth completely. As soon as it saw a new all of: or any of: header, it closed the current group and started the next one at the top if any: level. Instead of a nested tree, it built a flat soup:
administrator
OR (programmer AND issue is open)
OR assignee
OR creator
The security impact was severe. Any programmer gained edit access to every open issue in the system, even ones they had nothing to do with. Meanwhile, a regular issue creator with a viewer role could edit an already closed issue without programmer permissions. The parser quietly widened access, and zero errors fired.
Drafting diagram contrasting a nested all of and any of condition tree with the flat parsing of an older parser that opened bypass access.
A one-line parser patch wasn't enough because the data model itself couldn't store groups inside groups. The team had to rework four layers: add a ruleSets field alongside rules in AbilityRuleSet, teach the parser to compare the current group header's column with the next token's column, rewrite tree evaluation recursively, and update recursive traversal for JSON serialization, explain diagnostics, and the type generator. They also banned except inside nested groups—exclusions are only allowed at the top policy level.
The core parser fix fits in a few lines:
// If the new group header isn't indented deeper than its parent, close the current group
if (isGroupHeader(nextToken)) {
if (nextToken.column <= parentHeader.column) {
// Sibling group: the caller level will pick it up
return group;
}
// Deeper indent means a nested subgroup
group.addRuleSet(parseGroup());
}
The most painful lesson from this bug is about testing. A positive test like "an assigned programmer edits an open issue" passed cleanly on the broken parser! When you only test scenarios where access should be granted, accidental privilege escalation stays invisible. Only negative regression tests—a matrix of cases where access must be denied—catch bugs like this:
import assert from "node:assert/strict";
// Run the issue.update rule above through a case matrix
const resolver = new AbilityResolver(issuePolicies, DenyOverridesStrategy);
// [role, isClosed, isAssignee, isCreator, expectedAllowed]
const cases = [
// Negative cases: the old parser wrongly allowed rows 1 and 3
["programmer", false, false, false, false],
["programmer", true, true, false, false],
["viewer", false, false, true, false],
// Positive cases
["programmer", false, true, false, true],
["administrator", true, false, false, true],
] as const;
for (const [role, isClosed, isAssignee, isCreator, allowed] of cases) {
const result = resolver.resolve(
"issue.update",
{ issue: { isClosed, isAssignee, isCreator } },
{ user: { roles: [role] } },
);
assert.equal(result.isAllowed(), allowed);
}
This five-row table guards against both the old flattening bug and future grammar regressions. If someone rewrites the rule and accidentally lets extra users in, the very first negative case breaks the build.
Holes #2 and #3: The !isDeny() Trap, Policy Conflicts, and the except Catch
The next pair of pitfalls sat in how the engine reduces policy results to a final yes or no. In early v2 (4d6f769), the resolver returned null when no policy matched. Meanwhile, isDeny() checked strictly for an explicit deny effect:
// Historical snippet from v2 (4d6f769)
const effect = AbilityResolver.resolve(policyOrPolicies, resource, action);
return effect !== null && effect.isEqual(AbilityPolicyEffect.DENY);
When effect came back null, both isDeny() and isPermit() returned false. That created a third, ambiguous state: "neither allowed nor denied." If a handler somewhere used if (!isDeny) { updateOrder(); } out of habit, the action quietly went through without a single matching permit.
The fix is enforcing two strict security rules. First, default deny: if no policy explicitly permits an action (or no policies exist for that key), the answer is always deny. Second, fail closed: any unexpected or unknown strategy result can never turn into a permit. In AbilityResult v3.8.3, a single line enforces this:
// Anything other than an explicit permit is forced to deny
this.effect =
effect === AbilityPolicyEffect.permit ? effect : AbilityPolicyEffect.deny;
Of course, this line won't save you if your app swallows an exception thrown by a malformed policy and keeps writing to the database. Still, the third state is gone from the API for good.
The second half of the problem is conflicting policies. Suppose one policy lets anyone with the manager role edit orders, while a second policy denies all actions for blocked users (env.user.blocked equals true). When a blocked manager sends a request, both policies match at once. If you just pick the last matching policy, reordering blocks in a config file silently breaks security.
That is why conflict resolution lives in dedicated strategy classes. @via-profit/ability ships eight of them: DenyOverridesStrategy, PermitOverridesStrategy, FirstMatchStrategy, SequentialLastMatchStrategy, PriorityStrategy, AllMustPermitStrategy, AnyPermitStrategy, and OnlyOneApplicableStrategy.
Production systems normally default to DenyOverridesStrategy. The logic is simple: if even one deny matches, reject immediately. If there is no deny and at least one permit, allow. If nothing matches, reject. By contrast, PermitOverridesStrategy works the opposite way: a single permit lets even a blocked manager straight through.
Instead of juggling two trees and strategy switches in your head, try both scenarios live below—both the group-nesting bug and permit colliding with deny under different strategies:
Interactive model: parser nesting bug and conflict strategies
On the first tab, you can clearly see how the old parser grants PERMIT on someone else's open issue when the role is programmer without "Assignee" or "Creator" checked, while the fixed one blocks it. On the second tab, switching from DenyOverridesStrategy to PermitOverridesStrategy or FirstMatchStrategy instantly lets the blocked manager into the order. Because the strategy is a core part of your security config, conflict tests must always run against your production strategy.
Another common surprise involves except. Suppose you want to forbid editing completed orders for everyone except administrators. Intuitively, it feels like except flips the denial and automatically grants the admin permission. In reality, it is stricter: except simply cancels that policy from firing, without turning deny into permit.
const denyPolicies = ability`
deny permission.order.update if all:
order.status equals 'completed'
except any of:
env.user.roles contains 'administrator'
`;
const denyResolver = new AbilityResolver(denyPolicies, DenyOverridesStrategy);
// Returns true (denied): the deny is skipped, but there is no permit!
denyResolver
.resolve(
"order.update",
{ order: { status: "completed" } },
{ user: { roles: ["administrator"] } },
)
.isDenied();
For an administrator, this deny policy simply drops out of the vote. To actually let them edit a completed order, you still need a separate permit policy alongside it.
Hole #4: JavaScript Data Quirks, Prototypes, and DSL Injection
Even when the parser builds a clean tree and the strategy enforces default deny, JavaScript's own quirks enter the picture. On November 25, 2026, a dedicated security commit 270c5d5 (fix: harden access checks and prevent DSL template injection) closed a batch of these traps.
The first nuance is undefined vs. null. If you write user.token is not null and the token field is missing altogether, undefined !== null evaluates to true. Whenever you need to guarantee a value is both present and non-null, you must write both checks: user.token is defined and user.token is not null. Of course, that only checks presence, not token validity—authentication happens before calling the engine.
The second trap is far sneakier. Look at a classic ownership check: document.ownerId equals env.user.id. What happens if a controller accidentally fails to load the document and also forgets to pass the user into environment? Both sides evaluate to undefined. A naive undefined === undefined in JavaScript returns true, making an anonymous user without a document its rightful owner! Commit 270c5d5 added a direct ban: two undefined values compared via equals no longer count as equal. One caveat remains: null === null still matches as an ordinary value, so nullable fields should also be guarded with is not null.
The third pitfall is prototype inheritance (Object.prototype.hasOwnProperty). Reading user.active in JavaScript checks the object first, then walks up the prototype chain if the key is missing. If an object like Object.create({ active: true }) enters environment, normal dot access returns true even though active isn't an own property. The engine switched to checking every path segment with Object.prototype.hasOwnProperty.call(current, prop). Keep in mind that an own getter on an object still runs when read, so always feed plain DTO data objects into the resolver.
The fourth fix targets tagged template literals (calls like ability`...` ). Previously, a developer could interpolate a variable directly into a policy string via ${userId}. That turned user data into raw DSL source code—classic DSL injection, just like string-concatenated SQL. Now ability`...` forbids any ${...} interpolation: TypeScript rejects it at the type level with never[], and JavaScript throws a runtime error. Every dynamic value must travel through resource and environment.
Isometric cutaway of the engine's security corridor showing four physical barriers against undefined matching, prototype chains, and DSL injections.
Here is how those three protections look in code:
// 1. Two undefined values no longer match as the same owner
const ownerResolver = new AbilityResolver(
ability`
permit permission.document.edit if all:
document.ownerId equals env.user.id
`,
DenyOverridesStrategy,
);
ownerResolver.resolve("document.edit", {}).isDenied(); // true
// 2. Prototype properties are ignored (hasOwnProperty)
const activeResolver = new AbilityResolver(
ability`
permit permission.document.edit if all:
env.user.active equals true
`,
DenyOverridesStrategy,
);
const inheritedUser = Object.create({ active: true });
activeResolver
.resolve("document.edit", {}, { user: inheritedUser })
.isDenied(); // true
// 3. ${userId} interpolation is forbidden (never[] in TS, throws in JS)
Naturally, this won't stop manual string concatenation passed to new AbilityDSLParser(text)—you should never assemble policy text from untrusted user input under any circumstances.
Debugging with Snapshot explain(), Type Generation, and Engine Boundaries
Once you pass a dozen policies with nested all of: / any of: groups and except clauses, a bare false stops being enough. A support ticket says "the manager can't save an order," and you need to see within a minute what failed: wrong branch, status, total, expired subscription, or an accidental block.
To make debugging painless, the engine provides explainToString() and explainToJSON(). You can label policies and individual rules with @name and print the full decision tree after a check:
// Create a resolver with human-readable rule names via @name
const explainResolver = new AbilityResolver(
ability`
@name "Редактировать можно только черновик"
permit permission.order.update if all:
@name "Проверка статуса"
order.status equals 'draft'
@name "Проверка филиала"
order.branchId equals env.user.branchId
`,
DenyOverridesStrategy,
);
const denied = explainResolver.resolve(
"order.update",
{ order: { status: "completed", branchId: 7 } },
{ user: { branchId: 7 } },
);
console.log(denied.explainToString());
const before = denied.explainToJSON();
// The next resolver call must not mutate the previous result
explainResolver.resolve(
"order.update",
{ order: { status: "draft", branchId: 7 } },
{ user: { branchId: 7 } },
);
assert.deepEqual(denied.explainToJSON(), before);
Your console prints a clean tree showing that the check tripped on the order status and never even evaluated the branch because of AND short-circuiting:
== order.update DENIED==
[MISMATCH ✗] POLICY <permit> Редактировать можно только черновик
└─ [MISMATCH ✗] RULESET g_b1f5f88ef4
├─ [MISMATCH ✗] RULE Проверка статуса (order.status = "draft")
└─ [SKIPPED …] RULE Проверка филиала (order.branchId = env.user.branchId)
Tree nodes have four internal statuses: MATCH, MISMATCH, PENDING (printed as SKIPPED in text output), and DISABLED. That brought out the fifth subtle bug: rule and group objects themselves stored the state of the last evaluation. If AbilityResult built its report directly from those live objects, the very next resolver.resolve(...) call on the server would silently overwrite the previous request's explanation.
The fix was state snapshots: inside the AbilityResult constructor, it calls strategy.policies.map((policy) => policy.snapshot()). This isn't a deep clone of policies and inputs, just a lightweight capture of evaluation results so logs never clobber each other. Server-side, this output saves huge amounts of incident debugging time, though you must never send raw explain data to the client unfiltered—internal rule names reveal too much business logic.
The second pain point of any text DSL is losing static typing. The TypeScript compiler sees a plain string and won't warn you if you mistype 'order.updtae' or pass total: '120000' as a string instead of a number. Those bugs only surface at runtime.
To bring back IDE autocomplete and argument checking, the library includes AbilityTypeGenerator. It walks parsed policies and generates an ability.types.ts file with Resources, Environment, and PolicyTags types, which you pass into the template generic:
import { writeFileSync } from "node:fs";
import { AbilityTypeGenerator } from "@via-profit/ability";
import type { Resources, Environment, PolicyTags } from "./ability.types";
// Step 1: generate ability.types.ts from parsed policies at build time
writeFileSync(
"ability.types.ts",
new AbilityTypeGenerator(policies).generateTypeDefs(),
);
// Step 2: attach the generated contract to the ability template
const typedPolicies = ability<Resources, Environment, PolicyTags>`
permit permission.order.update if all:
order.total < 500000
order.branchId equals env.user.branchId
`;
const typedResolver = new AbilityResolver(
typedPolicies,
DenyOverridesStrategy,
);
// TS catches total: '120000' and typos like 'order.updtae'
typedResolver.resolve(
"order.update",
{ order: { total: 120_000, branchId: 7 } },
{ user: { branchId: 7 } },
);
The generator infers number from numeric comparisons, arrays from contains, and strings from string operators. When two fields are simply compared to each other without extra constraints (order.branchId equals env.user.branchId), the inferred type is unknown, which you can narrow by intersecting with your domain model. You do need to re-run generation whenever .dsl files change, and as always in TypeScript, types disappear at runtime—so server-side input validation is still mandatory.
Performance-wise, the synchronous, zero-I/O design gives predictable headroom. Benchmarks from the official repository (Node.js v24.12.0, AMD Ryzen 7 PRO 3700, Linux x64) show how the engine behaves under load:
Average operation time in @via-profit/ability (Node.js v24.12.0, Ryzen 7 PRO 3700)
Scaling the rule base from twenty policies to two thousand barely moves resolve latency thanks to the permission-key cache. The main jump happens when enforce denies access: instantiating AbilityError and building a V8 stack trace costs several times more than the check itself. Parsing 200 policies from text DSL at startup takes 2.95 ms, and type generation takes 1.38 ms. In a stress test with 5,000 policies of 10 rules each on a single key, one resolve call reaches 6.64 ms.
In the studio's own CRM, rules live in separate .dsl files per module (clients, projects, bug tracker, finance), are loaded together at server startup, and log denials with explain. Still, the library intentionally draws four hard boundaries. First, browser checks only control UI: hiding a button never protects an API, so the server always re-checks using trusted data. Second, the engine doesn't generate SQL filters for list queries—fetching only the orders a manager can see is handled separately (unlike CASL with its ORM adapters). Third, order status can change between reading attributes and writing to the DB (a classic TOCTOU race), so database transactions remain the app's job. Fourth, policies are trusted configuration, so never accept policy JSON from clients.
Judging its maturity honestly, @via-profit/ability is a niche open-source tool from a small studio (at the time of review, the repo had no GitHub stars yet, though the authors have run it in their own projects for two years). For a large product needing multi-year ecosystem support, CASL, Casbin, or AWS Cedar are safer bets. If you want to test the DSL syntax, explain tree, and type generation right in your browser, try the interactive playground, install it with npm install @via-profit/ability@3.8.3, or inspect the source and tests in the GitHub repository.
What to check in your permission system before shipping
- Every policy with nested
AND/ORlogic has negative tests verifying that access is NOT granted to extra roles or states. - Unmatched policies and any unknown error always yield
deny(default denyandfail closed), with noif (!isDeny)checks in code. - Conflicts between
permitanddenyare tested against the production strategy, andexceptis never treated as an automatic permit. - Comparing two missing fields (
undefined === undefined) denies access, path lookups ignore prototype properties, and user input is never concatenated into policy text. -
explaindiagnostics write details only to server logs and never leak internal business rule names to the client.

![Node.JS [ru]](/api/digests/it_development/daily/20261202/assets/sources/we-use-js.jpg?v=41a4e6651b381078292301a12be421de7d74bc10e66eb18c05dfb41042c58831)

