Example 1
Example 1
import { AuthPlugin, authMiddleware, requireAuth, requireRole } from '@setu-ts/auth-plugin'; app.register(AuthPlugin({ jwt: { secret: process.env.JWT_SECRET! }, rbac: { roles: { admin: { permissions: ['*'], inherits: ['user'] }, user: { permissions: ['users:read'] }, }, }, })); // Priority 300 is the band ARCHITECTURE.md §10 reserves for authentication; // a bare add() would take the kernel default of 500 and run after it. app.middleware.add(authMiddleware(), { priority: 300 }); app.router.get('/protected', { middleware: [requireAuth()], handler });
Thrown by PasswordHasher.verify when the stored value is not a
well-formed pbkdf2$<iterations>$<salt>$<hash> string.
-
name: string
Discriminant for consumers that cannot use
instanceofacross realms.
Single-process access-token revocation store with bounded lazy expiry work.
-
isRevoked(jti: string): Promise<boolean>
Return whether an access-token identifier is currently revoked.
-
revoke(): Promise<void>jti: string,expiresAt: number
Record an access-token identifier as revoked until its expiry timestamp.
In-memory implementation of RateLimitStore.
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
In-memory implementation of RefreshTokenStore.
-
get(jti: string): Promise<RefreshTokenRecord | null>
Retrieve a record by jti; returns null if missing or expired. A revoked record is still returned so the caller can distinguish replay of a rotated token from an unknown token.
-
revoke(jti: string): Promise<void>
Revoke a token by jti.
-
revokeFamily(jti: string): Promise<readonly RefreshTokenRecord[]>
Revoke every refresh token in the requested token's family.
-
rotate(): Promise<IRefreshTokenRotation>jti: string,successor: RefreshTokenRecord
Atomically consume a live refresh token and persist its successor.
-
save(record: RefreshTokenRecord): Promise<void>
Store or update a refresh token record.
Password hasher using PBKDF2-SHA256 via Web Crypto.
-
hash(secret: string): Promise<string>
Hash a secret (password) with a random salt.
-
verify(): Promise<boolean>stored: string,secret: string
Verify a secret against a stored hash.
Redis-backed rate limit store implementation.
-
disconnect(): Promise<void>
Close the Redis connection (calls QUIT).
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
Refresh token service implementing token rotation and revocation.
-
issue(principal: IPrincipal): Promise<TokenPair>
Issue a new access + refresh token pair for the given principal.
-
refresh(refreshToken: string): Promise<TokenPair | null>
Refresh a token pair: verify the refresh token, revoke its jti, and issue a new pair (rotation). Returns null if the token is invalid, expired, tampered with, not a refresh token, or already revoked (replay).
-
revoke(refreshToken: string): Promise<boolean>
Revoke a refresh token (logout). Returns true if a live record was found and revoked; false when the token does not verify or no live record exists (missing, expired, or already revoked).
Authentication middleware that runs passive strategies and populates ctx.request.user. Always calls next() - it authenticates only, does not authorize.
AuthPlugin factory.
Default rate-limit key, in order of preference:
Guard that allows public access (always continues). Useful for explicitly marking routes as public when auth middleware is global.
Rate limiting middleware factory.
Guard that requires all of the specified permissions. Returns 401 if no principal, 403 if any missing.
Guard that requires any of the specified roles. Returns 401 if no principal, 403 if none match.
Guard that requires authentication. Returns 401 if no principal.
Guard that requires a specific permission. Returns 401 if no principal, 403 if insufficient permission.
Guard that requires a specific role. Returns 401 if no principal, 403 if insufficient role.
API key configuration options.
-
header: string
Header name for API key (default: 'X-API-Key').
-
validate: (key: string) => Promise<IPrincipal | null>
Callback to validate the API key and return a principal. Return
nullif the key is invalid.
Auth plugin configuration options.
-
apiKey: ApiKeyOptions
API key configuration. Optional.
-
jwt: JwtOptions
JWT configuration. Required.
-
local: LocalOptions
Local credentials configuration. Optional.
-
rbac: RbacConfig
RBAC configuration. When absent, AuthPlugin registers JWT authentication only and does not provide the authorization capability.
-
session: SessionAuthOptions
Session authentication configuration. When present, the plugin appends an internal session strategy after the API-key strategy and requires the
sessioncapability (SessionPlugin) to be registered. -
strategies: readonly IAuthStrategy[]
Caller-supplied strategies, appended after every built-in in declaration order. A strategy whose
namecollides with any other strategy in the assembled chain makesregister()throw.
Store for access-token identifiers revoked before their JWT expiry.
-
isRevoked(jti: string): Promise<boolean>
Return whether an access-token identifier is currently revoked.
-
revoke(): Promise<void>jti: string,expiresAt: number
Record an access-token identifier as revoked until its expiry timestamp.
Authentication service that coordinates strategies and provides credential verification for login flows.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Run configured passive strategies to authenticate a request.
-
verifyCredentials(credentials: { readonly identifier: string; readonly secret: string; }): Promise<IPrincipal | null>
Verify credentials for a login flow (e.g., username/password).
Authentication strategy interface. Implementations extract credentials
from a request and return a principal, or null if the strategy
does not apply.
-
authenticate(request: IRequest): Promise<IPrincipal | null>
Attempt to authenticate the request.
-
name: string
Strategy name for identification.
JWT sign/verify service.
-
decode<T = Readonly<Record<string, unknown>>>(token: string): T | null
Decodes a token without verifying it. Never trust the result for authorization decisions.
-
sign(): Promise<string>payload: Readonly<Record<string, unknown>>,options?: JwtSignOptions
Signs a payload into a JWT.
-
verify<T = Readonly<Record<string, unknown>>>(token: string): Promise<T>
Verifies a token's signature and validity window.
The authenticated identity attached to a request by authentication middleware.
-
claims: Readonly<Record<string, unknown>>
Additional claims from the credential.
-
id: string
Stable subject identifier.
-
permissions: readonly string[]
Permission names held by the principal.
-
roles: readonly string[]
Role names held by the principal.
JWT configuration options.
-
accessTokenRevocationStore: IAccessTokenRevocationStore
Optional shared store that rejects revoked typed access credentials. Supply the same instance to
RefreshTokenServicefor logout invalidation. -
algorithm: "HS256" | "RS256"
Algorithm to use. Inferred from key material if omitted.
-
audience: string
Expected audience for verification.
-
header: string
Header name for token extraction (default: 'authorization').
-
issuer: string
Expected issuer for verification.
-
privateKey: string
Private key for RS256 signing (PEM format). Required if HS256 secret not provided.
-
publicKey: string
Public key for RS256 verification (PEM format). Required for RS256 verification.
-
scheme: string
Token scheme prefix (default: 'bearer').
-
secret: string | Uint8Array
Secret key for HS256 algorithm. Required if RS256 keys not provided.
Options accepted when signing a JWT.
-
audience: string
Token audience.
-
expiresIn: string
Token lifetime (e.g.
"1h","7d"). -
issuer: string
Token issuer.
Local (credentials) configuration options.
-
verify: () => Promise<IPrincipal | null>identifier: string,secret: string
Callback to verify credentials (e.g., username/password). Return
nullif credentials are invalid.
Options for rate limiting middleware.
-
exclude: readonly PathPattern[]
Paths exempted from the limiter, matched against
IRequest.path. A string is an EXACT match; aRegExpis tested against the path. -
keyGenerator: (ctx: IRequestContext) => string
Key generator function. Defaults to
defaultRateLimitKey, which prefers the authenticated principal, then the client IP published byipSecurityMiddleware, thenIRequest.ip, and only then'anonymous'. -
max: number
Max requests per window per key.
-
message: string
Message returned in the 429 body.
-
standardHeaders: boolean
Emit standard RateLimit-* headers (default: true).
-
store: RateLimitStore
Custom store implementation. If omitted, a MemoryRateLimitStore is built lazily.
-
windowMs: number
Time window in milliseconds.
Result of incrementing a rate limit counter.
-
count: number
Request count in the current window.
-
resetTime: number
Absolute timestamp (ms since epoch) when the window resets.
Store interface for rate limiting.
-
increment(): Promise<RateLimitResult>key: string,windowMs: number
Increment the counter for the given key within its window. Creates the window if it does not exist.
-
reset(key: string): Promise<void>
Reset the counter for the given key.
RBAC configuration for role hierarchy and permissions.
-
roles: Readonly<Record<string, RoleDefinition>>
Role definitions keyed by role name.
Options for constructing a RefreshTokenService.
-
accessToken: { readonly expiresIn?: string; readonly audience?: string; readonly issuer?: string; }
Optional access token options (passed through to jwt.sign).
-
accessTokenRevocationStore: IAccessTokenRevocationStore
Optional shared store for invalidating paired access tokens at logout or refresh-token replay. Requires
accessToken.expiresInso entries remain bounded. -
jwt: IJwtService
The JWT service used to sign/verify tokens.
-
refreshTokenExpiresIn: string
Refresh token lifetime (default: '7d').
-
runtime: IRuntimeServices
Runtime services for random bytes and clock.
-
store: RefreshTokenStore
The store backing refresh tokens.
A refresh token record stored on the server.
-
accessTokenExpiresAt: number
Absolute expiry timestamp for the paired access token.
-
accessTokenJti: string
Identifier of the paired access token, when issued by the current service.
-
expiresAt: number
Absolute expiry timestamp (ms since epoch).
-
familyId: string
Family identifier shared by a rotated refresh-token lineage.
-
jti: string
Unique token identifier (from JWT jti claim).
-
principal: IPrincipal
Snapshot of the principal at issue time.
-
principalId: string
Principal ID the token belongs to.
-
revoked: boolean
Whether the token has been revoked.
Store interface for refresh tokens.
-
get(jti: string): Promise<RefreshTokenRecord | null>
Retrieve a record by jti; returns null if missing or expired. A revoked record is still returned so the caller can distinguish replay of a rotated token from an unknown token.
-
revoke(jti: string): Promise<void>
Revoke a token by jti.
-
revokeFamily(jti: string): Promise<readonly RefreshTokenRecord[]>
Revoke every refresh token in the requested token's family.
-
rotate(): Promise<IRefreshTokenRotation>jti: string,successor: RefreshTokenRecord
Atomically consume a live refresh token and persist its successor.
-
save(record: RefreshTokenRecord): Promise<void>
Store or update a refresh token record.
Role definition for RBAC configuration.
-
inherits: readonly string[]
Role names this role inherits from (transitive).
-
permissions: readonly string[]
Permissions granted by this role.
Session authentication configuration options.
-
toPrincipal: (view: SessionView) => IPrincipal | null
Maps an opened session to the principal it carries. Return
nullwhen the session holds no identity — the strategy chain then continues.
A pair of access + refresh tokens issued together.
-
accessToken: string
Short-lived access token.
-
refreshToken: string
Refresh token (signed JWT with type:'refresh' and jti).
| { readonly record: RefreshTokenRecord | null; readonly rotated: false; }
Result of atomically rotating one refresh token into its successor.
The operational paths RateLimitOptions.exclude exempts by
default: the framework's health, metrics and OpenAPI routes plus the
interactive docs. The same six tenantMiddleware exempts, deliberately —
one list to remember rather than two.
The namespace RedisRateLimitStore prepends to every key when no
keyPrefix is supplied.
Usage
import * as Authentication_and_authorization_plugin_for_Setu_TS___Provides_JWT_and_API_key_authentication__local_credentials_verification__and_RBAC_authorization_with_role_hierarchy__ from "auth-plugin/src/index.ts";