Skip to content

Documentation · IGNIS

Authentication Reference ​

Every option, binding key, class, and method the Authentication component exposes. See the Overview for the guided introduction.

Files:

Find what you need ​

You want toGo to
See how the pieces fit togetherArchitecture
Look up a binding key or option fieldBinding keys, Option interfaces
Check what IAuthUser / IAuthService requireIAuthUser / IJWTTokenPayload, IAuthService
Understand the JWS/JWKS/Basic class hierarchyService class hierarchy
Register or resolve a strategy programmaticallyStrategy registry
See exactly what the built-in /auth controller buildsController factory
Find a file on diskFile structure

Import paths ​

typescript
import {
  // Component + registry
  AuthenticateComponent,
  AuthenticateBindingKeys,
  Authentication,
  AuthenticationFieldCodecs,
  AuthenticationModes,
  AuthenticationTokenTypes,
  AuthenticationStrategyRegistry,
  ServiceAssertion,

  // JOSE standards + constants
  JOSEStandards,
  JWKSModes,
  JWKSKeyDrivers,
  JWKSKeyFormats,

  // Strategies
  JWSAuthenticationStrategy,
  JWKSIssuerAuthenticationStrategy,
  JWKSVerifierAuthenticationStrategy,
  BasicAuthenticationStrategy,
  ServiceAuthenticationStrategy,

  // Services
  AbstractBearerTokenService,
  JWSTokenService,
  JWKSIssuerTokenService,
  JWKSVerifierTokenService,
  BasicTokenService,

  // Controllers
  AuthControllerFactory,
  JWKSController,
  authenticate,

  // Entity column helpers
  AuthModelColumns,
  UserStatuses,
  UserTypes,
  RoleStatuses,
} from '@venizia/ignis';

import type {
  TAuthenticationRestOptions,
  TJWTTokenServiceOptions,
  IJWSTokenServiceOptions,
  IJWKSIssuerOptions,
  IJWKSVerifierOptions,
  TJWKSTokenServiceOptions,
  TBasicTokenServiceOptions,
  IServiceAuthOptions,
  IServiceAssertionClaims,
  TServiceCallerEntry,
  IAuthenticateOptions,
  IAuthUser,
  IJWTTokenPayload,
  IPayloadFieldCodec,
  IAuthService,
  IAuthenticationStrategy,
  TDefineAuthControllerOpts,
  TAuthStrategy,
  TAuthMode,
  TGetTokenExpiresFn,
  TJWKSAlgorithm,
  TJWKSKeyDriver,
  TJWKSKeyFormat,
  TJOSEStandard,
  TJWKSMode,
  TPermissionOptions,
  TPermissionCommonColumns,
  TPolicyDefinitionOptions,
  TPolicyDefinitionCommonColumns,
} from '@venizia/ignis';

Architecture ​

Application.preConfigure()
  ├── bind JWT_OPTIONS (TJWTTokenServiceOptions, discriminated on `standard`)
  ├── bind BASIC_OPTIONS / SERVICE_OPTIONS / REST_OPTIONS
  ├── this.component(AuthenticateComponent)
  └── AuthenticationStrategyRegistry.register() -- manual, after the component

AuthenticateComponent.binding()
  ├── switch on jwtOptions.standard
  │     ├── JWS  -> defineJWSAuth()  -> registers JWSTokenService
  │     └── JWKS -> defineJWKSAuth() -> switch on mode
  │                   ├── issuer   -> JWKSIssuerTokenService + JWKSController (/certs)
  │                   └── verifier -> JWKSVerifierTokenService
  ├── defineBasicAuth() -> registers BasicTokenService (if basicOptions bound)
  ├── defineServiceAuth() -> ServiceAssertionVerifierService + the `service` strategy
  │                          (if serviceOptions bound; with `keys` also the signer + /certs)
  ├── defineControllers() -> registers AuthController (if useAuthController: true)
  └── defineOAuth2() -> stub, not implemented

Bearer token service hierarchy:
  AbstractBearerTokenService (extractCredentials, verify, generate, encryptPayload/decryptPayload)
    ├── JWSTokenService (symmetric HS256)
    └── AbstractJWKSTokenService (lazy ensureInitialized() + retry-on-failure)
          ├── JWKSIssuerTokenService (sign + verify + getJWKS/getJWKSAsync)
          └── JWKSVerifierTokenService (verify only, via createRemoteJWKSet())

Tech stack

