toklyn
v0.6.0
Published
Access and refresh token sessions with rotation, reuse detection and pluggable storage.
Maintainers
Readme
toklyn
Access and refresh token sessions with rotation, reuse detection and pluggable storage.
The core of toklyn: short-lived JWT access tokens, opaque refresh tokens stored as hashes, server-side sessions, rotation on every refresh and session revocation when a used token is presented again.
Install
npm install toklynNode.js 22.12 or later, or any runtime with Web Crypto. ESM and CommonJS.
Usage
import { MemorySessionStore, accessTokensFromEnv, createAuth } from 'toklyn';
interface AppClaims {
role: string;
}
const auth = createAuth<AppClaims>({
// HS256 from TOKLYN_SECRET (at least 32 bytes; generate with `openssl rand -base64 32`).
...accessTokensFromEnv(),
sessions: new MemorySessionStore(),
accessTokenTtlSeconds: 5 * 60,
refreshTokenTtlSeconds: 7 * 24 * 60 * 60,
sessionMaxAgeSeconds: 30 * 24 * 60 * 60,
});
const tokens = await auth.createSession({
subject: user.id,
claims: { role: user.role },
});
const claims = await auth.verifyAccessToken(tokens.accessToken);
const rotated = await auth.refresh({ refreshToken: tokens.refreshToken });
await auth.revokeSession(claims.sid);Entry points
| Import | Contents |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| toklyn | createAuth, accessTokensFromEnv, JWT signer and verifier, createJwks and RemoteJwksAccessTokenVerifier, in-memory stores, ToklynError, types and store contracts |
| toklyn/http | createToklynHttp: framework-neutral login, refresh, logout and authentication responses, in bearer or cookie mode; httpOptionsFromEnv; verify-only createToklynResource and jwksResponse |
| toklyn/testing | sessionStoreContract and revocationStoreContract, Vitest suites for custom stores |
| toklyn/test-utils | createTestAuth and createTestClock for testing your app with any test runner |
Documentation
- How it works
- Configuration
- Signing keys and key rotation
- Publishing keys (JWKS) and verifying on other services
- HTTP integration: bearer and cookie mode
- Storage and custom stores
- Testing your app
- Errors
- Security model
Related packages
@toklyn/express: Express middleware and route handlers@toklyn/fastify: Fastify hooks and route handlers@toklyn/nest: NestJS module, guard and decorators@toklyn/next: Next.js App Router helpers@toklyn/store: PostgreSQL, MySQL/MariaDB, SQLite, MongoDB and Redis (Valkey, Upstash) stores
