# keypal > API key authentication for TypeScript. Issue keys, verify them on every request, scope and revoke them, storing only key hashes in the database you run. # keypal documentation Source: https://keypal.dev/docs keypal issues API keys, stores only their hashes, and checks incoming requests against them. It reads the key from the request headers, rejects keys that are unknown, revoked, expired, or disabled, and gives you the stored record so you can check its scopes. Keys can live in memory, Redis, or a SQL database through Drizzle, Kysely, or Prisma. If you already have an API keys table, keypal can verify against it without moving your data. ```ts import { createKeys } from 'keypal' const keys = createKeys({ prefix: 'sk_' }) // Issue a key. `key` is the secret: show it to the user once, then discard it. const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['read'], }) // Check a request. export async function handler(request: Request) { const result = await keys.verify(request.headers) if (!result.record) { return Response.json({ error: result.errorCode }, { status: 401 }) } if (!keys.hasScope(result.record, 'read')) { return Response.json({ error: 'forbidden' }, { status: 403 }) } return Response.json({ owner: result.record.ownerId }) } ``` ## Get started **[Installation](/docs/getting-started/installation)** Add keypal and the client for your storage. **[Quick start](/docs/getting-started/quick-start)** Create a key and verify your first request. **[Configuration](/docs/getting-started/configuration)** Every option `createKeys` takes. ## Go deeper **[Concepts](/docs/concepts/api-keys)** How verification works, and what scopes, expiry, tags, caching, and audit logs do. **[Storage](/docs/storage/overview)** Memory, Redis, Drizzle, Kysely, Prisma, or your own. **[API reference](/docs/api-reference/create-keys)** Every manager method and what it returns. **[Utilities](/docs/utilities/standalone-functions)** Hashing, scope checks, and errors without a manager. --- # Audit logs Source: https://keypal.dev/docs/api-reference/audit-logs These methods need `auditLogs: true` and a storage with audit-log methods. Memory and Redis storage have them; the Drizzle and Kysely adapters have them when given `auditLogTable`, and Prisma when given `auditLogModel`. For setup, see [Audit logging](/docs/concepts/audit-logging). **Every method throws**: - `AUDIT_LOGGING_DISABLED` when `auditLogs` is not `true`. - `STORAGE_NOT_SUPPORTED` when the storage lacks the method (for example a `KeyLookup`, or an adapter without an audit log table). ## AuditLog ```typescript type AuditLog = { id: string action: 'created' | 'revoked' | 'rotated' | 'enabled' | 'disabled' keyId: string ownerId: string timestamp: string // ISO timestamp data?: Record // the merged ActionContext } ``` `data` holds `auditContext` merged with the context passed to the method, with their `metadata` objects merged. A `created` entry's metadata also includes the key's `name` and `scopes`; a `rotated` entry's includes `rotatedTo`. A failed log write is logged to the console and doesn't fail the action. ## AuditLogQuery | Prop | Type | Default | Description | | - | - | - | - | | `keyId?` | `string` | - | Only entries for this key. | | `ownerId?` | `string` | - | Only entries for this owner. | | `action?` | `AuditAction` | - | Only entries with this action. | | `startDate?` | `string` | - | ISO date or timestamp; entries at or after it. | | `endDate?` | `string` | - | ISO date or timestamp; entries at or before it. | | `limit?` | `number` | `100` | Maximum entries returned by getLogs. | | `offset?` | `number` | `0` | Entries to skip, for paging getLogs. | Filters combine with AND. `limit` and `offset` apply only to `getLogs`. ## getLogs() ```typescript getLogs(query?: AuditLogQuery): Promise ``` Returns matching entries, newest first. ```typescript const page = await keys.getLogs({ ownerId: 'user_123', limit: 20, offset: 20 }) ``` ## countLogs() ```typescript countLogs(query?: AuditLogQuery): Promise ``` Counts all matching entries, ignoring `limit` and `offset`. ## deleteLogs() ```typescript deleteLogs(query: AuditLogQuery): Promise ``` Deletes matching entries and returns how many were deleted. :::warning A query with no `keyId`, `ownerId`, `action`, `startDate` or `endDate` deletes nothing and returns `0`, so a missing filter can't wipe the log. ::: ```typescript const deleted = await keys.deleteLogs({ endDate: '2025-01-01' }) ``` ## clearLogs() ```typescript clearLogs(keyId: string): Promise ``` Same as `deleteLogs({ keyId })`. ## getLogStats() ```typescript getLogStats(ownerId: string): Promise ``` ```typescript type AuditLogStats = { total: number byAction: Partial> // actions with no entries are absent lastActivity: string | null // newest entry's timestamp } ``` --- # createKeys() Source: https://keypal.dev/docs/api-reference/create-keys ## Signature ```typescript function createKeys(config?: ConfigInput): ApiKeyManager // Verify against your own table; verify returns your row type function createKeys( config: Omit, "storage"> & { storage: KeyLookup } ): ApiKeyManager ``` Returns an `ApiKeyManager`. `TKey` is `ApiKeyRecord` unless `storage` is a `KeyLookup` that returns your own rows. The `ApiKeyManager` type is exported for annotations; create instances with `createKeys`. ## Options All options are optional. | Prop | Type | Default | Description | | - | - | - | - | | `prefix?` | `string` | - | Prepended to every generated key, e.g. "sk_live_". When set, verify rejects keys that don't start with it (INVALID_FORMAT), and header extraction prefers a header whose value starts with it. | | `length?` | `number` | `32` | Characters in the random part of the key, not counting the prefix. Must be a positive integer. | | `alphabet?` | `string` | `A-Z, a-z, 0-9` | Characters the random part is drawn from. Needs 2 to 256 characters with at least 2 distinct. | | `algorithm?` | `"sha256" \| "sha512"` | `"sha256"` | Hash used to store keys. | | `salt?` | `string` | - | Added to every key before hashing. Changing it invalidates every stored key. | | `storage?` | `"memory" \| "redis" \| Storage \| KeyLookup` | `"memory"` | Where keys live. "redis" needs an ioredis client in the redis option. A KeyLookup ({ findByHash, findById?, update? }) verifies keys kept in your own table; management methods then throw STORAGE_NOT_SUPPORTED. | | `cache?` | `boolean \| "redis" \| Cache` | `false` | Caches which key id a key hash belongs to. true is an in-memory cache, "redis" uses the redis client, or pass your own Cache. verify still re-reads the key by id, so it needs findById; a KeyLookup without it skips the cache. | | `cacheTtl?` | `number` | `60` | Cache entry lifetime in seconds. | | `headerNames?` | `string[]` | `["authorization", "x-api-key"]` | Headers checked, in order, when verify is given headers. | | `extractBearer?` | `boolean` | `true` | Strip a leading "Bearer " from header values. | | `redis?` | `RedisClient` | - | ioredis client. Required for storage: "redis" or cache: "redis". | | `revokedKeyTtl?` | `number` | `604800` | Seconds Redis keeps a revoked or rotated key's record (7 days). 0 keeps it forever. Applies only to storage: "redis". | | `autoTrackUsage?` | `boolean` | `true` | Write lastUsedAt in the background after a successful verify. Off when the storage has no update method. | | `usageTrackingInterval?` | `number` | `60` | Minimum seconds between lastUsedAt writes for the same key, per manager instance. 0 writes on every verify. | | `impliedScopes?` | `Record` | - | Scopes that grant other scopes in the manager's scope checks, applied transitively, e.g. { admin: ["read", "write"] }. | | `auditLogs?` | `boolean` | `false` | Record created, revoked, rotated, enabled and disabled actions. Needs a storage with audit-log methods. | | `auditContext?` | `ActionContext` | - | Default context merged into every audit log entry. Per-call context overrides it; metadata objects are merged. | For what each option does in practice, see [Configuration](/docs/getting-started/configuration). ## Throws `createKeys` throws synchronously when: - `length` is not a positive integer, or `alphabet` has fewer than 2 distinct characters or more than 256 characters, or contains emoji or other characters outside the Basic Multilingual Plane (`RangeError`). - `storage: "redis"` or `cache: "redis"` is set without `redis`. - `storage: "redis"` gets a client without `pipeline`, i.e. not an ioredis client. ## Examples ```typescript title="Redis storage" import Redis from 'ioredis' import { createKeys } from 'keypal' const keys = createKeys({ prefix: 'sk_live_', storage: 'redis', redis: new Redis(), }) ``` ```typescript title="Verify against your own table" import { createKeys } from 'keypal' // `db` is your Prisma Client; `request` is the incoming Request. const keys = createKeys({ prefix: 'sk_', storage: { findByHash: (keyHash) => db.apiKey.findUnique({ where: { keyHash } }), update: async (id, fields) => { await db.apiKey.update({ where: { id }, data: fields }) }, }, }) const result = await keys.verify(request.headers) // result.record has your table's row type ``` A `KeyLookup` row needs `id` and `keyHash`, and may have `enabled`, `expiresAt` and `revokedAt`; verify applies the same checks as with built-in storage. For full adapters, see [Storage](/docs/storage/overview) and [Custom storage](/docs/storage/custom-storage). --- # Key management Source: https://keypal.dev/docs/api-reference/key-management Every method on this page that takes a `context` accepts an `ActionContext` (`{ userId?, ip?, userAgent?, metadata? }`), which is written to the [audit log](/docs/api-reference/audit-logs) when `auditLogs` is on. :::note With a `KeyLookup` as `storage` (keys kept in your own table), every method on this page except `updateLastUsed` throws `STORAGE_NOT_SUPPORTED`. `updateLastUsed` works when the lookup has `update`. ::: ## ApiKeyRecord ```typescript type ApiKeyRecord = { id: string keyHash: string ownerId: string name?: string description?: string scopes?: string[] resources?: Record // "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() ```typescript create( input: Partial, 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. ```typescript 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 ```typescript findById(id: string): Promise findByHash(keyHash: string): Promise list(ownerId: string): Promise findByTag(tag: string, ownerId?: string): Promise findByTags(tags: string[], ownerId?: string): Promise ``` - `list` returns every key of an owner, including revoked and disabled ones. - `findByTag` and `findByTags` match case-insensitively. `findByTags` returns keys that have any of the tags. Pass `ownerId` to limit results to one owner. - `findByHash` takes a hash, not a key; get it with [`hashKey()`](/docs/api-reference/utilities). None of these check whether a key is revoked, expired or disabled. Use [`verify()`](/docs/api-reference/verification) for that. ## revoke() ```typescript revoke(id: string, context?: ActionContext): Promise ``` 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() ```typescript revokeAll(ownerId: string, context?: ActionContext): Promise ``` 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() ```typescript enable(id: string, context?: ActionContext): Promise disable(id: string, context?: ActionContext): Promise ``` 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() ```typescript rotate( id: string, input?: Partial, 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`. ```typescript 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() ```typescript updateLastUsed(id: string): Promise ``` Sets `lastUsedAt` to now. `verify` already does this in the background (see [Verification](/docs/api-reference/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](/docs/utilities/error-handling). --- # Permissions Source: https://keypal.dev/docs/api-reference/permissions These methods take a record (anything with `scopes` and `resources`, such as `result.record` from `verify`) and return a `boolean`. They don't check revocation, expiry or `enabled`; `verify` does that. A key holds its global `scopes`, plus, when a `resource` is checked, the scopes in `resources[resource]`, plus everything those imply through `impliedScopes`. ## ScopeCheckOptions | Prop | Type | Default | Description | | - | - | - | - | | `resource?` | `string` | - | Resource being accessed, as "type:id", e.g. "project:123". Its scopes from resources are added to the global scopes. | | `resources?` | `Record` | - | Scopes per resource. Defaults to the record's resources. | | `impliedScopes?` | `Record` | - | Scopes that grant other scopes, applied transitively. Defaults to the manager's impliedScopes. | ## hasScope(), hasAnyScope(), hasAllScopes() ```typescript hasScope(record: ScopedKey, scope: string, options?: ScopeCheckOptions): boolean hasAnyScope(record: ScopedKey, scopes: string[], options?: ScopeCheckOptions): boolean hasAllScopes(record: ScopedKey, scopes: string[], options?: ScopeCheckOptions): boolean ``` `ScopedKey` is `{ scopes?: string[]; resources?: Record }`. `hasAnyScope` with an empty list returns `false`; `hasAllScopes` with an empty list returns `true`. ```typescript const keys = createKeys({ impliedScopes: { admin: ['read', 'write'] }, }) keys.hasScope({ scopes: ['admin'] }, 'write') // true keys.hasAllScopes(record, ['read', 'write'], { resource: 'project:123' }) ``` ## checkResourceScope(), checkResourceAnyScope(), checkResourceAllScopes() ```typescript checkResourceScope(record: ScopedKey | null, resourceType: string, resourceId: string, scope: string): boolean checkResourceAnyScope(record: ScopedKey | null, resourceType: string, resourceId: string, scopes: string[]): boolean checkResourceAllScopes(record: ScopedKey | null, resourceType: string, resourceId: string, scopes: string[]): boolean ``` Shorthand for the checks above with `resource` set to `"resourceType:resourceId"`. Global scopes count too, so a key with global `read` passes `checkResourceScope(record, 'project', '123', 'read')`. A `null` record returns `false`, so you can pass `verifyFromHeaders`'s result directly. ```typescript const record = await keys.verifyFromHeaders(request.headers) if (!keys.checkResourceScope(record, 'project', params.id, 'deploy')) { return new Response('Forbidden', { status: 403 }) } ``` To build `resources` maps, see [ResourceBuilder](/docs/utilities/resource-builder). For the model behind them, see [Resource scopes](/docs/concepts/resource-scopes). ## isExpired() ```typescript isExpired(record: { expiresAt?: Date | string | null }): boolean ``` `true` when `expiresAt` is now or in the past, or is a non-empty value that can't be parsed. `false` when it is unset, `null`, or an empty string. ## Functions without a manager `hasScope`, `hasAnyScope` and `hasAllScopes` are also exported as functions that take a scope array instead of a record. See [Standalone functions](/docs/utilities/standalone-functions). --- # Utilities Source: https://keypal.dev/docs/api-reference/utilities These methods use the manager's configured `prefix`, `length`, `alphabet`, `algorithm`, `salt` and header settings. For the same helpers without a manager, see [Standalone functions](/docs/utilities/standalone-functions). ## extractKey() ```typescript extractKey( headers: Record | Headers, options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string } ): string | null ``` Returns the key from the request headers, or `null`. Options default to the manager's `headerNames`, `extractBearer` and `prefix`. - Headers are checked in `headerNames` order; names match case-insensitively. Values are trimmed and empty values skipped. - With `extractBearer`, `Bearer ` yields ``; a bare `Bearer` is skipped. A value starting with `prefix` is returned as is, even if the prefix starts with "bearer". - With a `prefix`, the first value that starts with it wins. If none does, the first non-empty value is returned, and verify then rejects it with `INVALID_FORMAT`. ```typescript // prefix: 'sk_' keys.extractKey({ authorization: 'Basic dXNlcjpwYXNz', 'x-api-key': 'sk_abc' }) // 'sk_abc' ``` ## hasKey() ```typescript hasKey( headers: Record | Headers, options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string } ): boolean ``` `true` when `extractKey` returns a key. It doesn't verify the key. ## generateKey() ```typescript generateKey(): string ``` Returns a new key (`prefix` + `length` random characters from `alphabet`) without saving it. Use [`create()`](/docs/api-reference/key-management) to issue a key. ## hashKey() ```typescript hashKey(key: string): string ``` Returns the hex hash that storage keeps for `key`, using the configured `algorithm` and `salt`. Use it to look a key up with `findByHash`, or to hash keys you import into a custom table. :::note The manager hashes the configured `salt` with SHA-256 before using it, so the standalone `hashKey(key, { salt })` gives a different hash. Use the manager's method when a salt is set. ::: ## validateKey() ```typescript validateKey(key: string, storedHash: string): boolean ``` Hashes `key` with the manager's settings and compares it to `storedHash` in constant time. It only compares hashes; it doesn't read storage or check revocation, expiry or `enabled`. ## invalidateCache() ```typescript invalidateCache(keyHash: string): Promise ``` Removes the cache entry for a key hash. Does nothing without a cache. Unlike the internal clears, a cache error is thrown. `revoke`, `rotate`, `enable`, `disable` and failed verifies already clear the entry, and verify re-reads the record on every call, so you need this only after changing a key's stored hash outside keypal. See [Caching](/docs/concepts/caching). ```typescript await keys.invalidateCache(keys.hashKey(oldKey)) ``` --- # Verification Source: https://keypal.dev/docs/api-reference/verification ## verify() ```typescript verify( keyOrHeader: string | Record | Headers, options?: VerifyOptions ): Promise> ``` Checks a key and returns the stored record when it may be used. `verify` never throws for a bad key; it returns `valid: false` with an `errorCode`. Errors from your storage are not caught. **Input** - A string is trimmed and a leading `Bearer ` is removed, unless the string starts with the configured `prefix` (so a prefix such as `bearer_` stays part of the key). - Headers are read with [`extractKey()`](/docs/api-reference/utilities): `headerNames` are checked in order, and when a `prefix` is configured the first value that starts with it wins, so an unrelated `Authorization` header doesn't hide a key in `x-api-key`. ### VerifyOptions | Prop | Type | Default | Description | | - | - | - | - | | `skipCache?` | `boolean` | `false` | Look the key up by hash without reading or writing the cache. | | `headerNames?` | `string[]` | - | Headers to check for this call. Defaults to the manager's headerNames. | | `extractBearer?` | `boolean` | - | Strip "Bearer " from header values for this call. Defaults to the manager's extractBearer. String input always has it stripped. | | `skipTracking?` | `boolean` | `false` | Don't write lastUsedAt for this call. | ### VerifyResult ```typescript type VerifyResult = { valid: boolean record?: TKey // set when valid error?: string // message, set when not valid errorCode?: ApiKeyErrorCode } ``` ### Checks and error codes Checks run in this order; the first failure is returned. | `errorCode` | When | | --- | --- | | `MISSING_KEY` | No key in the string or any checked header. | | `INVALID_FORMAT` | The key doesn't start with the configured `prefix`, or is longer than 512 characters (or than `prefix` + `length`, if that is longer). Rejected before hashing. | | `INVALID_KEY` | No stored key has this hash. | | `REVOKED` | `revokedAt` is set. Rotated keys are revoked. | | `EXPIRED` | `expiresAt` is now or in the past, or is a non-empty value that can't be parsed. | | `DISABLED` | `enabled` is `false`. | A key that is revoked, expired and disabled reports `REVOKED`; expired and disabled reports `EXPIRED`. From `INVALID_KEY` on, a failure also removes the key's cache entry. ### Usage tracking After a successful verify, `lastUsedAt` is written in the background unless `autoTrackUsage` is `false`, `skipTracking` is set, or the storage has no `update`. Each manager writes a given key at most once per `usageTrackingInterval` seconds (default 60), so `lastUsedAt` can lag by up to that long. A failed write is logged, never returned, and retried on a later verify after at most 5 seconds. ### Example ```typescript import { ApiKeyErrorCode } from 'keypal' const result = await keys.verify(request.headers) if (!result.valid) { // A disabled key is known but turned off; every other failure is bad credentials. const status = result.errorCode === ApiKeyErrorCode.DISABLED ? 403 : 401 return Response.json({ error: result.error }, { status }) } const ownerId = result.record?.ownerId ``` To map every code to a response, see [Error handling](/docs/utilities/error-handling). ## verifyFromHeaders() ```typescript verifyFromHeaders( headers: Record | Headers, options?: VerifyOptions ): Promise ``` Calls `verify(headers, options)` and returns the record when valid, or `null` for any failure. Use `verify` when you need the reason. ```typescript const record = await keys.verifyFromHeaders(request.headers) if (!record) { return new Response('Unauthorized', { status: 401 }) } ``` --- # v0.2.0 Source: https://keypal.dev/docs/changelog/v0-2-0 Flatten ApiKeyRecord, unify scope API, fix types, move convex to optionalDependencies --- # AI resources Source: https://keypal.dev/docs/community/ai keypal's documentation is published in forms coding agents read directly, so Claude Code, Cursor, Codex and similar tools can write keypal code against the current API instead of guessing. ## Paste a prompt Copy this into your agent to add API keys to an app: ```text Add API key authentication to this app with the keypal npm package. Read https://keypal.dev/llms-full.txt before writing code, store keys with the adapter that matches our database, and protect our API routes with keys.verify(req.headers): reject the request unless result.valid is true, and read the owner from result.record. ``` ## Files for agents | File | What it holds | | --- | --- | | [`/llms.txt`](https://keypal.dev/llms.txt) | An index of every docs page with a one-line summary | | [`/llms-full.txt`](https://keypal.dev/llms-full.txt) | Every docs page in one Markdown file | | [`/skill.md`](https://keypal.dev/skill.md) | An agent skill describing when and how to use keypal | | Any page + `.md` | That page as Markdown, for example [`/docs/getting-started/quick-start.md`](https://keypal.dev/docs/getting-started/quick-start.md) | Every docs page also has **Copy as Markdown** and **Open in chat** in its page actions. ## Keep agents on the current API keypal 0.2 flattened the key record: fields such as `ownerId`, `scopes` and `revokedAt` sit on the record itself, not under `record.metadata`. Agents trained on older examples sometimes write `record.metadata.ownerId`; pointing them at `llms-full.txt` avoids that. --- # Contributing Source: https://keypal.dev/docs/community/contributing keypal is MIT licensed and developed in the open on [GitHub](https://github.com/izadoesdev/keypal). Bug reports, fixes, docs edits, and new storage adapters are all welcome. ## Before you start - Search [open issues](https://github.com/izadoesdev/keypal/issues) first. If your change is large, open an issue to agree on the approach before writing it. - Don't report a security problem in a public issue. Contact the maintainer, [@izadoesdev](https://github.com/izadoesdev), privately first. ## Set up keypal uses [Bun](https://bun.sh) for installs and scripts and [Vitest](https://vitest.dev) for tests. ```bash git clone https://github.com/izadoesdev/keypal cd keypal bun install bunx lefthook install # once, enables the pre-commit hook # Everything that doesn't need a database bunx vitest run \ --exclude '**/redis.test.ts' \ --exclude '**/drizzle.test.ts' \ --exclude '**/kysely.test.ts' \ --exclude '**/prisma.test.ts' ``` `bun run test` starts Vitest in watch mode; `bunx vitest run` runs once and exits. That covers key generation, hashing, verification, scopes, the manager, and the memory store. ## Test against the databases The adapter tests run against real servers. `docker-compose.yml` starts one of each, on the ports the tests expect: ```bash docker compose up -d ``` | Service | Port | Test command | | --- | --- | --- | | Redis | 6379 | `bun run test:redis` | | Postgres for Kysely | 5433 | `bun run test:kysely` | | Postgres for Drizzle | 5434 | `bun run test:drizzle` | | Postgres for Prisma | 5435 | `bun run test:prisma`, after creating the schema once (below) | :::warning The Redis tests clear the database they connect to. Point them at the Compose container, or set `REDIS_HOST` and `REDIS_PORT` to a Redis that holds nothing you need. ::: The Prisma suite needs its schema pushed once. `prisma/schema.prisma` reads `DATABASE_URL`, so set it to the Compose database unless you already point it elsewhere: ```bash DATABASE_URL="${DATABASE_URL:-postgresql://keypal:keypal_dev@localhost:5435/keypal_prisma}" bunx prisma db push ``` Each Postgres suite also reads `DATABASE_URL` if you'd rather use your own server. ## Making a change - Keep key generation and hashing byte-for-byte compatible. `src/core/compat.test.ts` pins hashes from earlier releases; if it fails, existing users' keys would stop verifying. - Add a test that fails without your change. Storage changes belong in the shared contracts in `src/storage/store-contract.ts`, so every adapter is held to them. - Run `bun run typecheck` and `bunx ultracite check` before you push. The pre-commit hook formats staged files for you once you've run `bunx lefthook install`. - Update the docs in `apps/docs/docs` when behavior changes. Run them locally with `cd apps/docs && bun install && bun run dev`. ## Pull requests Write the PR description for someone who hasn't read the code: what changed, why, and how you tested it. CI runs the unit tests and every database suite on each push. ## Releases Releases are published to npm from GitHub Actions with provenance. Each GitHub release appears in the changelog at keypal.dev/changelog. --- # API keys Source: https://keypal.dev/docs/concepts/api-keys ## The key and its hash A key is your `prefix` followed by random characters: `sk_live_` and then 32 characters from A–Z, a–z and 0–9 by default. The random part comes from `nanoid`, which uses the platform's secure random generator. keypal never stores the key. `create` returns it once and saves its SHA-256 or SHA-512 hash, with your `salt` mixed in if you set one. When a request arrives, keypal hashes the key it was given and looks the hash up. Someone who reads your database gets hashes, not working keys. To compare a key with a hash you already hold, `keys.validateKey(key, hash)` uses a timing-safe comparison. ## What a stored key holds `create` and `verify` give you an `ApiKeyRecord`. All its fields are top-level: | Field | Set by | Meaning | | --- | --- | --- | | `id` | keypal | Unique id. Use it to revoke, rotate, enable, or disable the key. | | `keyHash` | keypal | Hash of the key. | | `ownerId` | you | The user or account the key belongs to. `''` if you leave it out. | | `name`, `description` | you | Labels for people. | | `scopes` | you | What the key may do. See [Scopes and permissions](/docs/concepts/scopes-and-permissions). | | `resources` | you | Scopes limited to one resource. See [Resource scopes](/docs/concepts/resource-scopes). | | `tags` | you | Labels for finding keys, stored lowercase. See [Tags](/docs/concepts/tags). | | `expiresAt` | you | When the key stops working, or `null`. See [Expiration](/docs/concepts/expiration). | | `enabled` | you, `enable`, `disable` | `false` turns the key off without revoking it. Defaults to `true`. | | `createdAt` | keypal | ISO timestamp. | | `lastUsedAt` | keypal | ISO timestamp of a recent successful verify, written at most once per `usageTrackingInterval` by each manager instance, so several servers can each write within one interval. | | `revokedAt` | `revoke`, `rotate` | When the key was revoked. | | `rotatedTo` | `rotate` | Id of the key that replaced this one. | ## What verify checks `keys.verify(input)` takes request headers or the key itself, and returns `{ valid, record?, error?, errorCode? }`. It stops at the first failed check: 1. **Find the key.** From headers, it reads `headerNames` in order and strips `Bearer `. From a string, it trims it and strips `Bearer `. Nothing found returns `MISSING_KEY`. 2. **Check the format.** A key without the configured `prefix`, or longer than 512 characters (or your prefix plus `length`, if that is longer), returns `INVALID_FORMAT` without reading storage. 3. **Look it up.** keypal hashes the key and finds the stored record by hash. No match returns `INVALID_KEY`. 4. **Check its status.** A revoked key returns `REVOKED`, an expired one `EXPIRED`, a disabled one `DISABLED`. When several apply, the earliest in that list wins. 5. **Accept it.** keypal records `lastUsedAt` in the background and returns `{ valid: true, record }`. `verify` checks that the key is genuine and usable, not what it may do. Check scopes yourself after it succeeds. The status rule in step 4 is exported as `getKeyStatus(record)`, which returns `'active'`, `'revoked'`, `'expired'`, or `'disabled'`. Use it when you load a key some other way and need the same answer `verify` would give. ## Lifecycle ```ts const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['read'] }) await keys.disable(record.id) // verify returns DISABLED await keys.enable(record.id) // works again const { key: newKey, record: newRecord } = await keys.rotate(record.id) // The old key is revoked now; newKey has the same scopes, tags, and expiry. await keys.revoke(newRecord.id) // verify returns REVOKED await keys.revokeAll('user_123') // revokes every remaining key the owner has ``` **Disable** when you may want the key back. **Revoke** when you don't: a revoked key cannot be enabled, rotated, or revoked again. These calls throw `ALREADY_REVOKED`, `CANNOT_MODIFY_REVOKED`, `ALREADY_ENABLED`, or `ALREADY_DISABLED` when the key is already in that state. **Rotate** issues a new key that copies the old one's settings, including being disabled. Fields you pass replace the copied ones, so `keys.rotate(id, { expiresAt: null })` clears an expiry. The old key is revoked in the same call, with `rotatedTo` pointing at the new one. There is no overlap period: the old key fails `verify` as soon as `rotate` returns. If clients need time to switch, `create` a replacement instead, hand it over, and `revoke` the old key once they have moved. Revocation is soft: the record stays in storage with `revokedAt` set, so you can still list it and see its audit history. With `storage: 'redis'`, Redis deletes revoked records after `revokedKeyTtl` (7 days by default). ## Changes apply at once Every `verify` reads the key's current record from storage, even with a cache. A key revoked or disabled on one server fails on every other server sharing that storage on its next request. Nothing has to expire first. Memory storage is per process, so this only holds across servers when they share Redis or a database. --- # Audit logging Source: https://keypal.dev/docs/concepts/audit-logging With audit logging on, keypal writes a log entry each time a key is created, revoked, rotated, enabled, or disabled. Use it to answer "who revoked this key, and why?" Verifications are not logged; `lastUsedAt` on the key covers usage. ## Turn it on ```ts import { createKeys } from 'keypal' const keys = createKeys({ auditLogs: true, auditContext: { userId: 'system', metadata: { service: 'api' } }, }) ``` `auditContext` is optional and is added to every entry. Logs are stored by your storage adapter: | Storage | Logs | | --- | --- | | Memory, Redis | Built in. | | Drizzle, Kysely | Pass `auditLogTable` to the store. | | Prisma | Pass `auditLogModel` to the store. | | Custom | Implement `saveLog`, `findLogs`, `countLogs`, `deleteLogs`, and `getLogStats`. | If the storage can't save logs, actions still succeed and nothing is logged. A log write that fails is reported with `console.error` and doesn't fail the action. ## Say who did it Every action method takes an optional context as its last argument: ```ts await keys.revoke(record.id, { userId: 'admin_456', ip: request.headers.get('x-forwarded-for') ?? undefined, userAgent: request.headers.get('user-agent') ?? undefined, metadata: { reason: 'Leaked in a public repository' }, }) ``` `create(input, context)`, `rotate(id, input, context)`, `revoke`, `revokeAll`, `enable`, and `disable` all accept it. Its fields override `auditContext`, and the two `metadata` objects are merged. For `rotate`, the context goes on the `rotated` entry only; the `created` entry for the new key gets `auditContext` but not the per-call context. ## What an entry holds ```ts { id: 'V1StGXR8_Z5jdHi6B-myT', action: 'revoked', // 'created' | 'revoked' | 'rotated' | 'enabled' | 'disabled' keyId: 'hT3x9VqL2mPn8RkW4yJcZ', ownerId: 'user_123', timestamp: '2026-03-01T12:00:00.000Z', data: { userId: 'admin_456', ip: '203.0.113.7', userAgent: 'curl/8.7.1', metadata: { service: 'api', reason: 'Leaked in a public repository' }, }, } ``` `data` is your merged context. keypal adds to `metadata` in two cases: `created` entries include the key's `name` and `scopes`, and `rotated` entries include `rotatedTo`, the new key's id. A rotation writes two entries: `created` for the new key and `rotated` for the old one. ## Query logs ```ts const history = await keys.getLogs({ keyId: record.id }) const recentRevocations = await keys.getLogs({ ownerId: 'user_123', action: 'revoked', startDate: '2026-01-01T00:00:00.000Z', limit: 20, offset: 0, }) const created = await keys.countLogs({ action: 'created' }) const stats = await keys.getLogStats('user_123') // { total, byAction: { created: 4, revoked: 1 }, lastActivity: '2026-...' } ``` Every filter is optional. `startDate` and `endDate` are ISO timestamps and include both ends. Results come newest first, 100 at a time unless you set `limit`. ## Delete logs ```ts await keys.deleteLogs({ endDate: '2025-01-01T00:00:00.000Z' }) // up to the start of 2025 await keys.clearLogs(record.id) // one key's history ``` Both return how many entries were deleted. `deleteLogs` needs at least one filter; an empty query deletes nothing and returns `0`. ## Errors `getLogs`, `countLogs`, `getLogStats`, `deleteLogs`, and `clearLogs` throw `AUDIT_LOGGING_DISABLED` when `auditLogs` is off, and `STORAGE_NOT_SUPPORTED` when the storage has no log support. --- # Caching Source: https://keypal.dev/docs/concepts/caching The cache remembers which key id a key hash belongs to. `verify` still reads the key by id on every call, so a key revoked or disabled on any server stops working at once, never after the cache expires. Because of that re-read, the cache only helps in one setup: the in-memory cache (`cache: true`) with Redis storage, where it saves the hash-index round trip. A Redis cache costs the same round trip it saves, and with a SQL database finding a key by hash costs the same as finding it by id, so in those setups leave it off. Caching is off by default. ## Turn it on ```ts import { createKeys } from 'keypal' import Redis from 'ioredis' const keys = createKeys({ storage: 'redis', redis: new Redis(), cache: true, // in-memory, per process cacheTtl: 60, // seconds, the default }) ``` `cache` also takes `'redis'` (stored in the `redis` client) or any object with `get`, `set`, and `del`. The cache needs a way to read keys by id. With a [lookup for your own table](/docs/getting-started/quick-start), add `findById` to it; without one, keypal skips the cache. ## How a verify uses it 1. **Valid key**: after a key verifies, its hash → id is cached. 2. **Cache hit**: the next verify reads the key by that id and checks it again: revoked, expired, disabled, and that the stored hash still matches. 3. **Cache miss or mismatch**: verify looks the key up by hash and caches the result. 4. **Failed check**: the entry is removed, so failures are never cached. 5. **TTL**: entries expire after `cacheTtl` seconds. `revoke`, `rotate`, `enable`, and `disable` also remove the key's entry, and an entry that can't be parsed is removed when read. To remove one yourself, call `keys.invalidateCache(keyHash)`. To bypass the cache for one call, pass `{ skipCache: true }` to `verify`. ## Size the in-memory cache `cache: true` holds up to 10,000 entries. When it is full, the entry added first is dropped, and expired entries are cleared every 60 seconds. To change either, pass your own `MemoryCache`: ```ts import { createKeys, MemoryCache } from 'keypal' import Redis from 'ioredis' const redis = new Redis() const cache = new MemoryCache({ maxSize: 50_000, // entries cleanupInterval: 30_000, // milliseconds }) const keys = createKeys({ storage: 'redis', redis, cache }) // On shutdown, stop the cleanup timer. process.on('SIGTERM', () => cache.dispose()) ``` The cleanup timer doesn't keep Node.js running on its own, so `dispose()` matters mostly in tests and hot-reloading servers that create many caches. --- # Expiration Source: https://keypal.dev/docs/concepts/expiration A key with `expiresAt` stops verifying once that time passes. Keys without it never expire; there is no default lifetime. ## Set an expiry `expiresAt` takes a `Date` or an ISO 8601 string. To expire a key 90 days from now: ```ts const DAY_MS = 24 * 60 * 60 * 1000 const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['read'], expiresAt: new Date(Date.now() + 90 * DAY_MS), }) ``` Leave `expiresAt` out, or pass `null`, for a key that never expires. ## What happens at expiry From the moment `expiresAt` is reached, `verify` returns `{ valid: false, errorCode: 'EXPIRED' }`. The record stays in storage: keypal does not delete expired keys, so you can still list them and show users which keys lapsed. A non-empty value that can't be parsed as a date counts as expired, so a corrupt field never turns into a key that works forever. An empty string (`expiresAt: ""`) means no expiry, the same as `null`, for compatibility with keys stored by keypal 0.2.0. If a key is both revoked and expired, `verify` reports `REVOKED`. ## Change an expiry Rotate the key to issue a replacement with a new expiry. Fields you pass replace the old key's, and `null` clears the expiry: ```ts const { key: newKey } = await keys.rotate(record.id, { expiresAt: new Date(Date.now() + 90 * DAY_MS), }) ``` This gives the client a new secret and revokes the old one at once. To extend a key without changing its secret, call `update(id, { expiresAt })` on your storage adapter. ## Check expiry yourself ```ts import { getKeyStatus, isExpired } from 'keypal' keys.isExpired(record) // true once expiresAt has passed isExpired(record.expiresAt) // the same, on the raw value getKeyStatus(record) // 'active' | 'revoked' | 'expired' | 'disabled' ``` `getKeyStatus` is the rule `verify` uses, so use it when you load keys some other way, such as listing an owner's keys for a dashboard. It reads only `revokedAt` and `expiresAt` (each a `Date`, string, or `null`) and `enabled` (a boolean or `null`), so it works on rows from your own table too. ## Choosing lifetimes Shorter lifetimes limit the damage from a leaked key but mean more rotations for your users. Common choices are 30 to 90 days for keys used by people and up to a year for keys in long-running services. To warn users before a key lapses, list their keys and compare `expiresAt` with the current date, then let them [rotate](/docs/api-reference/key-management) ahead of time. --- # Resource scopes Source: https://keypal.dev/docs/concepts/resource-scopes Global scopes apply everywhere. Resource scopes apply to one resource, named `type:id`, such as `project:123` or `website:site_abc`. Use them when a key should work on some of an account's projects but not others. ## Grant them ```ts const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['projects:read'], resources: { 'project:123': ['projects:write'], 'project:456': ['projects:write', 'deploy'], }, }) ``` This key can read every project, write to projects 123 and 456, and deploy only project 456. To build `resources` in code, [`ResourceBuilder`](/docs/utilities/resource-builder) has `add`, `addMany` (the same scopes for several ids), and `remove`, and merges scopes added twice for one resource: ```ts import { ResourceBuilder } from 'keypal' const resources = new ResourceBuilder() .addMany('project', ['123', '456'], ['projects:write']) .add('project', '456', ['deploy']) .build() ``` ## Check them Pass the resource type and id from the request: ```ts const projectId = '456' keys.checkResourceScope(record, 'project', projectId, 'deploy') keys.checkResourceAnyScope(record, 'project', projectId, ['deploy', 'admin']) keys.checkResourceAllScopes(record, 'project', projectId, ['projects:read', 'deploy']) ``` A resource check grants a scope if the key holds it globally, holds it for that resource, or gets it through [`impliedScopes`](/docs/concepts/scopes-and-permissions). In the last line above, `projects:read` comes from the global scopes and `deploy` from `project:456`, so it returns `true`. These methods return `false` for a `null` record, so you can pass the result of `verifyFromHeaders` directly. Each is shorthand for the matching scope check with a `resource` option: `keys.checkResourceScope(record, 'project', '456', 'deploy')` is `keys.hasScope(record, 'deploy', { resource: 'project:456' })`. A plain `keys.hasScope(record, 'deploy')` without `resource` only looks at global scopes. ## Global or per resource Because global scopes count for every resource, a scope you mean to limit must not also be in `scopes`. A key with `scopes: ['deploy']` can deploy every project, whatever `resources` says. A practical split: put read-only scopes that are safe everywhere in `scopes`, and anything that changes or deletes data in `resources`. Resource ids are stored on the key, so a key does not gain access to projects created after it. Issue a new key, or rotate this one with new `resources`, to add them. --- # Scopes and permissions Source: https://keypal.dev/docs/concepts/scopes-and-permissions A scope is a string naming something a key may do, such as `'read'` or `'deploy:production'`. You choose the names. keypal stores them on the key and gives you checks to run after `verify` succeeds. ## Give a key scopes ```ts const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['projects:read', 'projects:write'], }) ``` The manager has no method that edits a key in place. To change scopes, rotate the key with new ones, which issues a new secret: `keys.rotate(record.id, { scopes: ['projects:read'] })`. To keep the same secret, call `update(id, { scopes })` on your storage adapter. ## Check them ```ts const result = await keys.verify(request.headers) if (!result.record) { return Response.json({ error: result.errorCode }, { status: 401 }) } keys.hasScope(result.record, 'projects:write') // has this one keys.hasAnyScope(result.record, ['projects:write', 'admin']) // has at least one keys.hasAllScopes(result.record, ['projects:read', 'projects:write']) // has every one ``` Matching is exact and case-sensitive. keypal gives no meaning to the names: `'admin'` grants nothing beyond `'admin'`, `'*'` is not a wildcard, and `'projects'` does not include `'projects:read'`. If you want one scope to cover others, say so with `impliedScopes`. ## Scopes that grant other scopes `impliedScopes` maps a scope to the scopes it also grants: ```ts import { createKeys } from 'keypal' const keys = createKeys({ impliedScopes: { admin: ['projects:write', 'billing:read'], 'projects:write': ['projects:read'], }, }) keys.hasScope({ scopes: ['admin'] }, 'projects:read') // true, through projects:write ``` Implications are followed transitively, and cycles are safe. They are applied when the manager checks scopes, not stored on keys, so changing the map changes what existing keys may do on their next request. The common use is splitting a scope. Say `manage:websites` used to cover deleting visitor data and you add a separate `delete:visitor_data` scope for it. Keys issued before the split hold only `manage:websites`, so they would lose access. Add `{ 'manage:websites': ['delete:visitor_data'] }` and they keep it, while new keys can be given the narrow scope alone. The standalone `hasScope`, `hasAnyScope`, and `hasAllScopes` functions take a scope array instead of a record and do not read the manager's configuration; pass `{ impliedScopes }` as their last argument. See [Standalone functions](/docs/utilities/standalone-functions). ## Choosing scope names - Name the resource and the action, such as `projects:read`. Each endpoint can then check exactly one scope. - Give each new key the fewest scopes it needs. Broad scopes are easy to grant and hard to take back. - Keep the list of valid scopes in one place in your code, and validate requested scopes against it before calling `create`, since keypal accepts any string. To limit a key to one project or site instead of all of them, use [resource scopes](/docs/concepts/resource-scopes). --- # Tags Source: https://keypal.dev/docs/concepts/tags Tags are labels you attach to keys, such as `'production'` or `'ci'`. They don't affect `verify` or scope checks; they exist so you can find keys later. ## Add tags ```ts const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['deploy'], tags: ['CI', 'production'], }) record.tags // ['ci', 'production'] ``` keypal stores tags lowercase, and lookups ignore case, so `'CI'` and `'ci'` are the same tag. ## Find keys by tag ```ts await keys.findByTag('production') // every key tagged production await keys.findByTag('production', 'user_123') // only that owner's await keys.findByTags(['production', 'staging']) // keys with either tag await keys.findByTags(['production', 'staging'], 'user_123') ``` `findByTags` returns keys that have any of the tags, not all of them. Results include revoked, expired and disabled keys. To keep only usable ones, filter on `getKeyStatus(key) === 'active'`; filtering on `revokedAt` removes only revoked keys. Without an owner, the lookup covers every owner's keys. Pass the owner when the request comes from a user, so one customer can't see another's keys. ## Act on a group There is no bulk method per tag. Find the keys, then act on each: ```ts const ciKeys = await keys.findByTag('ci', 'user_123') for (const ciKey of ciKeys.filter((k) => !k.revokedAt)) { await keys.revoke(ciKey.id) } ``` Skip keys that are already revoked, since `revoke` throws `ALREADY_REVOKED` for them. To revoke all of an owner's keys regardless of tag, use `keys.revokeAll(ownerId)`. ## Change tags Rotating a key copies its tags; pass `tags` to replace them: `keys.rotate(record.id, { tags: ['staging'] })`. To retag without a new secret, call `update(id, { tags })` on your storage adapter. --- # Configuration Source: https://keypal.dev/docs/getting-started/configuration Every option is optional. `createKeys()` with no arguments gives you unprefixed 32-character keys, SHA-256 hashes, and in-memory storage. ```ts import { createKeys } from 'keypal' import Redis from 'ioredis' const redis = new Redis() const keys = createKeys({ prefix: 'sk_live_', salt: process.env.API_KEY_SALT, storage: 'redis', redis, cache: true, impliedScopes: { admin: ['read', 'write'] }, auditLogs: true, }) ``` ## Key format and hashing | Option | Default | What it does | | --- | --- | --- | | `prefix` | none | Added to the start of every generated key, such as `sk_live_`. `verify` rejects keys without it as `INVALID_FORMAT` before reading storage, and header extraction prefers a header holding a key with this prefix. | | `length` | `32` | Random characters after the prefix. Must be a positive integer. | | `alphabet` | `A–Z`, `a–z`, `0–9` | Characters the random part is drawn from. Needs 2 to 256 characters, at least 2 of them distinct. | | `algorithm` | `'sha256'` | `'sha256'` or `'sha512'`. | | `salt` | none | Secret mixed into every hash, so a leaked table of hashes can't be checked against guessed keys without it. Load it from an environment variable. | `createKeys` throws a `RangeError` for a bad `length` or `alphabet`. :::warning Changing `salt` or `algorithm` changes every key's hash, and changing `prefix` makes existing keys fail the prefix check. Existing keys stop verifying. Set these once, before you issue real keys. ::: ## Storage | Option | Default | What it does | | --- | --- | --- | | `storage` | `'memory'` | Where keys live. See below. | | `redis` | none | An ioredis client. Required when `storage` or `cache` is `'redis'`. | | `revokedKeyTtl` | `604800` (7 days) | Seconds a revoked key's record stays in Redis before Redis deletes it. `0` keeps it. Applies only with `storage: 'redis'`. | `storage` takes one of four things: - `'memory'`: keys live in the process and are lost when it exits. For tests and local development. - `'redis'`: keypal creates a Redis store from the `redis` client. - A storage adapter such as `new DrizzleStore(...)`, `new KyselyStore(...)`, `new PrismaStore(...)`, or your own object implementing `Storage`. See [Storage](/docs/storage/overview). - A lookup, `{ findByHash, findById?, update? }`, for keys kept in your own table. `verify` runs its checks against your rows and returns them with your type; key management methods throw `STORAGE_NOT_SUPPORTED`. See [the quick start](/docs/getting-started/quick-start) for an example. After `revokedKeyTtl` passes, Redis has deleted the record, so `verify` returns `INVALID_KEY` for that key instead of `REVOKED`. ## Caching | Option | Default | What it does | | --- | --- | --- | | `cache` | `false` | `true` for an in-memory cache, `'redis'` for a Redis cache, or your own `Cache` object. | | `cacheTtl` | `60` | Seconds a cache entry lives. | The cache maps a key's hash to its id, and `verify` still reads the key by id on every call. It only saves work with Redis storage and an in-process cache: `cache: true`, or your own local `Cache` such as a `MemoryCache`. A Redis-backed cache costs the round trip it saves. Leave it off otherwise. [Caching](/docs/concepts/caching) explains why. ## Reading keys from headers | Option | Default | What it does | | --- | --- | --- | | `headerNames` | `['authorization', 'x-api-key']` | Headers checked, in order. Names are case-insensitive. | | `extractBearer` | `true` | Strip `Bearer ` from header values. | With a `prefix` set, the first header whose value starts with the prefix wins, so an unrelated `Authorization: Basic ...` header does not hide a key sent in `x-api-key`. Without a match, keypal uses the first non-empty header. Both options can be overridden per call in `verify` and `extractKey`. ## Usage tracking | Option | Default | What it does | | --- | --- | --- | | `autoTrackUsage` | `true` | Write the key's `lastUsedAt` after each successful `verify`. | | `usageTrackingInterval` | `60` | Minimum seconds between `lastUsedAt` writes for the same key. `0` writes on every verify. | Writes happen in the background and never delay or fail a `verify`; a failed write is logged and retried on a later verify. Each manager instance tracks its own write times, so several servers can each write once per interval. With a positive `usageTrackingInterval`, one manager tracks up to 10,000 keys at a time; past that, a key not yet tracked is skipped until a slot frees up. With `0`, nothing is tracked and every verify writes, with no cap. Tracking is off when the storage has no `update` method, as with a lookup that leaves it out. Pass `skipTracking: true` to `verify` to skip it for one call. ## Scopes | Option | Default | What it does | | --- | --- | --- | | `impliedScopes` | none | Scopes that grant other scopes, such as `{ admin: ['read', 'write'] }`. Applied transitively by the manager's scope checks. | See [Scopes and permissions](/docs/concepts/scopes-and-permissions). ## Audit logging | Option | Default | What it does | | --- | --- | --- | | `auditLogs` | `false` | Record who created, revoked, rotated, enabled, or disabled each key. | | `auditContext` | none | Context added to every log entry, such as `{ userId: 'system', metadata: { service: 'api' } }`. Per-call context overrides it. | The storage must support logs. See [Audit logging](/docs/concepts/audit-logging). --- # Installation Source: https://keypal.dev/docs/getting-started/installation ## Install keypal ```package-install npm install keypal ``` keypal hashes with `node:crypto`, so it runs on Node.js, Bun, and other runtimes that provide that module. Its only runtime dependency is `nanoid`. ## Add your storage client The core package has no storage dependencies. Each adapter has its own import path, and the database client it uses is an optional peer dependency: install the one you use and skip the rest. | Storage | Import | Also install | | --- | --- | --- | | Memory | `keypal` (the default) or `keypal/memory` | nothing | | Redis | `storage: 'redis'`, or `RedisStore` from `keypal/redis` | `ioredis` (5 or 6) | | Drizzle | `DrizzleStore` from `keypal/drizzle`, schema from `keypal/drizzle/schema` | `drizzle-orm` | | Kysely | `KyselyStore` from `keypal/kysely` | `kysely` | | Prisma | `PrismaStore` from `keypal/prisma` | `@prisma/client` | For example, to keep keys in Redis: ```package-install npm install keypal ioredis ``` The SQL adapters also need the driver for your database, such as `pg` for PostgreSQL. Each [storage page](/docs/storage/overview) lists what to install and the table to create. :::note Memory storage is the default and keeps keys only for the life of the process. Use it for tests and local development, and pick a persistent store before you issue real keys. ::: ## Next Follow the [quick start](/docs/getting-started/quick-start) to create a key and verify a request. --- # Quick start Source: https://keypal.dev/docs/getting-started/quick-start This page takes you from a new project to a request that keypal has authenticated. The examples use the Fetch API's `Request`, which Hono, Next.js route handlers, Bun, Deno, and Cloudflare Workers all hand you. `verify` also takes a plain header object or the key as a string. 1. **Create a manager** `createKeys` returns the manager you create and verify keys with. Make one per process and share it. ```ts keys.ts import { createKeys } from 'keypal' import Redis from 'ioredis' export const keys = createKeys({ prefix: 'sk_live_', salt: process.env.API_KEY_SALT, storage: 'redis', redis: new Redis(), // localhost:6379; pass a URL or options for other servers }) ``` The prefix is added to every key and lets keypal reject keys without it before touching storage. The salt is mixed into every hash; keep it secret and never change it, because existing keys stop matching. To try keypal without Redis, leave out `storage` and `redis` and keys are kept in memory. For SQL databases, see [Storage](/docs/storage/overview). 2. **Create a key** ```ts import { keys } from './keys' const { key, record } = await keys.create({ ownerId: 'user_123', name: 'CI deploys', scopes: ['deploy'], }) ``` `key` is the secret: `sk_live_` followed by 32 random characters. Show it to the user once; keypal stores only its hash and cannot show it again. `record` is what was stored: its `id`, `ownerId`, `scopes`, and the other fields described in [API keys](/docs/concepts/api-keys). 3. **Verify a request** Clients send the key in `Authorization: Bearer ` or `x-api-key: `. Pass the request's headers to `verify`: ```ts import { keys } from './keys' export async function handler(request: Request) { const result = await keys.verify(request.headers) if (!result.record) { return Response.json( { error: result.error, code: result.errorCode }, { status: 401 } ) } return Response.json({ owner: result.record.ownerId }) } ``` `record` is set only when `valid` is `true`. Otherwise `errorCode` says why: `MISSING_KEY`, `INVALID_FORMAT`, `INVALID_KEY`, `REVOKED`, `EXPIRED`, or `DISABLED`. See [Error handling](/docs/utilities/error-handling) for mapping them to responses. 4. **Check scopes** A valid key is not necessarily allowed to do everything. Check its scopes before acting: ```ts if (!keys.hasScope(result.record, 'deploy')) { return Response.json({ error: 'forbidden' }, { status: 403 }) } ``` [Scopes and permissions](/docs/concepts/scopes-and-permissions) covers the other checks, and [resource scopes](/docs/concepts/resource-scopes) covers keys limited to one project or site. 5. **Revoke it** ```ts await keys.revoke(record.id) ``` The next `verify` of that key, on any server sharing the storage, returns `REVOKED`. ## Already have an API keys table? If your app already stores hashed keys, pass a lookup instead of a storage adapter. `verify` runs the same checks against your rows (prefix and length, hashing, revoked, expired, disabled, usage tracking) and returns them with your row type. ```ts keys.ts import { createKeys } from 'keypal' import { eq } from 'drizzle-orm' import { db } from './db' import { apiKeys } from './schema' export const keys = createKeys({ prefix: 'sk_', storage: { // Rows need id and keyHash; enabled, expiresAt and revokedAt are read when present. findByHash: async (keyHash) => (await db.query.apiKeys.findFirst({ where: eq(apiKeys.keyHash, keyHash) })) ?? null, // Optional. Without it, keypal does not track lastUsedAt. 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) // result.record has your row's type, e.g. result.record.organizationId ``` Your table's `keyHash` values must be what `keys.hashKey(secret)` returns with the same `salt` and `algorithm`. Creating and revoking keys stays in your code: `keys.generateKey()` gives you a new secret and `keys.hashKey()` its hash to store. keypal's own management methods (`create`, `revoke`, `list`, and the rest) throw `STORAGE_NOT_SUPPORTED` in this mode. The exception is `updateLastUsed`, which works when you pass `update`. ## Next - [Configuration](/docs/getting-started/configuration) lists every option. - [API keys](/docs/concepts/api-keys) explains what `verify` checks and in what order. --- # Custom storage Source: https://keypal.dev/docs/storage/custom-storage 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. ```ts 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](/docs/concepts/caching) 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): ```ts 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` and `disable` throw `STORAGE_NOT_SUPPORTED`. The audit log methods throw `AUDIT_LOGGING_DISABLED` unless `auditLogs: true` is set, and `STORAGE_NOT_SUPPORTED` when it is. `updateLastUsed` works when the lookup has `update`. 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 an object as a full adapter only when it has every one of `save`, `findById`, `findByOwner`, `findByTags`, `findByTag`, `update`, `delete` and `deleteByOwner`; anything less is used as a lookup. ```ts import type { ApiKeyMutableFields, ApiKeyRecord, AuditLog, AuditLogQuery, AuditLogStats, } from 'keypal' type Storage = { save(record: ApiKeyRecord): Promise findByHash(keyHash: string): Promise findById(id: string): Promise findByOwner(ownerId: string): Promise findByTags(tags: string[], ownerId?: string): Promise findByTag(tag: string, ownerId?: string): Promise update(id: string, fields: Partial): Promise delete(id: string): Promise deleteByOwner(ownerId: string): Promise // Optional: audit logs saveLog?(log: AuditLog): Promise findLogs?(query: AuditLogQuery): Promise countLogs?(query: AuditLogQuery): Promise deleteLogs?(query: AuditLogQuery): Promise getLogStats?(ownerId: string): Promise } ``` Then pass an instance as `storage`: ```ts 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. --- # Drizzle Source: https://keypal.dev/docs/storage/drizzle `DrizzleStore` keeps keys in a table in your database, through the Drizzle instance your app already has. It works with PostgreSQL, MySQL, MariaDB and SQLite (including libSQL and Cloudflare D1). ## Install ```package-install keypal drizzle-orm ``` Plus the driver for your database, such as `pg`, `mysql2` or `better-sqlite3`. ## Table The default table has three columns: `id`, `keyHash`, and `metadata`, a JSON column holding every other field. Make `keyHash` unique; `verify` looks keys up by it. **PostgreSQL** keypal ships this table. Re-export it from your schema so drizzle-kit creates it: ```ts db/schema.ts export { apikey } from 'keypal/drizzle/schema' ``` It creates a table named `apikey` with `id text`, `key_hash text` (unique and indexed) and `metadata jsonb`. If you define it yourself, `metadata` must be `jsonb`, not `json`. **MySQL / MariaDB** ```ts db/schema.ts import { json, mysqlTable, varchar } from 'drizzle-orm/mysql-core' export const apikey = mysqlTable('apikey', { id: varchar('id', { length: 255 }).primaryKey(), keyHash: varchar('key_hash', { length: 128 }).notNull().unique(), metadata: json('metadata').notNull(), }) ``` **SQLite** ```ts db/schema.ts import { sqliteTable, text } from 'drizzle-orm/sqlite-core' export const apikey = sqliteTable('apikey', { id: text('id').primaryKey(), keyHash: text('key_hash').notNull().unique(), // Plain text: keypal writes the JSON itself, so don't use { mode: 'json' }. metadata: text('metadata').notNull(), }) ``` Then generate and run the migration with `drizzle-kit generate` and `drizzle-kit migrate` (or `drizzle-kit push`). ## Setup ```ts import { drizzle } from 'drizzle-orm/node-postgres' import { createKeys } from 'keypal' import { DrizzleStore } from 'keypal/drizzle' import { apikey } from './db/schema' const db = drizzle(process.env.DATABASE_URL!) const keys = createKeys({ prefix: 'sk_', storage: new DrizzleStore({ db, table: apikey }), }) ``` keypal detects the database from the Drizzle instance. If it can't, it logs a warning and assumes PostgreSQL; set `provider: 'pg' | 'mysql' | 'sqlite'` to say which. ## Options | Option | Type | Description | | --- | --- | --- | | `db` | Drizzle database | Your Drizzle instance | | `table` | Drizzle table | The API key table | | `provider` | `'pg' \| 'mysql' \| 'sqlite'` | Overrides detection | | `auditLogTable` | Drizzle table | Enables audit log storage | | `schema` | object | Column names and `flattenMetadata`; see below | | `debugLogs` | boolean | Logs every storage call | ## Column names Column names in `schema` are the property names on your Drizzle table object, not the SQL names. If your table calls the hash column `hash`: ```ts const store = new DrizzleStore({ db, table: apiKeys, schema: { apiKeyColumns: { keyHash: 'hash' } }, }) ``` ## One column per field With `flattenMetadata: true`, each field gets its own column instead of the JSON column. Use it to index or query fields such as `ownerId` directly. On MySQL, MariaDB and SQLite it also stops owner lookups from reading the whole table. The table needs a column for every field. Property names match keypal's field names unless you rename them with `apiKeyColumns.metadataColumns`. ```ts db/schema.ts import { boolean, index, jsonb, pgTable, text } from 'drizzle-orm/pg-core' export const apiKeys = pgTable( 'api_keys', { id: text('id').primaryKey(), keyHash: text('key_hash').notNull().unique(), ownerId: text('owner_id').notNull(), name: text('name'), description: text('description'), scopes: jsonb('scopes'), resources: jsonb('resources'), tags: jsonb('tags'), enabled: boolean('enabled'), // keypal stores timestamps as ISO strings expiresAt: text('expires_at'), revokedAt: text('revoked_at'), lastUsedAt: text('last_used_at'), createdAt: text('created_at'), rotatedTo: text('rotated_to'), }, (table) => [index('api_keys_owner_id_idx').on(table.ownerId)] ) ``` ```ts const store = new DrizzleStore({ db, table: apiKeys, schema: { flattenMetadata: true }, }) ``` ## Audit logs Pass `auditLogTable` and turn on `auditLogs` to store [audit logs](/docs/concepts/audit-logging): ```ts db/schema.ts import { jsonb, pgTable, text } from 'drizzle-orm/pg-core' export const apiKeyLogs = pgTable('api_key_logs', { id: text('id').primaryKey(), keyId: text('key_id').notNull(), ownerId: text('owner_id').notNull(), action: text('action').notNull(), timestamp: text('timestamp').notNull(), data: jsonb('data'), }) ``` ```ts const keys = createKeys({ prefix: 'sk_', auditLogs: true, storage: new DrizzleStore({ db, table: apikey, auditLogTable: apiKeyLogs }), }) ``` `timestamp` holds an ISO string, which sorts and compares correctly as text. Use `json` for `data` on MySQL and `text` on SQLite. Rename columns with `schema.auditLogColumns`. ## Behavior - **Updates** write only the given fields in one statement (a JSONB merge on PostgreSQL, `json_set` on MySQL, MariaDB and SQLite), so a background `lastUsedAt` write can't undo a concurrent revoke. - **Owner and tag lookups** run in SQL on PostgreSQL. On MySQL, MariaDB and SQLite with the JSON column, `list`, `findByTag` and `revokeAll` read the whole table. With `flattenMetadata` there, owner lookups run in SQL, and tag lookups read the owner's keys (or the whole table when no owner is given) and filter them in your process. - **Duplicates** are rejected by your table's constraints, so keep `id` as the primary key and `keyHash` unique. - **Caching** saves nothing here; leave `cache` off. See [Caching](/docs/concepts/caching). --- # Kysely Source: https://keypal.dev/docs/storage/kysely `KyselyStore` keeps keys in a table in your database, through a Kysely instance. It works with PostgreSQL, MySQL, MariaDB and SQLite. SQL Server is untested, and its updates are not atomic (see below). ## Install ```package-install keypal kysely ``` Plus the driver for your dialect, such as `pg`, `mysql2` or `better-sqlite3`. ## Table The default table has three columns: `id`, `keyHash`, and `metadata`, which holds every other field as JSON. Column names are used exactly as written, so the default hash column is `keyHash` in camelCase. Make it unique; `verify` looks keys up by it. **PostgreSQL** ```sql CREATE TABLE api_keys ( id TEXT PRIMARY KEY, "keyHash" TEXT NOT NULL UNIQUE, metadata JSONB NOT NULL ); ``` `metadata` must be `JSONB`: owner and tag lookups use the `@>` operator, which `JSON` doesn't have. **MySQL / MariaDB** ```sql CREATE TABLE api_keys ( id VARCHAR(255) PRIMARY KEY, keyHash VARCHAR(128) NOT NULL UNIQUE, metadata JSON NOT NULL ); ``` **SQLite** ```sql CREATE TABLE api_keys ( id TEXT PRIMARY KEY, keyHash TEXT NOT NULL UNIQUE, metadata TEXT NOT NULL ); ``` ## Setup ```ts import { Kysely, PostgresDialect } from 'kysely' import { Pool } from 'pg' import { createKeys } from 'keypal' import { KyselyStore } from 'keypal/kysely' // Your own Database type works too: new Kysely(...) const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }), }), }) const keys = createKeys({ prefix: 'sk_', storage: new KyselyStore({ db, table: 'api_keys' }), }) ``` keypal detects the database from the dialect. If it can't, it logs a warning and assumes PostgreSQL; set `provider: 'pg' | 'mysql' | 'sqlite' | 'mssql'` to say which. ## Options | Option | Type | Description | | --- | --- | --- | | `db` | `Kysely` | Your Kysely instance, typed with any schema | | `table` | string | The API key table name | | `provider` | `'pg' \| 'mysql' \| 'sqlite' \| 'mssql'` | Overrides detection | | `auditLogTable` | string | Enables audit log storage | | `schema` | object | Column names and `flattenMetadata`; see below | | `debugLogs` | boolean | Logs every storage call | ## Column names Rename columns with `schema.apiKeyColumns`. The names are the SQL column names: ```ts const store = new KyselyStore({ db, table: 'api_keys', schema: { apiKeyColumns: { keyHash: 'key_hash', metadata: 'data' } }, }) ``` With `flattenMetadata: true`, each field gets its own column instead of `metadata`. The table then needs a column for every field: `ownerId`, `name`, `description`, `scopes`, `resources`, `tags`, `enabled`, `expiresAt`, `revokedAt`, `lastUsedAt`, `createdAt` and `rotatedTo`. Rename them with `apiKeyColumns.metadataColumns`: ```ts const store = new KyselyStore({ db, table: 'api_keys', schema: { flattenMetadata: true, apiKeyColumns: { keyHash: 'key_hash', metadataColumns: { ownerId: 'owner_id', expiresAt: 'expires_at' }, }, }, }) ``` Timestamps are stored as ISO strings. On PostgreSQL, make `scopes` and `tags` `TEXT[]` and `resources` `JSONB`; on the other databases, `scopes`, `resources` and `tags` hold JSON text. Index the owner column: owner lookups then run in SQL on every database. ## Audit logs Pass `auditLogTable` and turn on `auditLogs` to store [audit logs](/docs/concepts/audit-logging): ```sql CREATE TABLE api_key_logs ( id TEXT PRIMARY KEY, "keyId" TEXT NOT NULL, "ownerId" TEXT NOT NULL, action TEXT NOT NULL, timestamp TEXT NOT NULL, data JSONB ); ``` ```ts const keys = createKeys({ prefix: 'sk_', auditLogs: true, storage: new KyselyStore({ db, table: 'api_keys', auditLogTable: 'api_key_logs' }), }) ``` `timestamp` holds an ISO string, which sorts and compares correctly as text. On MySQL and SQLite, `data` can be `TEXT`. Rename columns with `schema.auditLogColumns`. ## Behavior - **Updates** write only the given fields in one statement on PostgreSQL, MySQL, MariaDB and SQLite, so a background `lastUsedAt` write can't undo a concurrent revoke. - **SQL Server** with the JSON column rewrites the whole `metadata` value on each update. Two updates at the same moment can overwrite each other, for example a `lastUsedAt` write undoing a revoke. Use `flattenMetadata` there, which writes only the changed columns. - **Owner and tag lookups** run in SQL on PostgreSQL with the JSON column. On the other databases, `list`, `findByTag` and `revokeAll` read the whole table. With `flattenMetadata`, owner lookups run in SQL everywhere, and tag lookups read the owner's keys (or the whole table when no owner is given) and filter them in your process. - **Caching** saves nothing here; leave `cache` off. See [Caching](/docs/concepts/caching). --- # Memory Source: https://keypal.dev/docs/storage/memory Memory storage keeps keys in `Map`s inside the process. It is the default: with no `storage` option, keypal uses it. It needs no setup and no dependencies. Keys are lost when the process exits, and every process has its own store. Use it for tests, scripts and local development, not for production. ## Setup ```ts import { createKeys } from 'keypal' // The default const keys = createKeys({ prefix: 'sk_' }) // The same, spelled out const explicit = createKeys({ prefix: 'sk_', storage: 'memory' }) ``` Each `createKeys` call with memory storage gets its own empty store. To share one store between managers, for example in a test, create it yourself: ```ts import { createKeys } from 'keypal' import { MemoryStore } from 'keypal/memory' const store = new MemoryStore() const issuer = createKeys({ prefix: 'sk_', storage: store }) const verifier = createKeys({ prefix: 'sk_', storage: store }) ``` ## Behavior - Lookups by hash, id, owner and tag use indexes, so none of them scan every key. - `save` throws if the id or the key hash already exists. - Records are copied in and out, so changing a returned record doesn't change the stored key. - Tags are stored lowercase, as in every other store. - Audit logs are supported and kept in memory with the keys. For persistent storage, use [Redis](/docs/storage/redis) or a SQL adapter such as [Drizzle](/docs/storage/drizzle). --- # Overview Source: https://keypal.dev/docs/storage/overview keypal keeps keys in a storage adapter. Without a `storage` option it uses memory, which loses every key when the process exits. For anything real, pick Redis or one of the SQL adapters. The core package has no storage dependencies. Each adapter has its own import path, and its database client is an optional peer dependency that you install yourself. | Adapter | Import | Install | Databases | | --- | --- | --- | --- | | [Memory](/docs/storage/memory) | `keypal/memory` (or the default) | nothing | none, in-process | | [Redis](/docs/storage/redis) | `keypal/redis` (or `storage: "redis"`) | `ioredis` 5 or 6 | Redis, single node or Sentinel | | [Drizzle](/docs/storage/drizzle) | `keypal/drizzle` | `drizzle-orm` | PostgreSQL, MySQL, MariaDB, SQLite | | [Kysely](/docs/storage/kysely) | `keypal/kysely` | `kysely` | PostgreSQL, MySQL, MariaDB, SQLite | | [Prisma](/docs/storage/prisma) | `keypal/prisma` | `@prisma/client` | PostgreSQL | ## Choosing an adapter - **Memory** for tests, scripts and local development. - **Redis** when Redis is already your shared state. Revoked keys expire on their own after `revokedKeyTtl`. - **Drizzle, Kysely or Prisma** when you want keys in the database you already run, next to your other tables. Use the one your app already uses. - **Your own table** if you already have an API keys table: pass a lookup with `findByHash` and keypal verifies against it. See [Custom storage](/docs/storage/custom-storage). ## How the SQL adapters store keys Drizzle, Kysely and Prisma share one storage layer, so they behave the same way. By default a key is one row with three columns: `id`, `keyHash`, and `metadata`, holding every other field (`ownerId`, `name`, `scopes`, `tags`, `expiresAt`, `revokedAt`, and the rest) as JSON. It is a `JSONB` column on PostgreSQL, `JSON` on MySQL and MariaDB, and `TEXT` holding JSON on SQLite. Each adapter's page shows the table to create. `keyHash` should be unique and indexed: `verify` looks keys up by it on every call. ### Updates `update(id, fields)` writes only the fields it is given. A background `lastUsedAt` write therefore can't undo a revoke that happened at the same moment. How each database does this: - PostgreSQL merges the change into the JSON column in one statement. - MySQL, MariaDB and SQLite use `json_set` and `json_remove` in one statement. - Prisma compares the stored JSON before writing and retries if it changed. - With `flattenMetadata`, only the columns of the given fields are written. The exceptions are noted on the [Kysely](/docs/storage/kysely) and [Prisma](/docs/storage/prisma) pages. ### Options shared by every SQL adapter | Option | What it does | | --- | --- | | `schema.apiKeyColumns` | Renames `id`, `keyHash` and `metadata`, and (with `metadataColumns`) the per-field columns | | `schema.flattenMetadata` | Stores each field in its own column instead of the JSON column | | `schema.auditLogColumns` | Renames the audit log columns | | `debugLogs` | Logs every storage call and its result, with key hashes redacted | The audit log table (`auditLogTable` on Drizzle and Kysely, `auditLogModel` on Prisma) is optional. Without it, `auditLogs: true` records nothing and the log queries throw `STORAGE_NOT_SUPPORTED`. ### Owner and tag queries On PostgreSQL, finding keys by owner or tag runs in SQL against the JSON column. On MySQL, MariaDB and SQLite with the default `metadata` column, `list(ownerId)`, `findByTag` and `revokeAll` read the whole table and filter in your process. With `flattenMetadata` and an indexed owner column, `list(ownerId)` and `revokeAll` filter by owner in SQL on every database, and a tag lookup given an owner reads only that owner's rows. A tag lookup without an owner still reads the whole table on MySQL, MariaDB and SQLite. Turn it on for large tables on those databases. ## Caching The key cache (`cache: true`) saves a round trip only with Redis storage. With a SQL adapter, finding a key by hash costs the same as finding it by id, so leave the cache off. See [Caching](/docs/concepts/caching). **[Custom storage](/docs/storage/custom-storage)** Write your own adapter, or verify keys in a table you already have. **[Configuration](/docs/getting-started/configuration)** Every `createKeys` option, including `storage` and `revokedKeyTtl`. --- # Prisma Source: https://keypal.dev/docs/storage/prisma `PrismaStore` keeps keys in a model in your Prisma schema, through the Prisma Client your app already has. Use it with PostgreSQL: its owner and tag queries use Prisma's PostgreSQL JSON filters (`path: ['ownerId']`, `array_contains`), and keypal tests it only on PostgreSQL. For MySQL, MariaDB or SQLite, use [Drizzle](/docs/storage/drizzle) or [Kysely](/docs/storage/kysely). ## Install ```package-install keypal @prisma/client ``` keypal works with Prisma 6.18 and later 6.x releases. The `prisma` CLI, which runs the schema commands below, is a separate package: add it as a dev dependency if your app doesn't have it. ## Model Add a model with `id`, a unique `keyHash`, and a `Json` field for every other value: ```prisma prisma/schema.prisma model ApiKey { id String @id keyHash String @unique metadata Json @@map("api_keys") } ``` `keyHash` must be `@unique`: keypal finds keys with `findUnique` on it. Then run `prisma migrate dev` (or `prisma db push`) and `prisma generate`. ## Setup ```ts import { PrismaClient } from '@prisma/client' import { createKeys } from 'keypal' import { PrismaStore } from 'keypal/prisma' const prisma = new PrismaClient() const keys = createKeys({ prefix: 'sk_', storage: new PrismaStore({ prisma, model: 'apiKey' }), }) ``` `model` is the property on the client, which is the model name in camelCase: `model ApiKey` is `prisma.apiKey`, so pass `'apiKey'`. keypal throws at startup if the client has no such model. ## Options | Option | Type | Description | | --- | --- | --- | | `prisma` | `PrismaClient` | Your Prisma Client | | `model` | string | The client property for the API key model | | `auditLogModel` | string | Enables audit log storage | | `schema` | object | Field names; see below | | `debugLogs` | boolean | Logs every storage call | ## Field names If your model names the fields differently, map them with `schema.apiKeyColumns`. The names are Prisma field names, not database column names: ```ts const store = new PrismaStore({ prisma, model: 'apiKey', schema: { apiKeyColumns: { keyHash: 'hash', metadata: 'data' } }, }) ``` `schema.flattenMetadata` (one field per value instead of the `Json` field) exists for Prisma too, but keypal doesn't test it with Prisma. Prefer the `Json` field. ## Audit logs Add a log model, pass `auditLogModel`, and turn on `auditLogs` to store [audit logs](/docs/concepts/audit-logging): ```prisma prisma/schema.prisma model ApiKeyLog { id String @id keyId String ownerId String action String timestamp String data Json? @@index([ownerId]) @@map("api_key_logs") } ``` ```ts const keys = createKeys({ prefix: 'sk_', auditLogs: true, storage: new PrismaStore({ prisma, model: 'apiKey', auditLogModel: 'apiKeyLog' }), }) ``` `timestamp` holds an ISO string, which sorts and compares correctly as text. Rename fields with `schema.auditLogColumns`. ## Behavior - **Updates** compare and set: keypal writes the new `metadata` only if the stored value hasn't changed since it read it, and retries up to five times before throwing. A background `lastUsedAt` write can't undo a concurrent revoke. - **If the database rejects JSON equality filters**, keypal falls back to a plain read-then-write update for the rest of the process. Two updates at the same moment can then overwrite each other. - **Deleting a missing key** is a no-op, not an error. - **Caching** saves nothing here; leave `cache` off. See [Caching](/docs/concepts/caching). --- # Redis Source: https://keypal.dev/docs/storage/redis The Redis store keeps keys in Redis through an [ioredis](https://github.com/redis/ioredis) client, so every server running your app sees the same keys. Revoked keys expire on their own. ## Install ```package-install keypal ioredis ``` keypal works with ioredis 5 and 6. ## Setup Pass `storage: 'redis'` and your client: ```ts import Redis from 'ioredis' import { createKeys } from 'keypal' const redis = new Redis() // or new Redis('redis://user:pass@host:6379') const keys = createKeys({ prefix: 'sk_', storage: 'redis', redis, }) ``` `redis` must be an ioredis client. keypal throws at startup if it is missing or if it is a cache-only client without pipelines. ## Revoked keys expire When you revoke or rotate a key, keypal sets an expiry on its record. After `revokedKeyTtl` seconds (default 604800, 7 days) Redis deletes it. ```ts const keys = createKeys({ prefix: 'sk_', storage: 'redis', redis, revokedKeyTtl: 60 * 60 * 24 * 30, // 30 days; 0 keeps revoked keys forever }) ``` Until it expires, verifying a revoked key returns `REVOKED`. After that the key is gone: `verify` returns `INVALID_KEY` and `list` no longer includes it. Set `revokedKeyTtl: 0` if you need revoked keys to stay readable. `revokedKeyTtl` applies only with `storage: 'redis'`. If you create a `RedisStore` yourself (below), keypal doesn't set the expiry; call `store.setTtl(id, seconds)` after revoking if you want it. ## Custom key prefix To change the key prefix, create the store yourself: ```ts import Redis from 'ioredis' import { createKeys } from 'keypal' import { RedisStore } from 'keypal/redis' const store = new RedisStore({ client: new Redis(), prefix: 'myapp:apikey:' }) const keys = createKeys({ prefix: 'sk_', storage: store }) ``` ## How keys are stored With the default prefix `apikey:`: | Redis key | Type | Holds | | --- | --- | --- | | `apikey:{id}` | string | The key record as JSON | | `apikey:hash:{keyHash}` | string | The key's id, for `verify` | | `apikey:owner:{ownerId}` | set | Ids of the owner's keys | | `apikey:tag:{tag}` | set | Ids of keys with the tag | | `apikey:log:{id}` | string | One audit log entry | | `apikey:logs:all`, `apikey:logs:key:{keyId}`, `apikey:logs:owner:{ownerId}`, `apikey:logs:action:{action}` | sorted set | Audit log ids by timestamp | Audit log entries don't expire. Delete old ones with `deleteLogs`. ## Behavior - **Updates** use a compare-and-set script: keypal writes the record only if it hasn't changed since it was read, and retries up to five times. A background `lastUsedAt` write can't undo a concurrent revoke. - **Redis Cluster is not supported.** The store reads and writes several keys per call (the record, its hash entry, owner and tag sets), and Cluster rejects that when the keys sit in different slots. Use a single node, or Sentinel for failover. - **Caching:** with Redis storage, the in-memory cache (`cache: true`) saves one round trip per `verify`. A Redis cache (`cache: 'redis'`) costs the same round trip it saves. See [Caching](/docs/concepts/caching). --- # Error handling Source: https://keypal.dev/docs/utilities/error-handling keypal reports problems two ways: - `verify()` returns them: `{ valid: false, error, errorCode }`. It doesn't throw for a bad key. - Management and audit-log methods throw an `ApiKeyError`. Errors from your storage, cache or database client (connection failures, constraint violations) are passed through unchanged, not wrapped in an `ApiKeyError`. ## ApiKeyError ```typescript type ApiKeyError = { code: ApiKeyErrorCode message: string details?: unknown } ``` It is a plain object, not an `Error` instance, so `instanceof Error` is `false` and it has no stack trace. Check `code`: ```typescript import { ApiKeyErrorCode, type ApiKeyError } from 'keypal' function isApiKeyError(error: unknown): error is ApiKeyError { return typeof error === 'object' && error !== null && 'code' in error && 'message' in error && typeof error.message === 'string' && Object.values(ApiKeyErrorCode).includes((error as ApiKeyError).code) } ``` ## Error codes `ApiKeyErrorCode` is a const object; each value equals its name, e.g. `ApiKeyErrorCode.REVOKED === "REVOKED"`. ### Returned by verify() | Code | Message | When | | --- | --- | --- | | `MISSING_KEY` | Missing API key | No key in the string or headers. | | `INVALID_FORMAT` | Invalid API key format | Wrong prefix, or longer than the maximum key length. | | `INVALID_KEY` | Invalid API key | No stored key has this hash. | | `REVOKED` | API key has been revoked | Revoked or rotated. | | `EXPIRED` | API key has expired | `expiresAt` has passed, or is a non-empty value that can't be parsed. | | `DISABLED` | API key is disabled | `enabled` is `false`. | A key in more than one state reports the first of `REVOKED`, `EXPIRED`, `DISABLED`. Details are on [Verification](/docs/api-reference/verification). ### Thrown by methods | Code | Message | Thrown by | | --- | --- | --- | | `KEY_NOT_FOUND` | API key not found | `revoke`, `rotate`, `enable`, `disable` when no key has the id. | | `ALREADY_REVOKED` | API key is already revoked | `revoke` on a revoked key. | | `CANNOT_MODIFY_REVOKED` | Cannot modify a revoked key | `rotate`, `enable`, `disable` on a revoked key. | | `ALREADY_ENABLED` | API key is already enabled | `enable` on an enabled key. | | `ALREADY_DISABLED` | API key is already disabled | `disable` on a disabled key. | | `AUDIT_LOGGING_DISABLED` | Audit logging is not enabled | Audit-log methods when `auditLogs` is not `true`. | | `STORAGE_NOT_SUPPORTED` | Storage does not support this operation | Management methods when `storage` is a `KeyLookup`; `updateLastUsed` without `update`; audit-log methods when the storage lacks them. | ### Reserved `STORAGE_ERROR` ("Storage error occurred") and `CACHE_ERROR` ("Cache error occurred") exist in `ApiKeyErrorCode`, but keypal doesn't currently return or throw them. You can use them in your own code with `createApiKeyError`. ## Handling verify results ```typescript import { ApiKeyErrorCode } from 'keypal' const result = await keys.verify(request.headers) if (!result.valid) { const status = result.errorCode === ApiKeyErrorCode.DISABLED ? 403 : 401 return Response.json({ error: result.error, code: result.errorCode }, { status }) } ``` ## Handling thrown errors ```typescript try { await keys.disable(keyId, { userId: adminId }) } catch (error) { if (!isApiKeyError(error)) throw error switch (error.code) { case ApiKeyErrorCode.KEY_NOT_FOUND: return Response.json({ error: error.message }, { status: 404 }) case ApiKeyErrorCode.ALREADY_DISABLED: return new Response(null, { status: 204 }) case ApiKeyErrorCode.CANNOT_MODIFY_REVOKED: return Response.json({ error: error.message }, { status: 409 }) default: throw error } } ``` ## createApiKeyError() ```typescript createApiKeyError(code: ApiKeyErrorCode, details?: unknown): ApiKeyError ``` Returns `{ code, message, details }` with the standard message for `code`. Useful in a custom storage or middleware that should fail the same way keypal does. ```typescript throw createApiKeyError(ApiKeyErrorCode.STORAGE_NOT_SUPPORTED, { method: 'findByTags' }) ``` --- # ResourceBuilder Source: https://keypal.dev/docs/utilities/resource-builder `ResourceBuilder` builds the `resources` map a key stores: keys are `"type:id"`, values are the scopes granted on that resource. For how resource scopes are checked, see [Resource scopes](/docs/concepts/resource-scopes). ```typescript import { ResourceBuilder } from 'keypal' const resources = new ResourceBuilder() .add('project', 'proj_1', ['read', 'deploy']) .addMany('website', ['site_1', 'site_2'], ['read']) .build() // { 'project:proj_1': ['read', 'deploy'], 'website:site_1': ['read'], 'website:site_2': ['read'] } await keys.create({ ownerId: 'user_123', resources }) ``` `createResourceBuilder()` returns `new ResourceBuilder()`. ## Methods Methods that return `this` can be chained. | Method | Returns | Does | | --- | --- | --- | | `add(type, id, scopes: string[])` | `this` | Grants scopes on `type:id`. Scopes already on that resource are merged without duplicates; the first call stores the array as given. | | `addOne(type, id, scope: string)` | `this` | Same as `add` with one scope. | | `addMany(type, ids: string[], scopes: string[])` | `this` | `add` for each id. | | `remove(type, id)` | `this` | Removes the resource. | | `removeScopes(type, id, scopes: string[])` | `this` | Removes those scopes; removes the resource when none are left. | | `has(type, id)` | `boolean` | Whether the resource has been added. | | `get(type, id)` | `string[]` | The resource's scopes, or `[]` when it isn't there. | | `clear()` | `this` | Removes every resource. | | `build()` | `Record` | A shallow copy of the map. | ## ResourceBuilder.from() ```typescript static from(resources: Record): ResourceBuilder ``` Starts a builder from an existing map, for example to change a stored key's resources before passing them to [`rotate()`](/docs/api-reference/key-management). ```typescript const record = await keys.findById('key_123') const resources = ResourceBuilder.from(record?.resources ?? {}) .add('project', 'proj_2', ['read']) .removeScopes('project', 'proj_1', ['deploy']) .build() await keys.rotate('key_123', { resources }) ``` :::note The manager has no method that edits a key's resources or scopes in place (only `revoke`, `enable`, `disable` and usage tracking change a stored key). To change resources or scopes, rotate the key with the new values, or create a new key. ::: --- # Standalone functions Source: https://keypal.dev/docs/utilities/standalone-functions These functions are exported from `keypal` and need no `createKeys` instance. They don't know a manager's config, so pass any prefix, salt or implied scopes yourself. ## Key generation and hashing ```typescript generateKey(options?: { prefix?: string; length?: number; alphabet?: string }): string hashKey(key: string, options?: { algorithm?: 'sha256' | 'sha512'; salt?: string }): string validateKey(key: string, storedHash: string, options?: { algorithm?: 'sha256' | 'sha512'; salt?: string }): boolean ``` - `generateKey` defaults to 32 characters from A-Z, a-z and 0-9, with no prefix. It throws a `RangeError` for a length that isn't a positive integer or an alphabet without 2 to 256 characters and at least 2 distinct. - `hashKey` returns a hex digest of `key + salt`, SHA-256 by default. - `validateKey` hashes `key` and compares it to `storedHash` in constant time. :::warning A manager hashes its configured `salt` with SHA-256 before use, so these functions give different hashes from a salted manager for the same salt. To match a manager, call its own [`hashKey()`](/docs/api-reference/utilities) and `validateKey()`. ::: ```typescript import { generateKey, hashKey } from 'keypal' const key = generateKey({ prefix: 'sk_test_' }) const keyHash = hashKey(key) ``` ## Key extraction ```typescript extractKeyFromHeaders( headers: Record | Headers, options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string } ): string | null hasApiKey( headers: Record | Headers, options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string } ): boolean ``` Defaults: `headerNames: ["authorization", "x-api-key"]`, `extractBearer: true`, no prefix. The rules match the manager's [`extractKey()`](/docs/api-reference/utilities), including preferring a value that starts with `prefix`. ## Expiry and status ```typescript isExpired(expiresAt: Date | string | null | undefined, now?: number): boolean getExpirationTime(expiresAt: Date | string | null | undefined): Date | null getKeyStatus( record: { enabled?: boolean | null; expiresAt?: Date | string | null; revokedAt?: Date | string | null }, now?: number ): 'active' | 'revoked' | 'expired' | 'disabled' ``` - `isExpired` is `true` when `expiresAt` is at or before `now` (default `Date.now()`), or is a non-empty value that can't be parsed. Unset, `null`, or an empty string is never expired. - `getExpirationTime` returns `expiresAt` as a `Date`, or `null` when unset. It doesn't validate the string. - `getKeyStatus` is the rule `verify` uses: revoked wins over expired, and expired over disabled. ```typescript import { getKeyStatus } from 'keypal' const status = getKeyStatus(record) // 'active' | 'revoked' | 'expired' | 'disabled' ``` ## Scope checks ```typescript hasScope(scopes: string[] | undefined, required: string, options?: ScopeCheckOptions): boolean hasAnyScope(scopes: string[] | undefined, required: string[], options?: ScopeCheckOptions): boolean hasAllScopes(scopes: string[] | undefined, required: string[], options?: ScopeCheckOptions): boolean ``` These take a scope array, not a record. `ScopeCheckOptions` is `{ resource?, resources?, impliedScopes? }`; see [Permissions](/docs/api-reference/permissions). Unlike the manager methods, nothing is filled in from a record or config. ```typescript import { hasScope } from 'keypal' hasScope(record.scopes, 'write', { resource: 'project:123', resources: record.resources, impliedScopes: { admin: ['read', 'write'] }, }) ``` ### Deprecated resource variants `hasScopeWithResources`, `hasAnyScopeWithResources` and `hasAllScopesWithResources` take `(globalScopes, resources, required, options?)`. They are deprecated; pass `resources` in the options instead: ```typescript // Deprecated hasScopeWithResources(scopes, resources, 'read', { resource: 'project:123' }) // Use hasScope(scopes, 'read', { resources, resource: 'project:123' }) ``` ## Resources `ResourceBuilder` and `createResourceBuilder()` build `resources` maps. See [ResourceBuilder](/docs/utilities/resource-builder). ## Caches `MemoryCache` and `RedisCache` implement the `Cache` type that the `cache` option accepts. ```typescript new MemoryCache(options?: { maxSize?: number; cleanupInterval?: number }) new RedisCache(client: RedisClient) ``` `MemoryCache` holds up to `maxSize` entries (default 10,000), evicting the oldest when full, and removes expired entries every `cleanupInterval` ms (default 60,000). It also has `clear()`, `cleanup()`, `dispose()` (stops the cleanup timer) and a `size` getter. See [Caching](/docs/concepts/caching). ## Errors `ApiKeyErrorCode` and `createApiKeyError()` are covered in [Error handling](/docs/utilities/error-handling).