@authup/core-http-kit
Version:
Package containing global constants, types & interfaces.
995 lines (955 loc) • 34.7 kB
JavaScript
import { isClientError as isClientError$1, createClient, isClient, Client as Client$1, HookName, unsetHeader, HeaderName, setHeader, stringifyAuthorizationHeader } from 'hapic';
export { setHeader, unsetHeader } from 'hapic';
import { buildQuery } from 'rapiq';
import { buildIdentityProviderAuthorizePath } from '@authup/core-kit';
import { AuthorizeAPI, TokenAPI, UserInfoAPI } from '@hapic/oauth2';
import { isObject } from '@authup/kit';
import { isJWKErrorCode, isJWTErrorCode } from '@authup/specs';
import { EventEmitter } from '@posva/event-emitter';
import { VaultClient } from '@hapic/vault';
/*
* Copyright (c) 2022-2024.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ var CookieName = /*#__PURE__*/ function(CookieName) {
CookieName["ACCESS_TOKEN"] = "access_token";
CookieName["ACCESS_TOKEN_EXPIRE_DATE"] = "access_token_expire_date";
CookieName["REFRESH_TOKEN"] = "refresh_token";
CookieName["USER"] = "user";
CookieName["REALM"] = "realm";
CookieName["REALM_MANAGEMENT"] = "realm_management";
return CookieName;
}({});
function isClientError(input) {
return isClientError$1(input);
}
/*
* Copyright (c) 2022-2024.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ function cleanDoubleSlashes(input) {
if (input.indexOf('://') !== -1) {
return input.split('://').map((str)=>cleanDoubleSlashes(str)).join('://');
}
return input.replace(/\/+/g, '/');
}
/*
* Copyright (c) 2021-2024.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ function nullifyEmptyObjectProperties(data) {
const keys = Object.keys(data);
for(let i = 0; i < keys.length; i++){
if (data[keys[i]] === '') {
data[keys[i]] = null;
}
}
return data;
}
class BaseAPI {
// -----------------------------------------------------------------------------------
setClient(input) {
this.client = isClient(input) ? input : createClient(input);
}
// -----------------------------------------------------------------------------------
constructor(context){
context = context || {};
this.setClient(context.client);
}
}
class ClientAPI extends BaseAPI {
async getMany(options) {
const response = await this.client.get(`clients${buildQuery(options)}`);
return response.data;
}
async getOne(id, options) {
const response = await this.client.get(`clients/${id}${buildQuery(options)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`clients/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('clients', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`clients/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`clients/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class ClientPermissionAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`client-permissions${buildQuery(data)}`);
return response.data;
}
async getOne(id, data) {
const response = await this.client.get(`client-permissions/${id}${buildQuery(data)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`client-permissions/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('client-permissions', data);
return response.data;
}
}
class ClientRoleAPI extends BaseAPI {
async getMany(data = {}) {
const response = await this.client.get(`client-roles${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`client-roles/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`client-roles/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('client-roles', data);
return response.data;
}
}
class ClientScopeAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`client-scopes${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`client-scopes/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`client-scopes/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('client-scopes', data);
return response.data;
}
}
class IdentityProviderAPI extends BaseAPI {
getAuthorizeUri(id) {
return cleanDoubleSlashes(`${this.client.defaults.baseURL}/${buildIdentityProviderAuthorizePath(id)}`);
}
async getMany(record) {
const response = await this.client.get(`identity-providers${buildQuery(record)}`);
return response.data;
}
async getOne(id, record) {
const response = await this.client.get(`identity-providers/${id}${buildQuery(record)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`identity-providers/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('identity-providers', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`identity-providers/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`identity-providers/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class IdentityProviderRoleMappingAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`identity-provider-role-mappings${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`identity-provider-role-mappings/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`identity-provider-role-mappings/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('identity-provider-role-mappings', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`identity-provider-role-mappings/${id}`, data);
return response.data;
}
}
class PolicyAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`policies${buildQuery(data)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`policies/${id}`);
return response.data;
}
async getOne(id, record) {
const response = await this.client.get(`policies/${id}${buildQuery(record)}`);
return response.data;
}
async getOneExpanded(id, record) {
const response = await this.client.get(`policies/${id}/expanded${buildQuery(record)}`);
return response.data;
}
async create(data) {
const response = await this.client.post('policies', nullifyEmptyObjectProperties(data));
return response.data;
}
async createBuiltIn(data) {
return this.create(data);
}
async update(id, data) {
const response = await this.client.post(`policies/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async updateBuiltIn(id, data) {
return this.update(id, data);
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`policies/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdateBuiltin(idOrName, data) {
return this.createOrUpdate(idOrName, data);
}
async check(idOrName, data = {}) {
const response = await this.client.post(`policies/${idOrName}/check`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class PermissionAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`permissions${buildQuery(data)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`permissions/${id}`);
return response.data;
}
async getOne(id, record) {
const response = await this.client.get(`permissions/${id}${buildQuery(record)}`);
return response.data;
}
async create(data) {
const response = await this.client.post('permissions', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`permissions/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`permissions/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async check(idOrName, data = {}) {
const response = await this.client.post(`permissions/${idOrName}/check`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class RealmAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`realms${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`realms/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`realms/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('realms', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(realmId, data) {
const response = await this.client.post(`realms/${realmId}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`realms/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class RobotAPI extends BaseAPI {
async getMany(options) {
const response = await this.client.get(`robots${buildQuery(options)}`);
return response.data;
}
async getOne(id, options) {
const response = await this.client.get(`robots/${id}${buildQuery(options)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`robots/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('robots', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`robots/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`robots/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async integrity(id) {
const { data: response } = await this.client.get(`robots/${id}/integrity`);
return response;
}
}
class RobotPermissionAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`robot-permissions${buildQuery(data)}`);
return response.data;
}
async getOne(id, data) {
const response = await this.client.get(`robot-permissions/${id}${buildQuery(data)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`robot-permissions/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('robot-permissions', data);
return response.data;
}
}
class RobotRoleAPI extends BaseAPI {
async getMany(data = {}) {
const response = await this.client.get(`robot-roles${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`robot-roles/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`robot-roles/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('robot-roles', data);
return response.data;
}
}
class RoleAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`roles${buildQuery(data)}`);
return response.data;
}
async getOne(roleId) {
const response = await this.client.get(`roles/${roleId}`);
return response.data;
}
async delete(roleId) {
const response = await this.client.delete(`roles/${roleId}`);
return response.data;
}
async create(data) {
const response = await this.client.post('roles', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`roles/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`roles/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class RoleAttributeAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`role-attributes${buildQuery(data)}`);
return response.data;
}
async getOne(roleId) {
const response = await this.client.get(`role-attributes/${roleId}`);
return response.data;
}
async delete(roleId) {
const response = await this.client.delete(`role-attributes/${roleId}`);
return response.data;
}
async create(data) {
const response = await this.client.post('role-attributes', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`role-attributes/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class RolePermissionAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`role-permissions${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`role-permissions/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`role-permissions/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('role-permissions', data);
return response.data;
}
}
class ScopeAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`scopes${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`scopes/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`scopes/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('scopes', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`scopes/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`scopes/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class UserAPI extends BaseAPI {
async getMany(options) {
const response = await this.client.get(`users${buildQuery(options)}`);
return response.data;
}
async getOne(id, options) {
const response = await this.client.get(`users/${id}${buildQuery(options)}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`users/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('users', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`users/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
async createOrUpdate(idOrName, data) {
const response = await this.client.put(`users/${idOrName}`, nullifyEmptyObjectProperties(data));
return response.data;
}
// ---------------------------------------------------------------------------
async activate(token) {
const response = await this.client.post('users/activate', {
token
});
return response.data;
}
async register(data) {
const response = await this.client.post('users/register', nullifyEmptyObjectProperties(data));
return response.data;
}
async passwordForgot(data) {
const response = await this.client.post('users/password-forgot', nullifyEmptyObjectProperties(data));
return response.data;
}
async passwordReset(data) {
const response = await this.client.post('users/password-reset', nullifyEmptyObjectProperties(data));
return response.data;
}
}
class UserAttributeAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`user-attributes${buildQuery(data)}`);
return response.data;
}
async getOne(roleId) {
const response = await this.client.get(`user-attributes/${roleId}`);
return response.data;
}
async delete(roleId) {
const response = await this.client.delete(`user-attributes/${roleId}`);
return response.data;
}
async create(data) {
const response = await this.client.post('user-attributes', nullifyEmptyObjectProperties(data));
return response.data;
}
async update(id, data) {
const response = await this.client.post(`user-attributes/${id}`, nullifyEmptyObjectProperties(data));
return response.data;
}
}
class UserPermissionAPI extends BaseAPI {
async getMany(data) {
const response = await this.client.get(`user-permissions${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`user-permissions/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`user-permissions/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('user-permissions', nullifyEmptyObjectProperties(data));
return response.data;
}
}
class UserRoleAPI extends BaseAPI {
async getMany(data = {}) {
const response = await this.client.get(`user-roles${buildQuery(data)}`);
return response.data;
}
async getOne(id) {
const response = await this.client.get(`user-roles/${id}`);
return response.data;
}
async delete(id) {
const response = await this.client.delete(`user-roles/${id}`);
return response.data;
}
async create(data) {
const response = await this.client.post('user-roles', data);
return response.data;
}
}
class OAuth2AuthorizeAPI extends AuthorizeAPI {
async confirm(data) {
const response = await this.client.post('authorize', nullifyEmptyObjectProperties(data));
return response.data;
}
}
class OAuth2TokenAPI extends TokenAPI {
}
class OAuth2UserInfoAPI extends UserInfoAPI {
}
class Client extends Client$1 {
async getJwks() {
const response = await this.get('jwks');
return response.data;
}
async getJwk(id) {
const response = await this.get(`jwks/${id}`);
return response.data;
}
async getWellKnownOpenIDConfiguration() {
const response = await this.get('/.well-known/openid-configuration');
return response.data;
}
constructor(config = {}){
super(config);
const options = {
authorizationEndpoint: 'authorize',
introspectionEndpoint: 'token/introspect',
tokenEndpoint: 'token',
userinfoEndpoint: 'users/@me'
};
const baseURL = this.getBaseURL();
if (typeof baseURL === 'string') {
const keys = Object.keys(options);
for(let i = 0; i < keys.length; i++){
options[keys[i]] = new URL(options[keys[i]], baseURL).href;
}
}
this.authorize = new OAuth2AuthorizeAPI({
client: this,
options
});
this.token = new OAuth2TokenAPI({
client: this,
options
});
this.client = new ClientAPI({
client: this
});
this.clientPermission = new ClientPermissionAPI({
client: this
});
this.clientRole = new ClientRoleAPI({
client: this
});
this.clientScope = new ClientScopeAPI({
client: this
});
this.identityProvider = new IdentityProviderAPI({
client: this
});
this.identityProviderRoleMapping = new IdentityProviderRoleMappingAPI({
client: this
});
this.policy = new PolicyAPI({
client: this
});
this.permission = new PermissionAPI({
client: this
});
this.realm = new RealmAPI({
client: this
});
this.robot = new RobotAPI({
client: this
});
this.robotPermission = new RobotPermissionAPI({
client: this
});
this.robotRole = new RobotRoleAPI({
client: this
});
this.role = new RoleAPI({
client: this
});
this.roleAttribute = new RoleAttributeAPI({
client: this
});
this.rolePermission = new RolePermissionAPI({
client: this
});
this.scope = new ScopeAPI({
client: this
});
this.user = new UserAPI({
client: this
});
this.userInfo = new OAuth2UserInfoAPI({
client: this,
options
});
this.userAttribute = new UserAttributeAPI({
client: this
});
this.userPermission = new UserPermissionAPI({
client: this
});
this.userRole = new UserRoleAPI({
client: this
});
this.on(HookName.RESPONSE_ERROR, (error)=>{
if (isClientError$1(error) && error.response && error.response.data && typeof error.response.data.message === 'string') {
error.message = error.response.data.message;
}
throw error;
});
}
}
function getClientErrorCode(err) {
if (!isObject(err) || !isObject(err.response)) {
return null;
}
/* istanbul ignore next */ if (!isObject(err.response.data) || typeof err.response.data.code !== 'string') {
return null;
}
return err.response.data.code;
}
/*
* Copyright (c) 2025.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ var ClientAuthenticationHookEventName = /*#__PURE__*/ function(ClientAuthenticationHookEventName) {
ClientAuthenticationHookEventName["REFRESH_FINISHED"] = "refreshFinished";
ClientAuthenticationHookEventName["REFRESH_FAILED"] = "refreshFailed";
ClientAuthenticationHookEventName["HEADER_SET"] = "headerSet";
ClientAuthenticationHookEventName["HEADER_UNSET"] = "headerRemoved";
return ClientAuthenticationHookEventName;
}({});
/*
* Copyright (c) 2023-2024.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ var TokenCreatorVariation = /*#__PURE__*/ function(TokenCreatorVariation) {
TokenCreatorVariation["USER"] = "user";
TokenCreatorVariation["ROBOT"] = "robot";
TokenCreatorVariation["ROBOT_IN_VAULT"] = "robotInVault";
return TokenCreatorVariation;
}({});
function createTokenCreatorWithRobot(options, client) {
const api = client || new Client({
baseURL: options.baseURL
});
return async ()=>api.token.createWithRobotCredentials({
id: options.id,
secret: options.secret
}).then((response)=>{
if (options.created) {
options.created(response);
}
return response;
});
}
function createTokenCreatorWithRobotInVault(options) {
let client;
if (typeof options.vault === 'string') {
client = new VaultClient({
connectionString: options.vault
});
} else {
client = options.vault;
}
const apiClient = new Client({
baseURL: options.baseURL
});
const robotName = options.name.toLowerCase();
return async ()=>{
if (apiClient) {
await apiClient.robot.integrity(robotName);
}
const response = await client.keyValueV1.getOne('robots', robotName);
if (!isObject(response) || !isObject(response.data) || typeof response.data.id !== 'string' || typeof response.data.secret !== 'string') {
throw new Error('The vault robot credentials response is malformed.');
}
const creator = createTokenCreatorWithRobot({
id: response.data.id,
secret: response.data.secret
}, apiClient);
return creator().then((response)=>{
if (options.created) {
options.created(response);
}
return response;
});
};
}
function createTokenCreatorWithUser(options) {
const client = new Client({
baseURL: options.baseURL
});
return async ()=>client.token.createWithPassword({
username: options.name,
password: options.password,
...options.realmId ? {
realm_id: options.realmId
} : {},
...options.realmName ? {
realm_name: options.realmName
} : {}
}).then((response)=>{
if (options.created) {
options.created(response);
}
return response;
});
}
function createTokenCreator(options) {
switch(options.type){
case TokenCreatorVariation.USER:
{
return createTokenCreatorWithUser(options);
}
case TokenCreatorVariation.ROBOT:
{
return createTokenCreatorWithRobot(options);
}
case TokenCreatorVariation.ROBOT_IN_VAULT:
{
return createTokenCreatorWithRobotInVault(options);
}
}
return undefined;
}
/*
* Copyright (c) 2023-2024.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/ function getClientRequestRetryState(config) {
const currentState = config.retry || {};
currentState.retryCount = currentState.retryCount || 0;
config.retry = currentState;
return currentState;
}
const HOOK_SYMBOL = Symbol.for('ClientResponseHook');
class ClientAuthenticationHook extends EventEmitter {
// ------------------------------------------------
enable() {
this.isActive = true;
}
disable() {
this.isActive = false;
}
// ------------------------------------------------
setAuthorizationHeader(value) {
this.authorizationHeader = value;
for(let i = 0; i < this.clients.length; i++){
this.clients[i].setAuthorizationHeader(value);
}
this.emit(ClientAuthenticationHookEventName.HEADER_SET);
}
unsetAuthorizationHeader() {
this.authorizationHeader = undefined;
for(let i = 0; i < this.clients.length; i++){
this.clients[i].unsetAuthorizationHeader();
}
this.emit(ClientAuthenticationHookEventName.HEADER_UNSET);
}
// ------------------------------------------------
isAttached(client) {
return HOOK_SYMBOL in client;
}
attach(client) {
if (this.authorizationHeader) {
client.setAuthorizationHeader(this.authorizationHeader);
} else {
client.unsetAuthorizationHeader();
}
const index = this.clients.indexOf(client);
if (index === -1) {
this.clients.push(client);
}
if (!this.isAttached(client)) {
client[HOOK_SYMBOL] = client.on(HookName.RESPONSE_ERROR, (err)=>{
if (!this.isActive) {
return Promise.reject(err);
}
const { request } = err;
const currentState = getClientRequestRetryState(request);
if (currentState.retryCount > 0) {
return Promise.reject(err);
}
currentState.retryCount += 1;
const code = getClientErrorCode(err);
if (isJWKErrorCode(code)) {
this.unsetAuthorizationHeader();
if (request.headers) {
unsetHeader(request.headers, HeaderName.AUTHORIZATION);
}
return Promise.reject(err);
}
if (isJWTErrorCode(code) || isObject(err.response) && err.response.status === 401) {
return this.refresh().then((response)=>{
if (request.headers) {
setHeader(request.headers, HeaderName.AUTHORIZATION, stringifyAuthorizationHeader({
type: 'Bearer',
token: response.access_token
}));
}
return client.request(request);
}).catch((err)=>{
if (request.headers) {
unsetHeader(request.headers, HeaderName.AUTHORIZATION);
}
return Promise.reject(err);
});
}
return Promise.reject(err);
});
}
}
detach(client) {
client.unsetAuthorizationHeader();
const index = this.clients.indexOf(client);
if (index !== -1) {
this.clients.splice(index, 1);
}
if (this.isAttached(client)) {
client.off(HookName.RESPONSE_ERROR, client[HOOK_SYMBOL]);
delete client[HOOK_SYMBOL];
}
}
// ------------------------------------------------
setTimer(expiresIn) {
if (!this.options.timer) {
return;
}
this.clearTimer();
const refreshInMs = (expiresIn - 60) * 1000;
if (refreshInMs > 0) {
this.timer = setTimeout(async ()=>this.refresh(), refreshInMs);
}
}
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
}
}
// ------------------------------------------------
/**
* Refresh token
*
* @throws ClientError
*/ async refresh() {
if (this.refreshPromise) {
return this.refreshPromise;
}
this.refreshPromise = this.creator();
return this.refreshPromise.then((response)=>{
this.setTimer(response.expires_in);
this.emit(ClientAuthenticationHookEventName.REFRESH_FINISHED, response);
this.refreshPromise = undefined;
this.setAuthorizationHeader({
type: 'Bearer',
token: response.access_token
});
return response;
}).catch((e)=>{
if (isClientError$1(e)) {
this.emit(ClientAuthenticationHookEventName.REFRESH_FAILED, e);
} else {
this.emit(ClientAuthenticationHookEventName.REFRESH_FAILED, null);
}
this.refreshPromise = undefined;
this.unsetAuthorizationHeader();
return Promise.reject(e);
});
}
// ------------------------------------------------
constructor(options){
var _options;
super();
this.isActive = true;
this.authorizationHeader = undefined;
this.clients = [];
(_options = options).timer ?? (_options.timer = true);
this.options = options;
let creator;
if (typeof options.tokenCreator === 'function') {
creator = options.tokenCreator;
} else {
creator = createTokenCreator({
...options.tokenCreator,
baseURL: options.baseURL
});
}
this.creator = creator;
}
}
export { BaseAPI, Client, ClientAPI, ClientAuthenticationHook, ClientAuthenticationHookEventName, ClientPermissionAPI, ClientRoleAPI, ClientScopeAPI, CookieName, IdentityProviderAPI, IdentityProviderRoleMappingAPI, OAuth2AuthorizeAPI, OAuth2TokenAPI, OAuth2UserInfoAPI, PermissionAPI, PolicyAPI, RealmAPI, RobotAPI, RobotPermissionAPI, RobotRoleAPI, RoleAPI, RoleAttributeAPI, RolePermissionAPI, ScopeAPI, TokenCreatorVariation, UserAPI, UserAttributeAPI, UserPermissionAPI, UserRoleAPI, createTokenCreator, getClientErrorCode, getClientRequestRetryState, isClientError };
//# sourceMappingURL=index.mjs.map