Skip to main content

TokenService

@webda/core


Class: TokenService<T>

Defined in: packages/core/src/services/token.service.ts:212

Issues access tokens (JWT) and rotating refresh tokens

Webda Modda​

TokenService

Extends​

Type Parameters​

T​

T extends TokenServiceParameters = TokenServiceParameters

Constructors​

Constructor​

new TokenService<T>(name, params): TokenService<T>

Defined in: packages/core/src/services/service.ts:205

Create a new Service instance

Service

Parameters​

name​

string

The name of the service

params​

T

The parameters block define in the configuration file

Returns​

TokenService<T>

Inherited from​

Service.constructor

Properties​

_compiledCapabilities​

protected _compiledCapabilities: Record<string, any> = {}

Defined in: packages/core/src/services/iservice.ts:61

Capabilities detected at compile-time from @WebdaCapability-tagged interfaces.

Populated during Service.resolve by reading the service's entry in webda.module.json. Each key is a capability name (e.g., "request-filter"), and the value is an empty object {} by default. Override getCapabilities to provide capability-specific configuration or to conditionally disable capabilities.

See​

getCapabilities

Inherited from​

Service._compiledCapabilities


[WEBDA_EVENTS]​

[WEBDA_EVENTS]: object

Defined in: packages/core/src/services/service.ts:179

Set the Webda events here

Inherited from​

Service.[WEBDA_EVENTS]


logger​

protected logger: Logger

Defined in: packages/core/src/services/service.ts:192

Logger with class context

Inherited from​

Service.logger


metrics?​

protected optional metrics?: object

Defined in: packages/core/src/services/service.ts:196

Get metrics

Inherited from​

Service.metrics


name​

readonly name: string

Defined in: packages/core/src/services/iservice.ts:35

Name

Inherited from​

Service.name


parameters​

readonly parameters: T

Defined in: packages/core/src/services/iservice.ts:39

Parameters

Inherited from​

Service.parameters


revocationHits​

protected revocationHits: Map<string, { entry: RevokedAccess; until: number; }>

Defined in: packages/core/src/services/token.service.ts:214

Revoked keys, cached until their expiry (user: entries only for revocationCacheTtl: they can be raised)


revocationMisses​

protected revocationMisses: Map<string, number>

Defined in: packages/core/src/services/token.service.ts:216

Keys known not revoked, cached for revocationCacheTtl


sweepTimer?​

protected optional sweepTimer?: Timeout

Defined in: packages/core/src/services/token.service.ts:218

Periodic sweep of the expired denylist entries


createConfiguration?​

static optional createConfiguration?: (params) => any

Defined in: packages/core/src/services/iservice.ts:44

Create configuration set by the application on load

Parameters​

params​

any

Returns​

any

Inherited from​

Service.createConfiguration


filterConfiguration?​

static optional filterConfiguration?: (params) => any

Defined in: packages/core/src/services/iservice.ts:49

Create configuration set by the application on load

Parameters​

params​

any

Returns​

any

Inherited from​

Service.filterConfiguration


Parameters​

static Parameters: typeof ServiceParameters = ServiceParameters

Defined in: packages/core/src/services/service.ts:175

Service parameters

Inherited from​

Service.Parameters

Methods​

__clean()​

abstract __clean(): Promise<void>

Defined in: packages/core/src/services/service.ts:539

Clean the service data, can only be used in test mode

Returns​

Promise<void>

Inherited from​

Service.__clean


addListener()​

addListener<Key>(eventName, listener): this

Defined in: packages/core/src/events/asynceventemitter.ts:90

Add listener

Type Parameters​

Key​

Key extends never

Parameters​

eventName​

Key

the event name

listener​

(event) => void | Promise<void>

the event listener

Returns​

this

this for chaining

See​

EventEmitter.addListener

Inherited from​

Service.addListener


addRoute()​

protected addRoute(url, methods, executer, openapi?, override?): void

Defined in: packages/core/src/services/service.ts:400

Add a route dynamicaly

Parameters​

url​

string

of the route can contains dynamic part like {uuid}

methods​

HttpMethodType[]

the HTTP methods

executer​

Function

Method to execute for this route

openapi?​

OpenAPIWebdaDefinition = {}

the OpenAPI specification

override?​

boolean = false

whether to override existing

Returns​

void

Inherited from​

Service.addRoute


audienceOf()​

protected audienceOf(resource, resources, requested?): string

Defined in: packages/core/src/services/token.service.ts:349

Audience of an access token of a family (RFC 8707 §2.2)

Parameters​

resource​

string

default resource of the family, none for the application audience

resources​

string[]

