Skip to the content
Krizaka TS
Krizaka TS

@krizaka/api-keys

API keys created, rotated, revoked and authenticated; shown once, only a hash kept.

Install

bashTerminal
npm install @krizaka/api-keys

Also published as subpath exports: @krizaka/api-keys/testkit.

API keys for every Krizaka product. A key is <prefix>_<publicId>_<random>: the public id finds the record, only a SHA-256 of the random part is stored, the whole key is shown once (when it is created or rotated), scopes and rules are data, a key must end, a rotated key keeps working for a grace period, a revoked one stops at once, and every refusal has a stable code.

import { createApiKeys, pgApiKeyStore, apiKeysMigration } from "@krizaka/api-keys";

await db.query(apiKeysMigration("accounts")); // once, in your migrations
const keys = createApiKeys({ store: pgApiKeyStore(query), clock: { now: () => new Date() }, rules: { prefix: "yzk", scopes: ["checks:write", "reports:read"], secretBytes: 24, maxExpiryDays: 365, rotationGraceHours: 24, lastUsedEveryMinutes: 5 } });

const { key } = await keys.create(owner, { name: "Mon ERP", scopes: ["checks:write"], expiresInDays: 90 }, { maxActive: 5 });
const auth = await keys.authenticate(request.headers.get("authorization"), "checks:write"); // { ok: true, key } | { ok: false, code }

What a product decides stays in the product: its scopes, how many keys a plan holds (maxActive), its rate limit, its audit trail, its HTTP answers. Any store runs the contract kit: apiKeyStoreContract from @krizaka/api-keys/testkit.

Exports

The 17 names the package exports, read from its types.

NameKindWhat it is
API_KEY_CODEconstant
ApiKeyCodetype
ApiKeyErrorclass
ApiKeyRecordtype
ApiKeyRulestypeThe API-KEY ports (ADR-0011).
ApiKeystype
apiKeysMigrationfunctionThe table of API keys.
ApiKeyStoretype
ApiKeyViewtypeWhat a person sees of a key: never the hash, never the secret.
Authenticatedtype
Clocktype
createApiKeysfunctionAPI keys: created, authenticated, rotated, revoked.
Createdtype
memoryApiKeyStorefunctionAn in-memory store: the tests' adapter, and the reference the contract is written against.
NewKeytype
pgApiKeyStorefunctionPostgreSQL adapter (table api_keys, migration 0021).
QuerytypeThe SQL runner this adapter needs: the app passes its own (no import from the app here).

@krizaka/api-keys/testkit

NameKindWhat it is
apiKeyStoreContractfunctionWhat every ApiKeyStore adapter must do: the same behaviour behind the same port.

Package

Version on npm0.1.0 (npm)
LicenceApache-2.0
Node.js>=22
Dependenciesdate-fns ^4.4.0
Peer dependenciesvitest >=4
Sourceapi-keys

Changelog

0.1.0

Minor changes

  • First release, extracted from Yomizaka: create, rotate (with a grace period), revoke and authenticate API keys behind a store port; memory and PostgreSQL stores, the migration, and the store contract kit.

On this page