TechnologyPurpose
joseJWT signing (SignJWT), verification (jwtVerify), JWKS (createRemoteJWKSet, exportJWK, importPKCS8, importSPKI, importJWK). Loaded once per process, never at import. With JWT or service authentication configured, the component loads it at boot, so a missing jose fails the boot
@venizia/ignis-helpersAES payload encryption, BaseHelper/BaseService, getError, HTTP result codes
Hono middlewareRoute-level integration via createMiddleware from hono/factory
node:fs/promisesAsync key file reads for JWKS

Component methods ​

AuthenticateComponent.binding() runs five private configuration methods and one public stub:

MethodPurpose
defineJWSAuth(opts)Validates jwtSecret, getTokenExpiresFn and claims, binds IJWSTokenServiceOptions to JWT_OPTIONS, registers JWSTokenService
defineJWKSAuth(opts)Switches on mode.
Issuer: validates keys/format/kid/getTokenExpiresFn/claims, binds to JWKS_OPTIONS, registers JWKSIssuerTokenService + JWKSController.
Verifier: validates jwksUrl, claims and verify.algorithms, binds to JWKS_OPTIONS, registers JWKSVerifierTokenService
defineServiceAuth(opts)Validates name and resolvePrincipal, registers the verifier and the service strategy. With keys present it also registers the signer and mounts the certs route. Absent options: does nothing
defineBasicAuth(opts)Validates verifyCredentials presence, registers BasicTokenService. Skips (debug log) if basicOptions not bound
defineControllers(opts)Requires jwtOptions when useAuthController: true. Calls AuthControllerFactory.build() and registers the generated controller
defineOAuth2()Public stub, called during binding(), performs no action - not yet implemented

NOTE

The component reads the discriminated union from JWT_OPTIONS. It then re-binds only the inner options object - IJWSTokenServiceOptions, or IJWKSIssuerOptions/IJWKSVerifierOptions - to JWKS_OPTIONS or back to JWT_OPTIONS. The token service resolves it with a plain @inject.

Binding keys ​

ConstantKey stringTypeRequiredDefault
AuthenticateBindingKeys.REST_OPTIONS@app/authenticate/rest-optionsTAuthenticationRestOptionsNo{ useAuthController: false }
AuthenticateBindingKeys.JWT_OPTIONS@app/authenticate/jwt-optionsTJWTTokenServiceOptionsConditional--
AuthenticateBindingKeys.JWKS_OPTIONS@app/authenticate/jwks-optionsIJWKSIssuerOptions | IJWKSVerifierOptionsInternalBound by the component from JWT_OPTIONS
AuthenticateBindingKeys.BASIC_OPTIONS@app/authenticate/basic-optionsTBasicTokenServiceOptionsConditional--
AuthenticateBindingKeys.SERVICE_OPTIONS@app/authenticate/service-optionsIServiceAuthOptionsConditional--
AuthenticateBindingKeys.SERVICE_CERTS_PATH@app/authenticate/service-certs-pathstringInternalBound by the component from serviceOptions.rest.path

IMPORTANT

At least one of JWT_OPTIONS, BASIC_OPTIONS or SERVICE_OPTIONS must be bound, or AuthenticateComponent.binding() throws. A service that only VERIFIES assertions needs neither jwt nor basic.

Option interfaces ​

TJWTTokenServiceOptions ​

Discriminated union on standard:

typescript
type TJWTTokenServiceOptions =
  | { standard: typeof JOSEStandards.JWS; options: IJWSTokenServiceOptions }
  | { standard: typeof JOSEStandards.JWKS; options: TJWKSTokenServiceOptions };

type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions; // discriminated on `mode`

IJWSTokenServiceOptions ​

OptionTypeDefaultRequiredDescription
jwtSecretstring--YesSecret for signing and verifying the JWT signature. At least 32 bytes (UTF-8): a shorter one refuses the boot
getTokenExpiresFnTGetTokenExpiresFn--YesReturns token expiration in seconds
applicationSecretstring--NoEnables AES payload field encryption when set
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload encryption
headerAlgorithmstring'HS256'NoJWT signing algorithm
fieldCodecsIPayloadFieldCodec[][]NoCustom serialize/deserialize per field name
verifyIJWTVerifyOptions--NoFurther checks on verify: subject, algorithms, clockTolerance, maxTokenAge, typ, requiredClaims. issuer and audience are claims now. algorithms unset pins the algorithm the service signs with
claims{ issuer: string; audience?: string | string[] }--Yesissuer is required: stamped as iss on every issued token and required on every verified one. audience is optional: set, it is stamped as aud and required; absent, no aud is stamped and none is checked. A configured value WINS over one supplied in the payload. No other key is accepted

