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

> Source: <https://dev.to/kat_laszlo/a-small-open-source-library-for-scoped-budgeted-time-bounded-api-keys-1nb1>
> Published: 2026-06-18 19:09:52+00:00

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:

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.

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
```

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

``` js
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
});
```

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

``` js
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
```

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);
```

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](https://www.npmjs.com/package/@katrinalaszlo/agentkey) · GitHub: [katrinalaszlo/agentkey](https://github.com/katrinalaszlo/agentkey)
