kyun
v0.0.4
Published
A little bit faster and type-safe permission rules for TS/JS.
Maintainers
Readme
Kyun
This project is still in the development stage and may have breaking changes in the patch version.
Goal: A little bit faster and type-safe permission rules for TS/JS.
Installation
pnpm add kyunQuick Start
import { kyun } from 'kyun';
type User = { id: string; role: 'admin' | 'user' };
type Post = { id: string; ownerId: string; status: 'draft' | 'published' };
// Authentication Context
const k = kyun.$for<User>();
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);
const user = { id: 'user-1', role: 'user' };
const post = { id: 'post-1', ownerId: 'user-1', status: 'draft' };
// authorize
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 side
type Rules = typeof rules;
const packed = instance.pack(user);
// Transfer `packed` to the client via props or global state
// Client side
import { kyunClient } from 'kyun';
const can = kyunClient<Rules>({ rules: packed });
if (can.posts.read(post)) {
// Works instantly on the client!
}Get rules from Better Auth
import { kyunPlugin } from 'kyun/better-auth';
const auth = betterAuth({
plugins: [
kyunPlugin({
rules,
}),
]
});
// client
const client = createAuthClient({
plugins: [
kyunClientPlugin()
]
});
const packed = await client.kyun.getRules(); //
const can = kyunClient<Rules>({ rules: packed.rules });
if (can.posts.update(todo)) {
console.log('User can update this todo');
}License
MIT