WARNING

jwtSecret is mandatory - the component throws if it's missing, equals the placeholder 'unknown_secret', or is shorter than 32 bytes. applicationSecret is optional. When you omit it, the JWT payload stays standard plaintext. Standard fields (iss, sub, aud, jti, nbf, exp, iat) are never encrypted either way.

IJWKSIssuerOptions ​

OptionTypeDefaultRequiredDescription
modetypeof JWKSModes.ISSUER--YesMust be 'issuer'
algorithmTJWKSAlgorithm--Yes'ES256', 'RS256', or 'EdDSA'
keys.driverTJWKSKeyDriver--Yes'text' (inline) or 'file' (path)
keys.formatTJWKSKeyFormat--Yes'pem' or 'jwk'
keys.privatestring--YesPrivate key content or file path
keys.publicstring--YesPublic key content or file path
kidstring--YesKey ID exposed in the JWKS endpoint and JWT header
getTokenExpiresFnTGetTokenExpiresFn--YesReturns token expiration in seconds
rest.pathstring'/certs'NoPath of the generated JWKSController
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload encryption
applicationSecretstring--NoEnables AES payload field encryption when set
fieldCodecsIPayloadFieldCodec[][]NoCustom serialize/deserialize per field name
verifyIJWTVerifyOptions--NoFurther checks on verify: subject, algorithms, clockTolerance, maxTokenAge, typ, requiredClaims. issuer and audience are claims now. algorithms unset pins the algorithm the service signs with
claims{ issuer: string; audience?: string | string[] }--Yesissuer is required: stamped as iss on every issued token and required on every verified one. audience is optional: set, it is stamped as aud and required; absent, no aud is stamped and none is checked. A configured value WINS over one supplied in the payload. No other key is accepted

IJWKSVerifierOptions ​

OptionTypeDefaultRequiredDescription
modetypeof JWKSModes.VERIFIER--YesMust be 'verifier'
jwksUrlstring--YesURL of the issuer's JWKS endpoint
cacheTtlMsnumber43_200_000 (12h)NocreateRemoteJWKSet cacheMaxAge
cooldownMsnumber30_000 (30s)NocreateRemoteJWKSet cooldownDuration
aesAlgorithmAESAlgorithmType'aes-256-cbc'NoAES algorithm for payload decryption
applicationSecretstring--NoMust match the issuer's secret to decrypt payloads
fieldCodecsIPayloadFieldCodec[][]NoMust match the issuer's codecs to decrypt custom fields
claims{ issuer: string; audience?: string | string[] }--Yesissuer is required on every verified token. audience is optional: set, it is required too; absent, aud is not checked. No other key is accepted
verifyIJWKSVerifierVerifyOptions--Yesalgorithms is required (the accepted JWS algorithms, for example ['RS256']): a verifier cannot know what the issuer signs with. Also subject, clockTolerance, maxTokenAge, typ, requiredClaims
jwks.hosts.httpstring[][]NoExact hosts that may serve the key set over http:: a name, an IPv4 address or an IPv6 address in brackets, each with an optional :port. Without it the jwksUrl is https: or a loopback host. See JWKS over http

IMPORTANT

JWKSVerifierTokenService cannot sign tokens - getSigner(), getSigningKey(), and getDefaultTokenExpiresFn() all throw. Only verify() and extractCredentials() are functional.

JWKS over http ​

A JWKS URL is https:. It may be http: only when its host is loopback (localhost, 127.0.0.0/8, ::1) or is listed in jwks.hosts.http. Any other scheme is refused. A key set read over plain http: can be replaced on the way, and whoever replaces it signs tokens that verify.

