Quickstart
Get started quickly with Kilpi using this guide.
-
Install Kilpi
Terminal window npm install @kilpi/coreTerminal window yarn add @kilpi/coreTerminal window pnpm add @kilpi/coreTerminal window bun add @kilpi/core -
Create a
kilpi
directoryIn your
src
folder (or equivalent), create akilpi
directory with the following file structure.Directorysrc
Directorykilpi
- policies.ts // Define your policies here
- subject.ts // Define your subject here
- kilpi.ts // Create and export your Kilpi instance here
This is only a suggestion.
See project structure for more information on the recommended project structure.
-
Create your subject
Create
subject.ts
and create aSubject
type and agetSubject
function to wrap your authentication provider.This function will automatically be called (and cached) by Kilpi while authorizing.
src/kilpi/subject.ts export type Subject = { id: string, email: string, name: string };export async function getSubject(): Promise<Subject | null> {const session = await getSession(); // From your auth providerif (!session) return null;return { id: session.id, email: session.email, name: session.name };} -
Create your policies
Create
policies.ts
where you define all policies. This will be the main place to define your authorization logic.For improved typesafety, add
as const satisfies Policyset<YourSubjectType>
. It type-checks your return types and automatically infers theuser
type.src/kilpi/policies.ts import { type Policyset, deny, grant } from "@kilpi/core";import type { Subject } from "./subject";const policies = {documents: {// Create a policy that does not take in a resource:// All authed users can create documentscreate(user) {if (!user) return deny("Unauthenticated");return grant(user);}// Create a policy that takes in a resource:// All authed users can read documents they own or public documentsread(user, document: Document) {if (!user) return deny("Unauthenticated");if (document.isPublic) return grant(user);if (user.id === document.ownerId) return grant(user);return deny();},},} as const satisfies Policyset<Subject | null> -
Create your Kilpi instance
Create
kilpi.ts
where you create your Kilpi instance from your subject and policies. TheKilpi
object will be used primarily for authorization.src/kilpi/kilpi.ts import { createKilpi } from "@kilpi/core";import { getSubject } from "./subject";import { policies } from "./policies";export const Kilpi = createKilpi({ getSubject, policies });Also list any plugins, default behaviours and other configuration here.
-
Protect your first function
Create a function that you want to protect with Kilpi, using for example the
Kilpi.authorize
method.myFunction.ts export async function myFunction() {await Kilpi.authorize("documents:create");// Your logic here ...}
Next steps
- Follow the installation guide for your framework of choice.
- Read up on Kilpi concepts and guides.
- Start using Kilpi on the client.