other resources the family may mint tokens for

requested?​

string

resource asked for this token, the default one when absent

Returns​

string

the audience

Throws​

InvalidTarget when the requested resource is neither the default nor one of the others


authorizeClientEvent()​

authorizeClientEvent(_event, _context): boolean

Defined in: packages/core/src/services/service.ts:353

Authorize a public event subscription

Parameters​

_event​

string

the event name

_context​

OperationContext

the execution context

Returns​

boolean

true if the condition is met

Inherited from​

Service.authorizeClientEvent


cacheHit()​

protected cacheHit(key, entry): void

Defined in: packages/core/src/services/token.service.ts:408

Cache a revoked entry: a user: notBefore can be raised by a later revocation, so re-read it after the TTL

Parameters​

key​

string

denylist key

entry​

RevokedAccess

the entry

Returns​

void


computeParameters()​

computeParameters(): void

Defined in: packages/core/src/services/service.ts:214

Used to compute or derivate input parameter to attribute

Returns​

void

Deprecated​

Inherited from​

Service.computeParameters


denylist()​

protected denylist(key, notBefore?, accessTtl?): Promise<void>

Defined in: packages/core/src/services/token.service.ts:447

Perform denylist

Parameters​

key​

string

denylist key

notBefore?​

number

for user entries, tokens issued before are rejected (ms)

accessTtl?​

number = 0

longest lifetime (s) of the access tokens to reject, at least the accessTtl parameter

Returns​

Promise<void>


emit()​

emit<Key>(event, data): Promise<void>

Defined in: packages/core/src/services/service.ts:520

Emit the event with data and wait for Promise to finish if listener returned a Promise

Type Parameters​

Key​

Key extends never

Parameters​

event​

Key

the event name

data​

object[Key]

the data to process

Returns​

Promise<void>

Inherited from​

Service.emit


getCapabilities()​

getCapabilities(): Record<string, any>

Defined in: packages/core/src/services/iservice.ts:89

Return the capabilities of this service.

By default returns capabilities detected at compile-time from

Returns​

Record<string, any>

the result

Webda Capability-tagged​

interfaces in webda.module.json.

Override to disable capabilities based on configuration:

getCapabilities() {
const caps = super.getCapabilities();
if (!this.parameters.enabled) delete caps["request-filter"];
return caps;
}

Inherited from​

Service.getCapabilities


getClientEvents()​

getClientEvents(): string[]

Defined in: packages/core/src/services/service.ts:341

Return the events that an external system can subscribe to

Returns​

string[]

the list of results

Inherited from​

Service.getClientEvents


getMaxListeners()​

getMaxListeners(): number

Defined in: packages/core/src/events/asynceventemitter.ts:97

Returns​

number

Inherited from​

Service.getMaxListeners


getMetric()​

getMetric<T>(type, configuration): T

Defined in: packages/core/src/services/service.ts:323

Add service name label

Type Parameters​

T​

T = Gauge<string> | Counter<string> | Histogram<string>

Parameters​

type​

CustomConstructor<T, [MetricConfiguration<T>]>

the type to look up

configuration​

MetricConfiguration<T>

the configuration

Returns​

T

the result

Inherited from​

Service.getMetric


getName()​

getName(): string

Defined in: packages/core/src/services/service.ts:530

Get service name

Returns​

string

the result string

Inherited from​

Service.getName


getOpenApiReplacements()​

getOpenApiReplacements(): any

Defined in: packages/core/src/services/service.ts:429

Return variables for replacement in openapi

Returns​

any

the result

Inherited from​

Service.getOpenApiReplacements


getOperationId()​

getOperationId(id): string

Defined in: packages/core/src/services/service.ts:387

If undefined is returned it cancel the operation registration

Parameters​

id​

string

the identifier

Returns​

string

the result

Inherited from​

Service.getOperationId


getParameters()​

getParameters(): T

Defined in: packages/core/src/services/service.ts:222

Get the service parameters

Returns​

T

the result

Inherited from​

Service.getParameters


getService()​

getService<T>(name): ServicesMap[T]

Defined in: packages/core/src/services/service.ts:313

Get a service by name

Type Parameters​

T​

T extends keyof ServicesMap

Parameters​

name​

T

the name to use

Returns​

ServicesMap[T]

the result map

Deprecated​

Use useService, might reconsider

Inherited from​

Service.getService


getState()​

getState(): ServiceStates

Defined in: packages/core/src/services/service.ts:185

Get the current state

Returns​

ServiceStates

the result

Inherited from​

Service.getState


getUrl()​

getUrl(url, _methods): string

Defined in: packages/core/src/services/service.ts:364

