Policy Objects for Authorization Logic
Policy objects gather who may do what into small testable classes instead of scattering role checks. See a TypeScript policy layer for a Node.js API.

A policy object is a small class or function that answers one question: may this user perform this action on this resource? Instead of scattering if (user.role === "admin") checks through controllers and views, you gather the authorization rules for each kind of resource into one place that can be read, tested and audited. This post builds policy objects in TypeScript 5.9 for a Node.js API: a policy per resource, a central check that denies by default, rules that depend on the resource and not only the role, and the tests that keep the rules honest.
The problem: checks everywhere
Authorization logic starts as a single if in one handler and spreads.
interface User { id: number; role: "admin" | "editor" | "viewer" }
interface Post { id: number; authorId: number; status: "draft" | "published" }
function editPost(user: User, post: Post) {
if (user.role === "admin" || (user.role === "editor" && post.authorId === user.id)) {
return "edited";
}
throw new Error("forbidden");
}
function deletePost(user: User, post: Post) {
if (user.role === "admin") return "deleted";
throw new Error("forbidden");
}
function showEditButton(user: User, post: Post) {
return user.role === "admin" || user.role === "editor";
}The rule for editing appears in editPost, and a looser, slightly different version appears in showEditButton, where the author check is missing. The interface shows a button that the server then refuses. This kind of drift is common: the same decision is made in several places, each a little different, and security bugs hide in the differences.
One policy per resource
A policy collects every rule for one resource type behind methods named for the actions.
export interface User { id: number; role: "admin" | "editor" | "viewer" }
export interface Post { id: number; authorId: number; status: "draft" | "published" }
export class PostPolicy {
constructor(private readonly user: User) {}
view(post: Post): boolean {
if (post.status === "published") return true;
return this.user.role === "admin" || post.authorId === this.user.id;
}
edit(post: Post): boolean {
if (this.user.role === "admin") return true;
return this.user.role === "editor" && post.authorId === this.user.id;
}
delete(post: Post): boolean {
return this.user.role === "admin";
}
create(): boolean {
return this.user.role === "admin" || this.user.role === "editor";
}
}
const ada: User = { id: 1, role: "editor" };
const lin: User = { id: 2, role: "editor" };
const draft: Post = { id: 10, authorId: 1, status: "draft" };
console.log(new PostPolicy(ada).edit(draft));
console.log(new PostPolicy(lin).edit(draft));
console.log(new PostPolicy(lin).view(draft));
console.log(new PostPolicy({ id: 3, role: "viewer" }).create());true
false
false
falseAda can edit her own draft, Lin cannot edit it and cannot even view it, and a viewer cannot create posts. Each rule has a name and one definition. The interface calls policy.edit(post) to decide whether to draw the button, and the handler calls the same method before saving, so the two cannot disagree.
Deny by default
A policy for a new action must not be silently permissive. Avoid designs where a missing rule means "allowed". A central function that looks up the action and returns false when none exists keeps that safe.
type Rule<U, R> = (user: U, resource: R) => boolean;
export function createAuthorizer<U, R>(rules: Record<string, Rule<U, R>>) {
return function can(user: U, action: string, resource: R): boolean {
const rule = rules[action];
if (!rule) return false;
return rule(user, resource) === true;
};
}
const can = createAuthorizer<{ role: string }, { locked: boolean }>({
read: () => true,
write: (u, r) => u.role === "editor" && !r.locked,
});
const editor = { role: "editor" };
console.log(can(editor, "read", { locked: true }));
console.log(can(editor, "write", { locked: true }));
console.log(can(editor, "archive", { locked: false }));true
false
falsearchive has no rule, so the answer is false. Typos in an action name fail closed, which is the safe direction. The === true comparison guards against a rule that accidentally returns a truthy non-boolean value.
Enforcing at the boundary
Policies decide, and something must enforce. In an HTTP handler, the check belongs before any change, and a failure should produce a clear status. Use 403 when the user is known but not allowed, and consider 404 when revealing that the resource exists would itself leak information.
import { PostPolicy, type Post, type User } from "./post-policy.ts";
class HttpError extends Error {
constructor(readonly status: number, message: string) {
super(message);
}
}
function authorize(allowed: boolean): void {
if (!allowed) throw new HttpError(403, "forbidden");
}
export function updatePost(user: User, post: Post, title: string) {
const policy = new PostPolicy(user);
if (!policy.view(post)) throw new HttpError(404, "not found");
authorize(policy.edit(post));
return { ...post, title };
}
const draft: Post = { id: 10, authorId: 1, status: "draft" };
for (const user of [{ id: 1, role: "editor" }, { id: 2, role: "editor" }] as User[]) {
try {
console.log(updatePost(user, draft, "New title"));
} catch (err) {
console.log((err as HttpError).status);
}
}{ id: 10, authorId: 1, status: 'draft', title: 'New title' }
404The author's edit succeeds. Lin cannot view the draft at all, so the handler answers 404, which does not confirm that the post exists. Someone who can see a post but not edit it gets 403. Checking view before edit is the pattern, since a user who may not see a resource has no business learning more about it.
Filtering lists
Single-resource checks are not enough for lists. Loading every post and calling view on each is slow and leaks counts. Push the rule into the query, so the database returns only what the user may see. A policy can expose a scope function that builds the condition.
interface Filter { where: string; params: unknown[] }
export function visiblePosts(user: { id: number; role: string }): Filter {
if (user.role === "admin") return { where: "1 = 1", params: [] };
return { where: "(status = 'published' OR author_id = ?)", params: [user.id] };
}
console.log(visiblePosts({ id: 5, role: "viewer" }));
console.log(visiblePosts({ id: 1, role: "admin" }));{ where: "(status = 'published' OR author_id = ?)", params: [ 5 ] }
{ where: '1 = 1', params: [] }The condition mirrors PostPolicy.view. Keep the two next to each other and test them together, because a mismatch means the list shows posts the detail page refuses, or the reverse. Use parameters for values, as above, and never build the condition by concatenating user input.
Rules that depend on the resource and the context
Role checks are the simplest form. Real rules also look at the resource's state, its owner, the time and other facts. Policies are the natural home for them.
interface Doc { ownerId: number; locked: boolean; sharedWith: number[] }
export function canEditDoc(userId: number, doc: Doc, now: Date): boolean {
if (doc.locked) return false;
if (doc.ownerId === userId) return true;
const hour = now.getUTCHours();
return doc.sharedWith.includes(userId) && hour >= 8 && hour < 18;
}
const doc: Doc = { ownerId: 1, locked: false, sharedWith: [2] };
console.log(canEditDoc(1, doc, new Date("2026-11-20T23:00:00Z")));
console.log(canEditDoc(2, doc, new Date("2026-11-20T10:00:00Z")));
console.log(canEditDoc(2, doc, new Date("2026-11-20T23:00:00Z")));
console.log(canEditDoc(2, { ...doc, locked: true }, new Date("2026-11-20T10:00:00Z")));true
true
false
falseThe time is a parameter, so tests can fix it. A policy that calls new Date() inside would give different answers at different moments and be hard to test. The same applies to any other external fact: pass it in.
Where policies go wrong
Checking in the interface only. Hiding a button is a convenience, not a control. Every action must be checked on the server, by the same policy.
Trusting client-supplied roles. The user object must come from a verified session or token, never from a field in the request body.
Forgetting a path. If one route reaches the same data through a different handler, it needs the same check. Where possible, enforce at a layer all routes share, such as a service function, and not in each controller.
Ownership checks missing. A request for /posts/10 by an authenticated user who is not the owner is the classic broken access control bug, listed first in the OWASP Top 10. A policy that checks the resource's owner prevents it, and a test for it should exist for every resource.
Testing
Policies are pure functions of a user, a resource and context, so they are easy to test exhaustively. A table keeps the matrix readable.
import assert from "node:assert/strict";
import { test } from "node:test";
import { PostPolicy, type Post, type User } from "./post-policy.ts";
const draft: Post = { id: 1, authorId: 1, status: "draft" };
const published: Post = { id: 2, authorId: 1, status: "published" };
const cases: Array<[string, User, "view" | "edit" | "delete", Post, boolean]> = [
["author edits own draft", { id: 1, role: "editor" }, "edit", draft, true],
["other editor edits draft", { id: 2, role: "editor" }, "edit", draft, false],
["viewer reads published", { id: 3, role: "viewer" }, "view", published, true],
["viewer reads draft", { id: 3, role: "viewer" }, "view", draft, false],
["editor deletes", { id: 1, role: "editor" }, "delete", published, false],
["admin deletes", { id: 9, role: "admin" }, "delete", published, true],
];
for (const [name, user, action, post, expected] of cases) {
test(name, () => {
assert.equal(new PostPolicy(user)[action](post), expected);
});
}✔ author edits own draft (0.9ms)
✔ other editor edits draft (0.1ms)
✔ viewer reads published (0.1ms)
✔ viewer reads draft (0.1ms)
✔ editor deletes (0.1ms)
✔ admin deletes (0.1ms)
ℹ tests 6
ℹ pass 6
ℹ fail 0The table reads like the requirements document, and a reviewer can check it against the product's rules. Always include the negative cases, since an authorization bug is usually a case that should have been denied and was not.
When not to use it
For an application with two roles and three screens, a role check in middleware may be enough. Policy objects pay off as soon as rules depend on the resource, as when an editor may edit only their own posts, or when the same rule is needed on the server and in the interface. If your rules become very dynamic, expressed by administrators in configuration, look at a dedicated authorization engine with a policy language, and keep policy objects as the code-level entry point.
Auditing and explaining decisions
A policy that returns only a boolean cannot tell a support engineer why a request was refused. For sensitive systems, return a decision object with the outcome and a reason, such as { allowed: false, reason: "post is locked" }, and log it. The reason is for your logs and not necessarily for the user: telling an attacker exactly which rule denied them can help them probe. Show a generic message to the client and keep the detail in the audit trail.
Logging every denial also gives you a signal. A user who triggers dozens of denied requests in a minute is either confused or probing, and an unusual spike in denials after a deploy points to a policy change that was too strict. Because every decision passes through one place, adding that log line is a one-line change.
Keeping policies in sync with the data layer
The weak spot of any policy system is the gap between the rule in code and the query that loads the data. A rule such as "editors see only their own drafts" must exist twice: once as a method that checks one post and once as a filter on the list query. Keep both in the same file, name them consistently, and write one test that loads a mixed set of posts through the filter and compares the result with the single-post method applied to each. If the two ever disagree, that test fails before a user notices a post that is listed but cannot be opened, or one that is hidden but can be fetched by id.


