Endpoint Plugin

Create a web standard endpoint for requesting authorization decisions, used with the Kilpi client.


The endpoint plugin is already included in @kilpi/core. Apply the plugin in your Kilpi configuration as follows. This plugin is intended to be used together with @kilpi/client.

kilpi.ts
import { createKilpi, EndpointPlugin } from "@kilpi/core";
export const Kilpi = createKilpi({
getSubject,
policies,
plugins: [
EndpointPlugin({
// Required
secret: process.env.KILPI_SECRET,
})
]
})

Usage

The endpoint plugin exposes the Kilpi.$createPostEndpoint() function which constructs a web-standard request-response handler function. You can integrate it with your framework of choice however you want. For example, with Next.js:

app/api/kilpi/route.ts
// (req: Request) => Promise<Response>
export const POST = Kilpi.$createPostEndpoint();

Optional configuration

You can provide additional configuration to EndpointPlugin to customize its behavior. See below examples.

EndpointPlugin({
secret: "...",
// Extract the `ctx` parameter from the request for `getSubject`
// if required.
getContext(req) {
return req;
},
// Before handling the request, run this hook. This hook may
// optionally throw or return an early response to terminate
// execution. Useful for e.g. rate-limiting.
async onBeforeHandleRequest(req) {
const allow = await rateLimit();
if (!allow) {
return Response.json({ error: "Too fast" }, { status: 429 });
}
},
// Before handling each item in the request, run this hook.
// Simply an "event-listener" type callback.
async onBeforeProcessItem(item) {
if (item.type === "fetchDecision") {
console.log(`Deciding ${item.action} on ${item.object}`);
}
},
});