kyun
v0.0.6
Published
A little bit faster and type-safe permission rules for TS/JS.
Maintainers
Readme
Kyun
⚠️ Development Stage: This project is in active development and may have breaking changes in patch versions.
A blazingly fast, type-safe permission authorization library for TypeScript/JavaScript. Kyun is 10x faster than CASL and 400x faster than Casbin while providing compile-time type safety.
Overview
Kyun provides a declarative, type-safe way to define and evaluate authorization rules. It compiles rules into optimized decision trees for near-constant evaluation time, regardless of rule complexity. Perfect for applications requiring fine-grained access control with minimal performance overhead.
Key Features:
- 🚀 Ultra-fast: ~10x faster than CASL, ~400x faster than Casbin
- 🔒 Type-safe: Full TypeScript support with compile-time checks
- 📦 Lightweight: Zero runtime dependencies for core library
- 🔄 Server/Client sync: Pack rules on server, evaluate instantly on client
- ⚛️ React integration: Built-in hooks and components
- 🔐 Better Auth plugin: Seamless integration with Better Auth
Tech Stack
- Language: TypeScript (ES2022 target)
- Build Tool: tsup (ESM output)
- Testing: Vitest (unit tests) + Playwright (E2E tests)
- Linting/Formatting: Biome
- Package Manager: pnpm 10.27.0
- Node Version: 22 (see
.nvmrc)
Project Structure
src/
├── core/ # Core authorization engine
│ ├── ast.ts # Abstract syntax tree for rule compilation
│ ├── client.ts # Client-side rule evaluation
│ ├── kyun.ts # Main Kyun class and rule builder
│ ├── types.ts # TypeScript type definitions
│ └── index.ts # Public API exports
├── react/ # React hooks and components
└── better-auth/ # Better Auth integration plugin
├── index.ts # Server-side plugin
└── client.ts # Client-side plugin
examples/ # Real-world usage examples
├── ecommerce.ts # E-commerce authorization patterns
├── saas-multitenant.ts # Multi-tenant SaaS patterns
└── social-media.ts # Social media authorization patterns
bench/ # Performance benchmarks
├── compare_implementations.ts # Compare Kyun vs CASL vs Casbin
├── scenarios/ # Real-world benchmark scenarios
├── scaling/ # Rule scaling benchmarks
├── stress/ # Stress tests (10k resources, 50k rules)
└── memory/ # Memory profiling
tests/ # Test suite
├── core.test.ts # Core functionality tests (95%+ coverage)
├── error-messages.test.ts # Error handling tests
├── dynamic-messages.test.ts # Dynamic message tests
└── e2e/ # End-to-end tests with Next.jsGetting Started
Prerequisites
- Node.js: v22 or higher (specified in
.nvmrc) - Package Manager: pnpm 10.27.0 (or npm/yarn)
Installation
pnpm add kyun
# or
npm install kyun
# or
yarn add kyunBasic Usage
import { kyun } from 'kyun';
type User = { id: string; role: 'admin' | 'user' };
type Post = { id: string; ownerId: string; status: 'draft' | 'published' };
// Define authentication context
const k = kyun.$for<User>();
// Define authorization rules
const postRules = k.define<Post>(({ c, u, s }) => {
// Admins can do anything
c.allow('read').if(c.eq(u.role, 'admin'));
// Users can read published posts or their own drafts
c.allow('read').if(
c.or(
c.eq(s.status, 'published'),
c.eq(s.ownerId, u.id)
)
);
// Only owners can edit
c.allow('update').if(c.eq(s.ownerId, u.id));
});
const rules = { posts: postRules };
const instance = k.use(rules);
// Authorize actions
const user = { id: 'user-1', role: 'user' };
const post = { id: 'post-1', ownerId: 'user-1', status: 'draft' };
const can = instance.for(user);
if (can.posts.read(post)) {
console.log('User can read this post');
}
if (can.posts.update(post)) {
console.log('User can update this post');
}Server/Client Sync
Server-side (pack rules):
type Rules = typeof rules;
const packed = instance.pack(user);
// Transfer `packed` to client via props or global stateClient-side (instant evaluation):
import { kyunClient } from 'kyun';
const can = kyunClient<Rules>({ rules: packed });
if (can.posts.read(post)) {
// Works instantly on the client!
}Better Auth Integration
Server-side:
import { betterAuth } from 'better-auth';
import { kyunPlugin } from 'kyun/better-auth';
const auth = betterAuth({
plugins: [
kyunPlugin(rules),
]
});Client-side:
import { createAuthClient } from 'better-auth/client';
import { kyunClientPlugin } from 'kyun/better-auth/client';
const client = createAuthClient({
plugins: [
kyunClientPlugin()
]
});
const packed = await client.kyun.getRules();
const can = kyunClient<Rules>({ rules: packed.rules });
if (can.posts.update(post)) {
console.log('User can update this post');
}Development
Available Scripts
# Development
pnpm dev # Watch mode with auto-rebuild
# Building
pnpm build # Build for production (ESM, minified)
# Testing
pnpm test # Run unit tests
pnpm coverage # Generate coverage report (95%+ target)
pnpm test:e2e # Run Playwright E2E tests
pnpm test-app:dev # Start Next.js test app
# Code Quality
pnpm typecheck # TypeScript type checking
pnpm lint # Lint code with Biome
pnpm lint:fix # Auto-fix lint issues
pnpm format # Check formatting
pnpm format:fix # Auto-format code
pnpm check # Lint + format + fixRunning Tests
# Unit tests with Vitest
pnpm test
# Coverage report
pnpm coverage
# E2E tests with Playwright
pnpm test:e2eRunning Benchmarks
Compare Kyun against CASL and Casbin:
# Overall comparison
npx tsx bench/compare_implementations.ts
# Stress test: 10,000 resources (30,000 checks)
npx tsx bench/stress/stress_10k_resources.ts
# Stress test: 50,000 rules
npx tsx bench/stress/stress_50k_rules.tsBenchmarks
Kyun is designed for speed. Here's how it compares to popular alternatives:
Batch Authorization (100 resources × 3 checks)
| Library | Latency | Throughput | |---------|---------|------------| | Kyun | 1.9μs | 527k ops/s | | CASL | 18.8μs | 54k ops/s | | Casbin | 748μs | 1.3k ops/s |
Kyun is ~10x faster than CASL, ~400x faster than Casbin.
Rule Scaling (500 rules)
| Library | Latency | |---------|---------| | Kyun | 72ns | | CASL | 107ns | | Casbin | 391μs |
Stress Test: 10,000 Resources (30,000 checks)
| Library | Total Time | |---------|------------| | Kyun | 1.2ms | | CASL | 3.1ms | | Casbin | ~7,500ms (estimated) |
Stress Test: 50,000 Rules
| Library | Build Time | Evaluation | |---------|------------|------------| | CASL | 71ms | 79ns | | Kyun | 296ms | 27ns | | Casbin | 41,000ms | 42ms |
Kyun maintains near-constant evaluation time regardless of rule count.
Examples
Check the examples/ directory for real-world patterns:
- ecommerce.ts: Product management, cart operations, order fulfillment
- saas-multitenant.ts: Workspace isolation, role-based access
- social-media.ts: Posts, comments, privacy controls
API Exports
Kyun provides multiple entry points:
kyun- Core authorization enginekyun/react- React hooks and componentskyun/better-auth- Server-side Better Auth pluginkyun/better-auth/client- Client-side Better Auth plugin
Contributing
This project uses:
- pnpm for package management
- Biome for linting and formatting
- Vitest for unit testing
- Playwright for E2E testing
Run pnpm check before committing to ensure code quality.
License
MIT