WhereOption
JWKS verifieroptions.jwks.hosts.http, beside jwksUrl
Service-assertion callersIServiceAuthOptions.jwks.hosts.http, which covers every callers[...].jwksUrl
  • Exact entries. An entry is a host name (identity-service), an IPv4 address (10.0.0.5) or an IPv6 address in brackets ([fd00::1]), with an optional :port (identity-service:3000, 10.0.0.5:8080, [fd00::1]:8443).
  • Ports. An entry without a port covers every port of that host. An entry with a port covers that port only. A URL with no port is on port 80, so host:80 covers it.
  • Spelled the way the URL parser writes it. An entry is valid only when new URL('http://' + entry) gives the same host back, so 2130706433, 0x7f000001, 1.2.3, 010.0.0.5 and [::ffff:10.0.0.5] refuse the boot, naming the entry. A URL is read by the same parser, so http://167772165 is 10.0.0.5 and is covered by that entry, and http://[::ffff:10.0.0.5] is [::ffff:a00:5] and is not. A host name written with a trailing dot does not match its entry.
  • The mapped form is the same machine. [::ffff:a00:5] is 10.0.0.5 written as an IPv6 address. Listing one does not list the other, so list the form your JWKS URL uses; but know that both reach one host.
  • Entries are not trimmed. A space, tab or newline around an entry refuses the boot, naming the entry: it is a typo, not a value to correct.
  • DNS limits. A name is at most 253 characters and a label at most 63. An address is judged by the URL parser alone.
  • Not hosts. 0.0.0.0 and [::] mean "any local address" and are refused as entries.
  • Port 0. A jwksUrl on port 0 refuses the boot, whatever the entries: nothing listens there, and an entry without a port would otherwise cover it.
  • No wildcards, ranges or CIDR. A scheme, a path, a query, userinfo, a wildcard, an empty label or an empty port refuses the boot. There is no rule for private networks: what a name resolves to can change, so you opt in host by host. Loopback is always allowed.
  • Redirects are not followed. The key set fetch reads only a 200, so an https: URL cannot lead to an http: host; a URL that redirects fails verification.
  • Checked at boot. The component checks the verifier URL and every caller URL when the application starts; the services check again before they fetch.

TBasicTokenServiceOptions ​

OptionTypeDescription
verifyCredentials(opts: { credentials: { username: string; password: string }; context: TContext }) => Promise<IAuthUser | null>Callback that validates Basic credentials and returns the authenticated user, or null

TAuthenticationRestOptions ​

Discriminated union on useAuthController - when true, controllerOpts becomes required:

typescript
type TAuthenticationRestOptions = {} & (
  | { useAuthController?: false | undefined }
  | { useAuthController: true; controllerOpts: TDefineAuthControllerOpts }
);

TDefineAuthControllerOpts ​

OptionTypeDefaultDescription
restPathstring'/auth'Base path for the generated controller
serviceKeystring--DI key for the IAuthService implementation (required)
requireAuthenticatedSignUpbooleanfalseWhether POST /sign-up requires a valid JWT
payload.signIn{ request: { schema }, response: { schema } }Built-in schemasCustom Zod schemas for /sign-in
payload.signUp{ request: { schema }, response: { schema } }Built-in schemasCustom Zod schemas for /sign-up
payload.changePassword{ request: { schema? }, response: { schema } }Built-in schemasCustom Zod schemas for /change-password
payload.refreshToken{ response: { schema } }AnyObjectSchemaCustom response schema for /token/refresh
payload.getUserInformation{ response: { schema } }AnyObjectSchemaCustom response schema for /me and the who-am-i userInformation field

Route authenticate config ​

typescript
type TRouteAuthenticateConfig =
  | { skip: true }
  | { skip?: false; strategies?: TAuthStrategy[]; mode?: TAuthMode };
FieldTypeDefaultDescription
authenticate.strategiesTAuthStrategy[]--Strategy names to try - for example, ['jwt'] or ['jwt', 'basic']. Any name you register works too; 'jwt' and 'basic' are the ones the framework ships
authenticate.mode'any' | 'all''any''any': first success wins. 'all': every strategy must pass. A verified credential whose answer has no userId does not authenticate the request: in any mode that strategy counts as failed, in all mode the first strategy's answer must carry it
authenticate.skiptrue--Skips authentication for this route entirely

IAuthUser / IJWTTokenPayload ​

typescript
interface IAuthUser {
  userId: IdType;
  [extra: string | symbol]: any;
}

type TJWTTokenRole = { id: IdType; identifier: string; priority: number };

interface IJWTTokenPayload extends JWTPayload, IAuthUser {
  userId: IdType;
  roles?: TJWTTokenRole[];
  clientId?: string;
  provider?: string;
  email?: string;
  name?: string;
  [extra: string | symbol]: any;
}

roles may be absent. A token signed without it verifies without it, and authorization reads its roles as none. Check it before you read it: payload.roles ?? [].

TIP

IAuthUser is intentionally minimal. Your IAuthService can return extra fields (roles, email, provider) - they pass through JWT generation and are available on Authentication.CURRENT_USER after authentication.

IAuthService ​

