Examples (JavaScript)
Every example below builds on the same Actions/Subjects from the
Quick start:
const Actions = {
create: createAction("create"),
read: createAction("read"),
update: createAction("update"),
delete: createAction("delete"),
} as const;
const Subjects = {
article: createSubject<{ id: number; ownerId: number }>("article"),
comment: createSubject<{ userId: number; articleId: number }>("comment"),
} as const;
...and shares one KeycardConfig, built once from that vocabulary and handed to
both PolicyBuilder and Policy instead of kept in sync by hand — see
KeycardConfig further down:
const config: KeycardConfig = {
actions: Actions,
subjects: Subjects,
};
Schema-only check
No conditions needed — this checks whether the action/subject pair is allowed at all, ignoring any specific instance:
policy.can(Actions.create, Subjects.article);
Condition-based check
const article = Subjects.article.wrap({id: 1, ownerId: userId});
policy.can(Actions.update, article);
Multiple conditions
new PolicyBuilder(config)
.allow(Actions.update, Subjects.article, {
$and: [
{ownerId: userId},
{id: {$ne: 1}},
],
})
.buildDef();
Allow, deny, and last-match-wins
rules is a single, order-significant list — the last rule that matches an
action/subject/condition wins, so a later .deny() can carve an exception out
of an earlier .allow() (or vice versa). This example is self-contained: with
no dynamic (no-name) Actions/Subjects in play, PolicyBuilder doesn't need a
KeycardConfig at all.
import { createAction, createSubject, PolicyBuilder } from "@cptn-fizzbin/keycard";
const Actions = {
create: createAction("create"),
update: createAction("update"),
delete: createAction("delete"),
} as const;
const Subjects = {
article: createSubject<{ id: number; ownerId: number; status: string }>("article"),
} as const;
function policyForUser(user: { id: number }) {
return new PolicyBuilder()
.allow(Actions.create, Subjects.article)
.allow(Actions.update, Subjects.article, { ownerId: user.id })
.allow(Actions.delete, Subjects.article, { ownerId: user.id })
.deny(Actions.delete, Subjects.article, { status: "published" }) // last match wins: locked once live
.build();
}
const policy = policyForUser({ id: 42 });
const draft = Subjects.article.wrap({ id: 7, ownerId: 42, status: "draft" });
const published = Subjects.article.wrap({ id: 8, ownerId: 42, status: "published" });
policy.can(Actions.create, Subjects.article); // true - no conditions to satisfy
policy.can(Actions.delete, draft); // true - owns it, still a draft
policy.can(Actions.delete, published); // false - deny rule matches last
policy.require(Actions.delete, published);
// throws PolicyError: "delete" is not allowed on this "article"
Field mappers for renamed or computed fields
A SubjectFieldMapper resolves a condition field through an explicit getter
instead of property access — handy when a policy-facing field name doesn't match
the instance's own shape, like flattening a nested
instance.author.name into a single top-level authorName field (recall
conditions can only narrow one field deep — see
Condition Operators):
interface Post {
status: string;
author: { name: string }
}
const read = createAction("Read");
const post = createSubject<Post>("Post", {
authorName: (instance) => instance.author.name,
});
const config: KeycardConfig = {actions: {Read: read}, subjects: {Post: post}};
const policy = new Policy(
{version: "1.0", rules: [["allow", "Read", "Post", {authorName: "Alice"}]]},
config,
);
policy.can(read, post.wrap({status: "draft", author: {name: "Alice"}})); // true
A field the mapper doesn't define still falls back to ordinary property access,
and a mapped field's own value can still use any non-field operator ($substr,
$in, ...) — only narrowing is restricted to one level, not operator use.
KeycardConfig
Bundle actions/subjects/operators/field mappers into one object shared by
PolicyBuilder and Policy, instead of keeping each in sync by hand:
const post = createSubject<Post>("Post");
const read = createAction("Read");
const mappers = new SubjectFieldMapperCatalog({
Post: {authorName: (instance: Post) => instance.author.name},
});
const config = {subjects: {Post: post}, mapper: mappers};
// config.subjects widens the meta.subjects catalog, so "Post" is accepted
// here even though this raw definition declares no meta.subjects of its
// own (see Policy Definition's `meta` section for catalog enforcement):
const policy = new Policy(
{version: "1.0", rules: [["allow", "Read", "Post", {authorName: "Alice"}]]},
config,
);
PolicyBuilder.allow()'s conditions parameter is typed against the subject's
real fields (Condition<Post> here) — a field that only exists through a
SubjectFieldMapper, like authorName above, has no static type, so a
mapped-only field can't be referenced through .allow()'s typed API. Build that
rule as a plain object instead, as shown above.
Custom error handling
try {
policy.require(Actions.delete, article);
} catch (err) {
console.warn("Access denied:", err.message);
sendError(403, "You do not have permission to delete this article");
}
Cross-language usage
PolicyDefinitions are plain JSON, so a policy built in one language can be
evaluated in another:
// Build & serialize in JavaScript
const json = JSON.stringify(policy.def());
// ...ship `json` to a Java service, a Rust service, a browser, etc.
// It can be loaded with any conformant KeyCard implementation.
See examples/basic.ts in the
impl/js
package for a complete working example.
See A Real Backend for a larger, more realistic
walkthrough of this same API across a whole app's policy/ module.