Key management
Create, find, revoke, rotate, enable and disable API keys
Every method on this page that takes a context accepts an ActionContext ({ userId?, ip?, userAgent?, metadata? }), which is written to the audit log when auditLogs is on.
ApiKeyRecord
type ApiKeyRecord = {
id: string
keyHash: string
ownerId: string
name?: string
description?: string
scopes?: string[]
resources?: Record<string, string[]> // "type:id" → scopes
expiresAt?: Date | string | null
createdAt?: string // ISO timestamp
lastUsedAt?: string
enabled?: boolean
revokedAt?: Date | string | null
rotatedTo?: string | null // id of the key that replaced it
tags?: string[]
}
Fields are top-level on the record (record.scopes, record.ownerId). ApiKeyMutableFields is the record without id and keyHash. ApiKeyMetadata is a deprecated alias of ApiKeyMutableFields.
create()
create(
input: Partial<ApiKeyMutableFields>,
context?: ActionContext
): Promise<{ key: string; record: ApiKeyRecord }>
Generates a key, saves its hash, and returns the plain key once. Only the hash is stored, so the key can’t be shown again.
Reads ownerId (default ""), name, description, scopes, resources, expiresAt (default null), enabled (default true) and tags (stored lowercase). createdAt is set to now; lastUsedAt, revokedAt and rotatedTo from input are ignored.
const { key, record } = await keys.create({
ownerId: 'user_123',
name: 'CI deploys',
scopes: ['deploy'],
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
})
Finding keys
findById(id: string): Promise<ApiKeyRecord | null>
findByHash(keyHash: string): Promise<ApiKeyRecord | null>
list(ownerId: string): Promise<ApiKeyRecord[]>
findByTag(tag: string, ownerId?: string): Promise<ApiKeyRecord[]>
findByTags(tags: string[], ownerId?: string): Promise<ApiKeyRecord[]>
listreturns every key of an owner, including revoked and disabled ones.findByTagandfindByTagsmatch case-insensitively.findByTagsreturns keys that have any of the tags. PassownerIdto limit results to one owner.findByHashtakes a hash, not a key; get it withhashKey().
None of these check whether a key is revoked, expired or disabled. Use verify() for that.
revoke()
revoke(id: string, context?: ActionContext): Promise<void>
Sets revokedAt, so verify returns REVOKED. The record is kept; with storage: "redis" it expires after revokedKeyTtl seconds (default 7 days), after which verify returns INVALID_KEY. Revoking can’t be undone.
Throws: KEY_NOT_FOUND, ALREADY_REVOKED.
revokeAll()
revokeAll(ownerId: string, context?: ActionContext): Promise<void>
Revokes every key of the owner that isn’t revoked yet. Keys already revoked are skipped, so it doesn’t throw ALREADY_REVOKED.
enable() and disable()
enable(id: string, context?: ActionContext): Promise<void>
disable(id: string, context?: ActionContext): Promise<void>
Set enabled. A disabled key fails verify with DISABLED until enabled again. A key whose enabled is unset counts as enabled.
Throws: KEY_NOT_FOUND, CANNOT_MODIFY_REVOKED, ALREADY_ENABLED (enable), ALREADY_DISABLED (disable).
rotate()
rotate(
id: string,
input?: Partial<ApiKeyMutableFields>,
context?: ActionContext
): Promise<{ key: string; record: ApiKeyRecord; oldRecord: ApiKeyRecord }>
Creates a new key and revokes the old one, setting its rotatedTo to the new key’s id. The old key stops working at once.
The new key copies the old key’s name, description, scopes, resources, expiresAt, tags and enabled. Fields in input replace them; expiresAt: null removes the expiry. ownerId always stays the old key’s. oldRecord is the old key as it was before rotation.
An expired key can be rotated, but its past expiresAt is copied too, so pass a new expiresAt.
const { key, record } = await keys.rotate('key_123', {
expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
})
Throws: KEY_NOT_FOUND, CANNOT_MODIFY_REVOKED.
With audit logging on, rotation writes a created entry for the new key and a rotated entry for the old one with metadata.rotatedTo.
updateLastUsed()
updateLastUsed(id: string): Promise<void>
Sets lastUsedAt to now. verify already does this in the background (see Verification), so call it only when you skip tracking or turn autoTrackUsage off. It doesn’t check that the key exists.
Throws: STORAGE_NOT_SUPPORTED when the storage has no update.
Errors
Methods throw an ApiKeyError object ({ code, message, details? }), not an Error instance. Check error.code; see Error handling.