ApiKey.ts overview
API keys: long-lived keys shown once and verified by their SHA-256 digest, with expiry, enabling, per-resource permissions, use quotas, metadata and an optional per-key rate limit through the RateLimiter. Only the digest is stored.
Exports Grouped by Category
- utils
- ApiKey (interface)
- ApiKeyConfig (interface)
- ApiKeyCreateOptions (interface)
- ApiKeyCreateResult (interface)
- ApiKeyError (class)
- ApiKeyRefusal (type alias)
- ApiKeyService (class)
- ApiKeyStore (class)
- ApiKeyUpdate (interface)
- ApiKeyUse (interface)
- ApiKeyVerifyResult (interface)
- applyApiKeyUse
- hashApiKey
- make
utils
ApiKey (interface)
Persistent API key record.
keyHash holds the sha256 hex digest of the full plaintext key (prefix included) — the plaintext itself is NEVER stored. start keeps the first six characters of the key’s random portion so dashboards can display a recognizable fragment without revealing the secret.
Signature
export interface ApiKey {
readonly id: string
/** Human-readable label (e.g. "CI deploy key") */
readonly name?: string
/** Visible key prefix the plaintext key starts with (e.g. "myapp_") */
readonly prefix?: string
/** First 6 characters of the key's secret portion, for display */
readonly start: string
/** sha256 hex digest of the full plaintext key — never the plaintext */
readonly keyHash: string
readonly userId: string
readonly enabled: boolean
/** Unix ms timestamp after which the key is rejected; undefined = never */
readonly expiresAt?: number
/** Unix ms timestamp of the last successful verification */
readonly lastUsedAt?: number
/** resource → allowed actions; undefined = no permission restrictions */
readonly permissions?: Record<string, readonly string[]>
readonly metadata: Types.JsonObject
/** Remaining uses; decremented on each successful verify. undefined = unlimited */
readonly remaining?: number
/**
* Refill amount applied per elapsed `refillInterval`. When set alongside
* `refillInterval`, each successful verify lazily tops up `remaining` by
* `floor((now - lastRefillAt) / refillInterval) * refillAmount`, capped at
* `refillMax`. Only meaningful when `remaining` is also set.
*/
readonly refillAmount?: number
/** Interval in milliseconds between refill ticks */
readonly refillInterval?: number
/** Maximum value `remaining` can be refilled to; defaults to initial `remaining` at creation */
readonly refillMax?: number
/** Unix ms timestamp of the last refill tick baseline */
readonly lastRefillAt?: number
/** Per-key rate limit configuration, enforced by `verifyWithRateLimit` */
readonly rateLimit?: {
readonly maxRequests: number
readonly windowMs: number
}
readonly createdAt: number
readonly updatedAt: number
}
ApiKeyConfig (interface)
API key service configuration
Signature
export interface ApiKeyConfig {
/** Prefix prepended to generated keys when none is supplied (default: "ak_") */
readonly defaultPrefix?: string
/** Number of random bytes in the secret portion, base64url-encoded (default: 32) */
readonly keyLength?: number
/** Default key lifetime in milliseconds; undefined = keys never expire */
readonly defaultExpiresIn?: number
/** Maximum number of keys a single user may hold (default: 10) */
readonly maxKeysPerUser?: number
}
ApiKeyCreateOptions (interface)
Options for creating an API key
Signature
export interface ApiKeyCreateOptions {
readonly name?: string
/** Overrides the configured default prefix for this key */
readonly prefix?: string
/** Lifetime in milliseconds from now; overrides `defaultExpiresIn` */
readonly expiresIn?: number
readonly permissions?: Record<string, readonly string[]>
readonly metadata?: Types.JsonObject
/** Number of allowed uses; undefined = unlimited */
readonly remaining?: number
/** Number of uses to restore per `refillInterval` */
readonly refillAmount?: number
/** Milliseconds between refill ticks */
readonly refillInterval?: number
/** Cap for refill; defaults to `remaining` at creation time */
readonly refillMax?: number
readonly rateLimit?: {
readonly maxRequests: number
readonly windowMs: number
}
}
ApiKeyCreateResult (interface)
Result of creating an API key. key is the full plaintext key (prefix + secret) and is shown exactly once — it is never stored.
Signature
export interface ApiKeyCreateResult {
readonly key: string
readonly apiKey: ApiKey
}
ApiKeyError (class)
API key error
Signature
declare class ApiKeyError
ApiKeyRefusal (type alias)
Why a key was refused, as ApiKeyVerifyResult.reason names it:
invalid: no key has that digest.disabled,expired: the key exists but is switched off or past itsexpiresAt.exhausted: the key has noremaininguses left.missing-permissions: the key lacks a required permission.rate-limited: the key is over its ownrateLimit(verifyWithRateLimitonly).
Signature
type ApiKeyRefusal = "invalid" | "disabled" | "expired" | "exhausted" | "missing-permissions" | "rate-limited"
ApiKeyService (class)
API key service. Requires ApiKeyStore, RateLimiter and UserStore (a key verifies only while its owner exists and is neither banned nor SCIM-deactivated).
Signature
declare class ApiKeyService
ApiKeyStore (class)
Storage interface for API keys
Signature
declare class ApiKeyStore
ApiKeyUpdate (interface)
Fields of an API key that may be changed after creation.
Signature
export interface ApiKeyUpdate {
readonly name?: string
readonly enabled?: boolean
readonly expiresAt?: number
readonly permissions?: Record<string, readonly string[]>
readonly metadata?: Types.JsonObject
readonly remaining?: number
readonly refillAmount?: number
readonly refillInterval?: number
readonly refillMax?: number
/** Override the refill baseline timestamp (useful for testing and admin corrections) */
readonly lastRefillAt?: number
readonly rateLimit?: {
readonly maxRequests: number
readonly windowMs: number
}
}
ApiKeyUse (interface)
One spend of an API key, applied by ApiKeyStore’s recordUse.
refill is the quota top-up due at usedAt, computed by the service from the record it read: the store applies it only while the key’s lastRefillAt still equals from, so two verifies that both saw a refill due add it once.
Signature
export interface ApiKeyUse {
/** Unix ms time of the use: the new `lastUsedAt` and `updatedAt` */
readonly usedAt: number
readonly refill?: {
/** The `lastRefillAt` the refill was computed from */
readonly from: number
/** The new `lastRefillAt` */
readonly to: number
/** Uses to add to `remaining` before the spend */
readonly amount: number
/** Cap on `remaining` after the top-up; undefined = no cap */
readonly max?: number
}
}
Since v0.6.0
ApiKeyVerifyResult (interface)
Result of verifying an API key. Verification failures are reported as { valid: false, error, reason } rather than typed failures so callers can treat a bad key as a normal (unauthenticated) outcome.
Signature
export interface ApiKeyVerifyResult {
readonly valid: boolean
readonly apiKey?: ApiKey
/** A refusal's message, for the server log; an HTTP answer never carries it. */
readonly error?: string
/** A refusal's cause, to branch on (the HTTP tier's `429` for `rate-limited`). */
readonly reason?: ApiKeyRefusal
/** For a `rate-limited` refusal: how long until the key's own limit lets it through. */
readonly retryAfter?: Duration.Duration
}
applyApiKeyUse
The record recordUse stores for use of key, or None when the key may not be spent: ApiKeyStore’s recordUse contract as a pure function, for a store that can run it inside one atomic step of its own (a lock, a compare-and-set loop, a single-threaded actor).
Signature
declare const applyApiKeyUse: (key: ApiKey, use: ApiKeyUse) => Option.Option<ApiKey>
Since v0.6.0
hashApiKey
SHA-256 hex digest of a plaintext API key. Exposed so stores/tests can compute lookup hashes without duplicating the hashing scheme.
Signature
declare const hashApiKey: (token: string) => Effect.Effect<string, never, Digest.Digest>
make
Create an API key service
Signature
declare const make: (
config?: ApiKeyConfig
) => Effect.Effect<
typeof ApiKeyService.Service,
never,
ApiKeyStore | RateLimiter | UserStore | SecureRandom.SecureRandom | Digest.Digest
>