Return the full path url based on parameters

Parameters​

url​

string

relative url to service

_methods​

HttpMethodType[]

in case we need filtering (like Store)

Returns​

string

absolute url or undefined if need to skip the Route

Inherited from​

Service.getUrl


hash()​

protected hash(token): string

Defined in: packages/core/src/services/token.service.ts:259

Hash operation

Parameters​

token​

string

raw refresh token

Returns​

string

SHA-256 hex


init()​

init(): Promise<TokenService<T>>

Defined in: packages/core/src/services/token.service.ts:236

Purge expired denylist entries now and then periodically

Returns​

Promise<TokenService<T>>

Overrides​

Service.init


initMetrics()​

initMetrics(): void

Defined in: packages/core/src/services/service.ts:303

Init the metrics

Returns​

void

Inherited from​

Service.initMetrics


initOperations()​

initOperations(): void

Defined in: packages/core/src/services/service.ts:459

Init the operations from

Returns​

void

Operation​

decorators on this service

Inherited from​

Service.initOperations


isConditionFailure()​

protected isConditionFailure(err): boolean

Defined in: packages/core/src/services/token.service.ts:629

Check whether condition failure

Parameters​

err​

any

error thrown by a conditional write

Returns​

boolean

true if the error is a failed write condition


isRevoked()​

isRevoked(claims): Promise<boolean>

Defined in: packages/core/src/services/token.service.ts:431

Check whether revoked

Parameters​

claims​

AccessClaims

verified access claims

Returns​

Promise<boolean>

true when the family or the user was revoked after the token was issued


issue()​

issue(session, family?, options?): Promise<IssuedTokens & object>

Defined in: packages/core/src/services/token.service.ts:280

Issue an access + refresh token pair for a logged session

Roles are not persisted: refreshed access tokens carry no roles until they are re-derived.

Parameters​

session​

Session

logged session (must not be anonymous nor pending MFA)

family?​

string = ...

existing family when rotating

options?​

IssueOptions = {}

OAuth client, scope and display name

Returns​

Promise<IssuedTokens & object>

the tokens and their family


listeners()​

listeners(eventName): Function[]

Defined in: packages/core/src/events/asynceventemitter.ts:195

Get all listeners for an event

Parameters​

eventName​

never

the event name

Returns​

Function[]

the list of results

Inherited from​

Service.listeners


loadCapabilities()​

protected loadCapabilities(): void

Defined in: packages/core/src/services/service.ts:283

Load capabilities from webda.module.json metadata into _compiledCapabilities.

Called during resolve after dependency injection. Reads the service's type name from parameters, looks it up in the application's module metadata (moddas or beans section), and populates _compiledCapabilities with an empty object for each declared capability name.

Fails silently if the application is not available (e.g., in unit tests where services are instantiated without a full application context).

Returns​

void

Example​

// If webda.module.json contains:
// { "moddas": { "MyApp/HawkService": { "capabilities": ["request-filter", "cors-filter"] } } }
// Then after resolve(), this.getCapabilities() returns:
// { "request-filter": {}, "cors-filter": {} }

See​

getCapabilities

Inherited from​

Service.loadCapabilities


log()​

log(level, ...args): void

Defined in: packages/core/src/services/service.ts:561

Log operation

Parameters​

level​

WorkerLogLevel

to log

args​

...any[]

additional arguments

Returns​

void

Inherited from​

Service.log


lookupRevoked()​

protected lookupRevoked(key): Promise<RevokedAccess>

Defined in: packages/core/src/services/token.service.ts:386

Return the entry, or undefined

Parameters​

key​

string

denylist key

Returns​

Promise<RevokedAccess>

the entry, or undefined


newRefreshToken()​

protected newRefreshToken(): string

Defined in: packages/core/src/services/token.service.ts:267

Return a new raw refresh token

Returns​

string

a new raw refresh token


off()​

off<Key>(eventName, listener): this

Defined in: packages/core/src/events/asynceventemitter.ts:152

Perform off

Type Parameters​

Key​

Key extends never

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.off

Inherited from​

Service.off


on()​

on<Key>(eventName, listener): this

Defined in: packages/core/src/events/asynceventemitter.ts:128

Perform on

Type Parameters​

Key​

Key extends never

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.once

Inherited from​

Service.on


once()​

once<Key>(eventName, listener): this

Defined in: packages/core/src/events/asynceventemitter.ts:116

Perform once

Type Parameters​

Key​

Key extends never

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.once

Inherited from​

Service.once


operationSchemaName()​

protected operationSchemaName(method, side): string

Defined in: packages/core/src/services/service.ts:441