typescript
interface IAuthService<
  E extends Env = Env,
  SIRQ extends TSignInRequest = TSignInRequest, SIRS = AnyObject,
  SURQ extends TSignUpRequest = TSignUpRequest, SURS = AnyObject,
  CPRQ extends TChangePasswordRequest = TChangePasswordRequest, CPRS = AnyObject,
  UIRQ = AnyObject, UIRS = AnyObject,
  RTRS = AnyObject,
> {
  signIn(context: TContext<E>, opts: SIRQ): Promise<SIRS>;
  signUp(context: TContext<E>, opts: SURQ): Promise<SURS>;
  changePassword(context: TContext<E>, opts: CPRQ): Promise<CPRS>;
  getUserInformation?(context: TContext<E>, opts: UIRQ): Promise<UIRS>;
  refreshToken?(context: TContext<E>): Promise<RTRS>;
}

NOTE

getUserInformation and refreshToken are optional. The generated auth controller returns 501 for /me, /token/refresh, or ?withUserInformation=true on /who-am-i if the bound service doesn't implement the corresponding method.

Field codecs ​

typescript
interface IPayloadFieldCodec<T = unknown> {
  key: string;
  serialize(opts: { value: T }): string;
  deserialize(opts: { raw: string }): T;
}

AuthenticationFieldCodecs.ROLES_CODEC is a ready-made codec for the roles field (pipe-separated id|identifier|priority strings). It is not applied automatically - pass it explicitly via fieldCodecs: [AuthenticationFieldCodecs.ROLES_CODEC] in the JWS/JWKS options. Without it, roles (and every other non-standard field) is serialized with plain JSON.stringify before AES encryption.

typescript
class AuthenticationFieldCodecs {
  static readonly ROLES_CODEC: IPayloadFieldCodec<TJWTTokenRole[]>;
  static build<T>(opts: { key: string; serialize; deserialize }): IPayloadFieldCodec<T>;
}

Context variables ​

Set on the Hono Context during authentication, readable via context.get():

ConstantKey stringTypeDescription
Authentication.CURRENT_USERauth.current.userIAuthUserAuthenticated user payload
Authentication.AUDIT_USER_IDaudit.user.idIdTypeAuthenticated user's ID
Authentication.SKIP_AUTHENTICATIONauthentication.skipbooleanSet true in a preceding middleware to bypass auth

Constants ​

Authentication

ConstantValueDescription
Authentication.STRATEGY_JWT'jwt'JWT strategy name
Authentication.STRATEGY_BASIC'basic'Basic strategy name
Authentication.STRATEGY_SERVICE'service'Service-assertion strategy name
Authentication.TYPE_BEARER'Bearer'Bearer token type prefix
Authentication.TYPE_BASIC'Basic'Basic token type prefix
Authentication.AUTHENTICATION_STRATEGY'authentication.strategy'Binding key prefix for registered strategies

AuthenticationTokenTypes

ConstantValue
TYPE_AUTHORIZATION_CODE'000_AUTHORIZATION_CODE'
TYPE_ACCESS_TOKEN'100_ACCESS_TOKEN'
TYPE_REFRESH_TOKEN'200_REFRESH_TOKEN'

JOSE / JWKS constants - each class also exposes SCHEME_SET: Set<string> and isValid(input): boolean

ClassMembers
JOSEStandardsJWS ('JWS'), JWKS ('JWKS')
JWKSModesISSUER ('issuer'), VERIFIER ('verifier')
JWKSKeyDriversTEXT ('text'), FILE ('file')
JWKSKeyFormatsPEM ('pem'), JWK ('jwk')
AuthenticateStrategyBASIC ('basic'), JWT ('jwt'), SERVICE ('service') - same values as Authentication.STRATEGY_*
AuthenticationModesANY ('any'), ALL ('all')

Strategy registry ​

AuthenticationStrategyRegistry is a singleton extending AbstractAuthRegistry<IAuthenticationStrategy>.

MethodSignatureDescription
getInstance()static (): AuthenticationStrategyRegistryReturns (creating if needed) the singleton
register(opts: { container: Container; strategies: { name: string; strategy: TClass<IAuthenticationStrategy> }[] }) => thisBinds each strategy into the container as a singleton under authentication.strategy.<name>. Returns this
resolveStrategy(opts: { name: string }) => IAuthenticationStrategyResolves a registered strategy instance by name
typescript
AuthenticationStrategyRegistry.getInstance().register({
  container: this,
  strategies: [
    { name: Authentication.STRATEGY_JWT, strategy: JWKSIssuerAuthenticationStrategy },
    { name: Authentication.STRATEGY_BASIC, strategy: BasicAuthenticationStrategy },
  ],
});

