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
generateKeydefaults to 32 characters from A-Z, a-z and 0-9, with no prefix. It throws aRangeErrorfor a length that isn’t a positive integer or an alphabet without 2 to 256 characters and at least 2 distinct.hashKeyreturns a hex digest ofkey + salt, SHA-256 by default.validateKeyhasheskeyand compares it tostoredHashin 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'
isExpiredistruewhenexpiresAtis at or beforenow(defaultDate.now()), or can’t be parsed. Unset ornullis never expired.getExpirationTimereturnsexpiresAtas aDate, ornullwhen unset. It doesn’t validate the string.getKeyStatusis the ruleverifyuses: 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.