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

Standalone functions

keypal functions you can call without a manager

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

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.
import { generateKey, hashKey } from 'keypal'

const key = generateKey({ prefix: 'sk_test_' })
const keyHash = hashKey(key)

Key extraction

extractKeyFromHeaders(
  headers: Record<string, string | undefined> | Headers,
  options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string }
): string | null

hasApiKey(
  headers: Record<string, string | undefined> | 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(), including preferring a value that starts with prefix.

Expiry and status

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 can’t be parsed. Unset or null 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.
import { getKeyStatus } from 'keypal'

const status = getKeyStatus(record) // 'active' | 'revoked' | 'expired' | 'disabled'

Scope checks

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. Unlike the manager methods, nothing is filled in from a record or config.

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:

// 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.

Caches

MemoryCache and RedisCache implement the Cache type that the cache option accepts.

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.

Errors

ApiKeyErrorCode and createApiKeyError() are covered in Error handling.

Was this page helpful?