Standalone authenticate() function - the primary export for creating middleware outside the route-config authenticate field:

typescript
const authenticationProvider = new AuthenticationProvider();
const authenticateFn = authenticationProvider.value();

export const authenticate = (opts: { strategies: string[]; mode?: TAuthMode }) => authenticateFn(opts);

AuthenticationProvider middleware behavior:

  1. If Authentication.SKIP_AUTHENTICATION is set on context, skips entirely (debug log)
  2. If Authentication.CURRENT_USER is already set, skips (already authenticated)
  3. Runs strategies per mode ('any' or 'all')
  4. On success, sets Authentication.CURRENT_USER and Authentication.AUDIT_USER_ID
  5. On failure, throws 401

NOTE

'any' mode logs each failing strategy at debug and discards the error, and a strategy whose answer has no userId counts as failed, so the next one gets its turn. It only throws once every strategy is exhausted. 'all' mode uses the first strategy's user payload as the identity source. If that payload has no userId, it throws 401 even though every strategy technically passed.

Service class hierarchy ​

AbstractBearerTokenService<E>          (extends BaseService)
  #aes, #applicationSecret, #fieldCodecs
  +extractCredentials(context)         Extract Bearer token from Authorization header
  +verify(opts)                        Template method -> doVerify()
  +generate(opts)                      Template method -> getSigner() + getSigningKey()
  +encryptPayload(payload) / decryptPayload(opts)
  #doVerify(token)*  +getSigner(opts)*  #getSigningKey()*  #getDefaultTokenExpiresFn()*

  JWSTokenService                       Symmetric HS256, shared secret
    used by JWSAuthenticationStrategy

  AbstractJWKSTokenService              Lazy ensureInitialized() + retry-on-failure
    #initialized, #initPromise
    +ensureInitialized()   #initialize()*

    JWKSIssuerTokenService               Sign with private key, verify with public key
      +getJWKS() (sync, throws if uninitialized)  +getJWKSAsync()
      used by JWKSIssuerAuthenticationStrategy

    JWKSVerifierTokenService             Verify only, via remote JWKS
      used by JWKSVerifierAuthenticationStrategy

AbstractBearerTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/bearer/abstract.service.ts

MethodSignatureDescription
configurePayloadEncryption(opts: { aesAlgorithm?; applicationSecret?; fieldCodecs?: IPayloadFieldCodec[] }) => voidSets up AES + field codecs. AES only activates if applicationSecret is provided
extractCredentials(context) => { type: string; token: string }Parses Authorization: Bearer <token>
verify(opts: { type, token }) => Promise<IJWTTokenPayload>Calls doVerify(), wraps errors as sanitized 401
generate(opts: { payload, getTokenExpiresFn? }) => Promise<string>Calls getSigner() then signs with getSigningKey()
serializeField / deserializeField(opts) => string / anyPer-field codec lookup, JSON.stringify/JSON.parse fallback
encryptPayload(payload) => Promise<Record<string, any>>AES-encrypts non-standard fields (keys and values); null is kept and undefined is skipped. No-op if AES not configured. Async: callers await it
decryptPayload(opts: { result }) => Promise<IJWTTokenPayload>Reverses encryptPayload. No-op if AES not configured. Async: callers await it

Static: JWT_COMMON_FIELDS: Set<'iss'|'sub'|'aud'|'jti'|'nbf'|'exp'|'iat'> - never encrypted or touched by field codecs.

JWSTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/bearer/jws.service.ts

The constructor validates jwtSecret, getTokenExpiresFn and claims, throwing 500 if any is missing. It encodes the secret to Uint8Array and calls configurePayloadEncryption(). doVerify calls jose.jwtVerify() with the shared secret. getSigner signs with header HS256, or headerAlgorithm if you set one.

AbstractJWKSTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/bearer/jwks/abstract.service.ts

ensureInitialized() lazily runs initialize() on the first call. Concurrent callers share the pending promise. If initialize() rejects, the promise resets - the next call retries instead of caching the failure.

JWKSIssuerTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts

initialize() runs in order:

  1. Reads the key content - readFile for keys.driver: 'file', inline text for 'text'.
  2. Imports it - importPKCS8/importSPKI for PEM, importJWK for JWK.
  3. Exports the public JWK with kid, alg, and use: 'sig' set.
  4. Caches the result as { keys: [publicJWK] }.