Schema of an operation side: <service name>.<method>.<side> when the application knows it, else the one the build writes, <class>.<method>.<side>, for the class or its nearest ancestor that has it (a service configured under another name than its class)

Parameters​

method​

string

the method name

side​

"input" | "output"

input or output

Returns​

string

the schema name

Inherited from​

Service.operationSchemaName


pruneRevocationCaches()​

protected pruneRevocationCaches(): void

Defined in: packages/core/src/services/token.service.ts:416

Drop the expired cache entries

Returns​

void


refresh()​

refresh(refreshToken, options?): Promise<IssuedTokens & object>

Defined in: packages/core/src/services/token.service.ts:495

Exchange a refresh token (rotation with reuse detection)

The token is only ever looked up by its hash, so an access token or any arbitrary string simply does not match a stored record.

Parameters​

refreshToken​

string

raw refresh token

options?​

client the token must belong to and optional narrower scope

clientId?​

string

client the token must belong to

issuer?​

string

issuer of the new access tokens, see IssueOptions.issuer

resource?​

string

resource of the new access token: the one the family is bound to, or one of the other resources it may mint tokens for; the family keeps its bound one

scope?​

Scope

narrower scope to grant

Returns​

Promise<IssuedTokens & object>

new tokens, the rebuilt session and the granted scope


removeAllListeners()​

removeAllListeners<Key>(eventName?): this

Defined in: packages/core/src/events/asynceventemitter.ts:162

Remove all listeners

Type Parameters​

Key​

Key extends never

Parameters​

eventName?​

Key

the event name

Returns​

this

this for chaining

See​

EventEmitter.removeAllListeners

Inherited from​

Service.removeAllListeners


removeListener()​

removeListener<Key>(eventName, listener): this

Defined in: packages/core/src/events/asynceventemitter.ts:140

Remove listener

Type Parameters​

Key​

Key extends never

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.removeListener

Inherited from​

Service.removeListener


resolve()​

resolve(): this

Defined in: packages/core/src/services/token.service.ts:226

Enforce the bearer token scope on every operation. The authorizer is never unregistered, even on stop: a scoped bearer must stay restricted while the service drains or reloads (fail closed). It does nothing for sessions without scopes

Returns​

this

Overrides​

Service.resolve


revokeFamily()​

revokeFamily(family): Promise<void>

Defined in: packages/core/src/services/token.service.ts:637

Revoke family

Parameters​

family​

string

family to revoke

Returns​

Promise<void>


revokeUser()​

revokeUser(userId): Promise<void>

Defined in: packages/core/src/services/token.service.ts:651

Revoke user

Parameters​

userId​

string

user whose tokens are revoked

Returns​

Promise<void>


setMaxListeners()​

setMaxListeners(n): this

Defined in: packages/core/src/events/asynceventemitter.ts:104

Parameters​

n​

number

Returns​

this

Inherited from​

Service.setMaxListeners


stop()​

stop(): Promise<void>

Defined in: packages/core/src/services/token.service.ts:248

Returns​

Promise<void>

Overrides​

Service.stop


sweepRevoked()​

sweepRevoked(): Promise<number>

Defined in: packages/core/src/services/token.service.ts:471

Sweep revoked

Returns​

Promise<number>

number of removed expired entries


toJSON()​

toJSON(): string

Defined in: packages/core/src/services/service.ts:499

Prevent service to be serialized

Returns​

string

the result

Inherited from​

Service.toJSON


toString()​

toString(): string

Defined in: packages/core/src/services/service.ts:238

Return service representation

Returns​

string

the result

Inherited from​

Service.toString


unusedSuccessor()​

protected unusedSuccessor(stored, now): Promise<{ ok: boolean; record?: RefreshToken; }>

Defined in: packages/core/src/services/token.service.ts:615

Whether a rotated token presented again may be rotated once more: within refreshGrace of its rotation, and the token it was exchanged for was never used (not rotated, not revoked; a record that was never written, the issue having failed after the rotation, counts as unused)

Parameters​

stored​

RefreshToken

the rotated token

now​

number

ms

Returns​

Promise<{ ok: boolean; record?: RefreshToken; }>

ok, with the successor's record to retire when it exists


verifyAccess()​

verifyAccess(token, options?): Promise<AccessClaims>

Defined in: packages/core/src/services/token.service.ts:365

Verify access

Parameters​

token​

string

access token

options?​

accepted audience(s), defaults to ACCESS_AUDIENCE (tokens bound to no resource)

audience?​

string | string[]

accepted audience(s)

Returns​

Promise<AccessClaims>

claims, or undefined when invalid/expired