DEV Community

Kat Laszlo
Kat Laszlo

Posted on

A small open-source library for scoped, budgeted, time-bounded API keys

When I led self-serve at a usage-based data company, one of the most common feature requests was credit limits per API Key. People wanted to hand a key to a script, a teammate, or now an AI agent, and know it couldn't run up the whole bill. We get the same request at my current startup, Tanso.

Account-level and user-level limits exist — That's what enterprise quota systems are for. But they're heavy. For a startup there wasn't a simple drop-in. So I wrote one.

agentkey does four things:

  • Cap what a key can spend: A budget per key, per day or month
  • Scope what it can do: Least privilege per key
  • Set when it expires: Short-lived by default if you want
  • Record which human authorized it: Delegation you can audit

The gap

AI agents made this urgent. An agent spends on its own — a loop or a bad prompt can burn a month's budget before anyone looks at a dashboard. And here's the part most tools miss: scoped keys tell you what an agent can do, not how much it can spend. LLM gateways cap spend. Identity platforms scope keys. Neither does both at the key level. agentkey does.

How it works

It's not a new auth system. It adds a few columns to your existing Postgres keys table and gives you a small API.

npm install @katrinalaszlo/agentkey
Enter fullscreen mode Exit fullscreen mode

Create a key that's scoped, budgeted, and expiring:

import { AgentKey } from '@katrinalaszlo/agentkey';

const ak = new AgentKey({ pool }); // your pg Pool

const key = await ak.create({
  accountId: 'acct_123',
  scopes: ['proxy.chat'],
  budgetCents: 5000,        // $50 cap
  budgetPeriod: 'month',
  expiresIn: '7d',
  delegatedBy: 'user_456',  // the human who authorized this agent
});
Enter fullscreen mode Exit fullscreen mode

Validate on each request, and track spend after a call:

const result = await ak.validate(key.key);
// { valid: true, scopes: ['proxy.chat'], budgetRemainingCents: 5000, ... }

await ak.trackUsage(key.key, { costCents: 15 }); // after an LLM call
Enter fullscreen mode Exit fullscreen mode

Budget enforcement is atomic, so concurrent agent calls can't race past the cap — which matters, because agents fire requests in parallel. There's also Express middleware if you want it:

app.post('/api/proxy', agentKeyMiddleware(ak, { scope: 'proxy.chat' }), handler);
Enter fullscreen mode Exit fullscreen mode

What it's not

It's small and focused, extracted from a real production key system, MIT-licensed. It isn't trying to be Clerk or Auth0. If you already have a keys table and you want per-key spend caps without building a quota system, it's a few columns and a function call.


npm: @katrinalaszlo/agentkey · GitHub: katrinalaszlo/agentkey

Top comments (0)