MethodSignatureDescription
getJWKS() => { keys: JWK[] }Synchronous, returns the cached JWKS. Throws if called before initialize() completes
getJWKSAsync() => Promise<{ keys: JWK[] }>Calls ensureInitialized() first

JWKSVerifierTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts

initialize() calls createRemoteJWKSet(jwksUrl, { cacheMaxAge: cacheTtlMs ?? 43_200_000, cooldownDuration: cooldownMs ?? 30_000 }). getSigner/getSigningKey/getDefaultTokenExpiresFn all throw - this service is verify-only.

BasicTokenService ​

File: packages/core-server/src/components/auth/authenticate/services/basic/service.ts

MethodSignatureDescription
extractCredentials(context) => { username: string; password: string }Decodes Authorization: Basic <base64>
verify(opts: { credentials, context }) => Promise<IAuthUser>Calls the user-provided verifyCredentials

Constructor throws 500 if verifyCredentials is missing from the injected options.

Strategy classes ​

All five strategies extend BaseHelper and implement IAuthenticationStrategy<E>. Each one carries:

  • A name field.
  • A standard field (Bearer strategies only).
  • One injected token service.
  • An authenticate(context) method that pulls the credential off the request, then verifies it.
StrategynameInjectsFile
JWSAuthenticationStrategyAuthentication.STRATEGY_JWTJWSTokenServicestrategies/jws.strategy.ts
JWKSIssuerAuthenticationStrategyAuthentication.STRATEGY_JWTJWKSIssuerTokenServicestrategies/jwks/issuer.ts
JWKSVerifierAuthenticationStrategyAuthentication.STRATEGY_JWTJWKSVerifierTokenServicestrategies/jwks/verifier.ts
BasicAuthenticationStrategyAuthentication.STRATEGY_BASICBasicTokenServicestrategies/basic.strategy.ts
ServiceAuthenticationStrategyAuthentication.STRATEGY_SERVICEServiceAssertionVerifierServicestrategies/service.strategy.ts

NOTE

Choose the strategy class that matches your JOSE standard. JWKSIssuerAuthenticationStrategy and JWKSVerifierAuthenticationStrategy both register under the same 'jwt' name - use only one of the two per service.

ServiceAuthenticationStrategy is the odd one out. It reads the ServiceAssertion.HEADER assertion rather than an Authorization header, verifies it against the calling service's own JWKS, then hands the issuer to your resolvePrincipal callback. It proves which SERVICE called, never which user, and it stamps the caller name onto the returned user as callerService. defineServiceAuth() registers it for you - you do not add it to AuthenticationStrategyRegistry by hand.

JWKSController ​

Serves the JWKS endpoint (default path /certs, configurable via rest.path). Intentionally unauthenticated - it serves the public keys external verifiers need.

File: packages/core-server/src/components/auth/authenticate/controllers/jwks/controller.ts

typescript
class JWKSController extends BaseRestController {
  constructor(@inject(...) private jwksService: JWKSIssuerTokenService) {
    super({ scope: JWKSController.name, path: '/certs', isStrict: true });
  }

  override binding() {
    this.defineRoute({
      configs: RouteConfigs.GET_JWKS_CERTS, // GET '/'
      handler: async context => {
        const jwks = await this.jwksService.getJWKSAsync();
        context.header('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
        return context.json(jwks, HTTP.ResultCodes.RS_2.Ok);
      },
    });
  }
}

The component applies @controller({ path }) to JWKSController dynamically at binding time (via Reflect.decorate), since the path depends on a runtime option.

Controller factory ​

AuthControllerFactory.build(opts: TDefineAuthControllerOpts): typeof AuthController builds a BaseRestController subclass at runtime.

File: packages/core-server/src/components/auth/authenticate/controllers/factory.ts

How it works:

