Skip to content
keypal
Esc
↑↓navigate↵open⌘Jpreview
On this page

Custom storage

Verify keys in a table you already have, or write your own adapter

There are two ways to plug in your own storage:

  • A key lookup ({ findByHash, update? }) when you already have an API keys table and only need verify. Your code keeps creating and revoking keys.
  • A full Storage when you want keypal to manage keys (create, revoke, rotate, list) in a store keypal has no adapter for.

Verify keys in your own table

Pass an object with findByHash as storage. verify runs all of keypal’s checks against the rows it returns (key extraction, prefix and length, hashing, revoked, expired, disabled, usage tracking) and returns your row with its own type.

import { eq } from 'drizzle-orm'
import { createKeys } from 'keypal'
import { db } from './db'
import { apiKeys } from './db/schema'

const keys = createKeys({
  prefix: 'sk_',
  storage: {
    findByHash: async (keyHash: string) =>
      (await db.query.apiKeys.findFirst({ where: eq(apiKeys.keyHash, keyHash) })) ?? null,
    // Optional: lets keypal record when a key was last used
    update: async (id: string, { lastUsedAt }: { lastUsedAt: string }) => {
      await db.update(apiKeys).set({ lastUsedAt: new Date(lastUsedAt) }).where(eq(apiKeys.id, id))
    },
  },
})

const result = await keys.verify(request.headers)
if (result.valid && result.record) {
  result.record.organizationId // a column from your table
}

Rows need these fields. The rest of the row is passed through untouched.

Field Type Meaning
id string Passed to update
keyHash string The hash keys.hashKey(key) produced
enabled boolean | null, optional false fails with DISABLED
expiresAt Date | string | null, optional A past date fails with EXPIRED
revokedAt Date | string | null, optional Any value fails with REVOKED

The lookup methods:

Method Required What it does
findByHash(keyHash) Yes Returns the row with that hash, or null
update(id, { lastUsedAt }) No Receives usage writes, at most once per key per usageTrackingInterval (60 seconds by default). lastUsedAt is an ISO string. Without it, usage tracking is off.
findById(id) No Lets the key cache re-read a key by id. Without it, the cache is skipped. With a SQL table the cache saves nothing, so you rarely need this.

To issue a key, use the same manager so the hash matches what verify computes (same algorithm and salt):

const key = keys.generateKey() // show this to the user once
await db.insert(apiKeys).values({
  id: crypto.randomUUID(),
  keyHash: keys.hashKey(key),
  organizationId,
})

In this mode keypal doesn’t own your table: create, revoke, rotate, list, enable, disable and the audit log methods throw STORAGE_NOT_SUPPORTED. Scope checks such as keys.hasScope(record, 'read') work on your rows if they have scopes and resources.

Write a full storage adapter

A full adapter implements the Storage type from keypal. keypal treats any object with a save method as a full adapter.

import type {
  ApiKeyMutableFields,
  ApiKeyRecord,
  AuditLog,
  AuditLogQuery,
  AuditLogStats,
} from 'keypal'

type Storage = {
  save(record: ApiKeyRecord): Promise<void>
  findByHash(keyHash: string): Promise<ApiKeyRecord | null>
  findById(id: string): Promise<ApiKeyRecord | null>
  findByOwner(ownerId: string): Promise<ApiKeyRecord[]>
  findByTags(tags: string[], ownerId?: string): Promise<ApiKeyRecord[]>
  findByTag(tag: string, ownerId?: string): Promise<ApiKeyRecord[]>
  update(id: string, fields: Partial<ApiKeyMutableFields>): Promise<void>
  delete(id: string): Promise<void>
  deleteByOwner(ownerId: string): Promise<void>

  // Optional: audit logs
  saveLog?(log: AuditLog): Promise<void>
  findLogs?(query: AuditLogQuery): Promise<AuditLog[]>
  countLogs?(query: AuditLogQuery): Promise<number>
  deleteLogs?(query: AuditLogQuery): Promise<number>
  getLogStats?(ownerId: string): Promise<AuditLogStats>
}

Then pass an instance as storage:

import { createKeys, type Storage } from 'keypal'

class MyStore implements Storage {
  // ...
}

const keys = createKeys({ prefix: 'sk_', storage: new MyStore() })

What each method must do

The built-in stores all follow these rules, and keypal relies on them.

  • save stores a new record. Reject a duplicate id or keyHash.
  • findByHash, findById return null when nothing matches.
  • findByTags returns keys with any of the tags. Tags are case-insensitive: store them lowercase and lowercase the query. When ownerId is given, return only that owner’s keys. findByTag is the one-tag case.
  • update writes only the fields it is given and throws if the key doesn’t exist. A field present with the value undefined is cleared. The write must not overwrite changes to other fields made at the same moment: keypal writes lastUsedAt in the background, and a read-then-write of the whole record could undo a revoke that landed in between. Use a single partial update, a compare-and-set, or a transaction.
  • delete does nothing if the key doesn’t exist.
  • deleteByOwner deletes every key of that owner.

ApiKeyRecord has id, keyHash and ownerId, plus the optional name, description, scopes, resources, tags, enabled, expiresAt, revokedAt, lastUsedAt, createdAt and rotatedTo. ApiKeyMutableFields is every field except id and keyHash.

Audit log methods

The audit log methods are optional. With auditLogs: true, keypal calls saveLog on every create, revoke, rotate, enable and disable if your store has it, and skips logging if it doesn’t. The query methods (getLogs, countLogs, deleteLogs, getLogStats on the manager) throw STORAGE_NOT_SUPPORTED when the matching store method is missing.

  • findLogs returns entries newest first, applying limit (default 100) and offset. Filters combine with AND. An empty-string keyId or ownerId is a real filter, not “any”.
  • countLogs counts the same matches without paging.
  • deleteLogs deletes matches and returns how many. A query with no filters must delete nothing and return 0.
  • getLogStats returns { total, byAction, lastActivity } for one owner.

startDate and endDate are inclusive ISO timestamps.

Was this page helpful?