Plugins
Usage Limits per Key
Enforce and decrement per-key usage counters. Provide helpers to manage remaining uses.
How it works
- Each key can carry
usesRemaining
(number or null). When> 0
, successful verifies decrement it by 1. When<= 0
, verification rejects with"usage_exceeded"
. - If
usesRemaining
isnull
, the key is not usage-limited by this plugin.
Settings
This plugin has no configuration options.
Option | Type | Default | Description |
---|---|---|---|
(none) | — | — | No options are required. |
Usage
import { usefulkey } from "betterkey";
import { usageLimitsPerKeyPlugin } from "usefulkey/plugins/usage-limits-per-key";
const uk = usefulkey({}, { plugins: [usageLimitsPerKeyPlugin()] });
// Create with a usage budget
const { result } = await uk.createKey({ userId: "u1", usesRemaining: 100 });
// Each successful verify decrements by 1
await uk.verifyKey({ key: result!.key });
// Management helpers
await uk.setUsesRemaining(result!.id, 50);
await uk.topUpUses(result!.id, 25);
const remaining = await uk.getUsesRemaining(result!.id);
await uk.clearUsageLimit(result!.id);
Functions added
uk.setUsesRemaining(id: string, remaining: number | null): Promise<void>
uk.topUpUses(id: string, amount: number): Promise<number | null>
uk.getUsesRemaining(id: string): Promise<number | null>
uk.clearUsageLimit(id: string): Promise<void>
Verification behavior
usesRemaining <= 0
→{ valid: false, reason: "usage_exceeded" }
- On success and when limited, decrements and persists the new value
Emitted analytics:
- On block:
"usage.blocked"
with{ keyId, userId, remaining: 0, ts }
. - On decrement:
"usage.decremented"
with{ keyId, userId, remaining, ts }
. - On set:
"usage.set"
with{ keyId, userId, remaining, ts }
. - On top-up:
"usage.topped_up"
with{ keyId, userId, added, remaining, ts }
. - On clear:
"usage.cleared"
with{ keyId, userId, ts }
.