  1. Class creation. class AuthController extends BaseRestController {} inside the factory closure, decorated with @controller({ path: restPath }), isStrict: true.
  2. Service injection. inject({ key: serviceKey })(AuthController, undefined, 0) is applied after class definition - the programmatic equivalent of decorating constructor parameter 0. The constructor throws 400 if the resolved service is falsy.
  3. Routes. Defined in binding() via this.defineRoute() - see the endpoint table in Usage & Examples.
  4. Schemas. Each endpoint uses payload.<name>.{request,response}.schema if you provide it. Otherwise it falls back to a built-in default, or AnyObjectSchema where there's no built-in schema for that response.

Also exports JWTTokenPayloadSchema, the Zod schema backing /who-am-i's response. It's extended at runtime with an optional userInformation field, typed from payload.getUserInformation.response.schema (or AnyObjectSchema if you don't provide one).

Entity column helper types ​

Exported for extending the auth entity column helpers - see Usage & Examples for the columns themselves.

typescript
type TPermissionOptions = { idType?: 'string' | 'number' };
type TPermissionCommonColumns = {
  code: NotNull<PgTextBuilderInitial<...>>;
  name: NotNull<PgTextBuilderInitial<...>>;
  subject: NotNull<PgTextBuilderInitial<...>>;
  method: NotNull<PgTextBuilderInitial<...>>;
  action: NotNull<PgTextBuilderInitial<...>>;
  scope: NotNull<PgTextBuilderInitial<...>>;
  description: PgTextBuilderInitial<...>;
};

type TPolicyDefinitionOptions<ExtraVariant extends string = never> = {
  idType?: 'string' | 'number';
  extraVariants?: ReadonlyArray<ExtraVariant>;
};

type TPolicyDefinitionCommonColumns<
  ExtraVariant extends string = never,
  Metadata extends object = TSubsetGrantMetadata,
> = {
  metadata: ReturnType<typeof jsonb>;         // $type<Metadata>()
  variant: ReturnType<typeof text>;           // $type<TAuthorizationPolicyVariant | ExtraVariant>(), notNull
  subjectType: ReturnType<typeof text>;       // notNull
  targetType: ReturnType<typeof text>;        // notNull
  domainType: ReturnType<typeof text>;        // nullable
  action: ReturnType<typeof text>;
  effect: ReturnType<typeof text>;            // $type<TAuthorizationDecision>()
};

Both are generic. extraVariants declares app-owned edge kinds that live in the same table, and Metadata types the metadata column - it defaults to TSubsetGrantMetadata ({ ops: string[] }), what subset grants write.

subjectId, targetId and domainId are not in the common shape. AuthModelColumns.buildPolicyDefinition adds all three per idType, as text or integer. The domain lives in two columns, domainType and domainId, never one - see Usage & Examples.

File structure ​

The contract lives in the kernel; the server-side wiring lives in core-server. Each package re-exports the other's half, so @venizia/ignis still resolves every name below.

packages/kernel/src/base/auth/
├── authenticate/
│   ├── common/
│   │   ├── codecs.ts             # AuthenticationFieldCodecs (ROLES_CODEC, build() factory)
│   │   ├── constants/            # Authentication, AuthenticateStrategy, AuthenticationModes, AuthenticationTokenTypes, JOSEStandards, JWKSModes, JWKSKeyDrivers, JWKSKeyFormats, ServiceAssertion
│   │   ├── errors.ts             # AuthenticationErrors
│   │   ├── keys.ts               # AuthenticateBindingKeys
│   │   └── types/                # Option interfaces, discriminated unions, IAuthUser, IJWTTokenPayload, IAuthService
│   ├── middlewares/
│   │   └── authenticate.middleware.ts   # Standalone authenticate() function
│   ├── providers/
│   │   └── authentication.provider.ts   # AuthenticationProvider
│   └── strategies/
│       └── strategy-registry.ts         # AuthenticationStrategyRegistry
├── base/
│   └── abstract-auth-registry.ts        # AbstractAuthRegistry (shared by authenticate + authorize)
├── context-variables.ts                 # Hono ContextVariableMap augmentation
└── models/
    └── requests/                        # SignInRequestSchema, SignUpRequestSchema, ChangePasswordRequestSchema

packages/core-server/src/components/auth/
├── authenticate/
│   ├── controllers/
│   │   ├── factory.ts            # AuthControllerFactory + JWTTokenPayloadSchema
│   │   ├── jwks/                 # JWKSController + route config
│   │   └── service-certs/        # ServiceCertsController + route config
│   ├── services/
│   │   ├── basic/service.ts             # BasicTokenService
│   │   ├── bearer/
│   │   │   ├── abstract.service.ts      # AbstractBearerTokenService
│   │   │   ├── jws.service.ts           # JWSTokenService
│   │   │   └── jwks/                    # AbstractJWKSTokenService, JWKSIssuerTokenService, JWKSVerifierTokenService
│   │   └── service/                     # ServiceAssertionSignerService, ServiceAssertionVerifierService
│   ├── strategies/                      # JWSAuthenticationStrategy, JWKS*, BasicAuthenticationStrategy, ServiceAuthenticationStrategy
│   └── component.ts                     # AuthenticateComponent
└── models/
    └── entities/                        # columns.ts (AuthModelColumns) + the model types

See also ​