---
title: Standalone functions
description: 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

```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<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()`](/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 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.

```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).
