Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)

## [7.1.0] - 2026-10-07

### Changed

- Add an option to provide whitelisted domains in httpClient. Auth Bearer token won't be forwarded if the urls don't belong to the whitelisted domains.

## [7.0.6] - 2026-01-19

### Changed
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lambda-essentials-ts",
"version": "7.0.6",
"version": "7.1.0",
"description": "A selection of the finest modules supporting authorization, API routing, error handling, logging and sending HTTP requests.",
"main": "lib/index.js",
"private": false,
Expand Down Expand Up @@ -29,7 +29,7 @@
"@aws-sdk/client-kms": "^3.930.0",
"@aws-sdk/client-secrets-manager": "^3.930.0",
"@types/node": "^25.0.3",
"axios": "1.13.2",
"axios": "1.18.0",
"axios-cache-interceptor": "1.11.2",
"fast-safe-stringify": "~2.1.1",
"is-error": "~2.2.2",
Expand Down
72 changes: 70 additions & 2 deletions src/httpClient/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
RawAxiosRequestHeaders,
} from 'axios';
import * as rax from 'retry-axios';
Expand Down Expand Up @@ -45,6 +46,8 @@ export default class HttpClient {

private readonly clientExceptionStatusCodeMapOverride?: Record<number, number>;

private readonly whitelistedDomains?: string[];

/**
* Create a new Instance of the HttpClient
*/
Expand All @@ -60,6 +63,7 @@ export default class HttpClient {
this.timeout = options?.timeout;
this.clientExceptionStatusCodeMapOverride = options?.clientExceptionStatusCodeMapOverride;
this.client = options?.client ?? axios.create();
this.whitelistedDomains = options?.whitelistedDomains;

if (this.enableCache) {
setupCache(this.client, {
Expand Down Expand Up @@ -112,6 +116,7 @@ export default class HttpClient {
if (!config.url) {
throw new InternalException('HttpClient Error: "url" must be defined');
}
this.stripAuthHeaderIfNotWhitelisted(config);
return config;
},
(error: AxiosError) => {
Expand Down Expand Up @@ -212,6 +217,33 @@ export default class HttpClient {
return `${key}${req.data ? md5(req.data) : ''}`;
}

/**
* Checks whether the given url's hostname exactly matches or is a subdomain of, one of the whitelistedDomains.
* If no whitelistedDomains were provided, all urls are considered whitelisted.
*/
private isUrlWhitelisted(url: string, config?: AxiosRequestConfig): boolean {
if (!this.whitelistedDomains) {
return true;
}

let hostname: string;
try {
const resolvedUrl = config ? this.client.getUri({ ...config, url, params: null }) : url;
hostname = new URL(resolvedUrl).hostname.toLowerCase();
} catch {
Comment thread
matushudec marked this conversation as resolved.
return false;
}

return this.whitelistedDomains.some((domain) => {
const normalizedDomain = domain.toLowerCase();

return (
normalizedDomain.length > 0 &&
(hostname === normalizedDomain || hostname.endsWith(`.${normalizedDomain}`))
);
});
}

/**
* Resolves the token with the token provider and adds it to the headers
*/
Expand All @@ -224,7 +256,12 @@ export default class HttpClient {
}

if (this.tokenResolverFunction) {
if (headers && headers.Authorization) {
if (
headers &&
Object.entries(headers).some(
([header, value]) => header.toLowerCase() === 'authorization' && value,
)
) {
throw new InternalException(
'Authorization header already specified, please create a new HttpClient with a different (or without a) tokenResolver',
);
Expand All @@ -240,17 +277,44 @@ export default class HttpClient {
};
}

/**
* Removes the Authorization header when the url is not whitelisted (only applies if whitelistedDomains was configured)
*/
private stripAuthHeaderIfNotWhitelisted(config: InternalAxiosRequestConfig): void {
if (!this.whitelistedDomains) {
return;
}

if (!this.isUrlWhitelisted(config.url ?? '', config)) {
config.headers.delete('Authorization');
}

const beforeRedirect = config.beforeRedirect;
config.beforeRedirect = (options, responseDetails, requestDetails) => {
beforeRedirect?.(options, responseDetails, requestDetails);

if (!this.isUrlWhitelisted(options.href)) {
Object.keys(options.headers ?? {}).forEach((header) => {
if (header.toLowerCase() === 'authorization') {
delete options.headers[header];
}
});
}
};
}

/**
* Get from the given url. Bearer token is automatically injected if tokenResolverFunction was provided to the constructor.
*/
async get<T = any>(
url: string,
config: AxiosRequestConfig = { responseType: 'json' },
): Promise<AxiosResponse<T>> {
const headers = await this.createHeadersWithResolvedToken(config.headers);
return this.client.get<T>(url, {
responseType: 'json',
...config,
headers: await this.createHeadersWithResolvedToken(config.headers),
headers,
});
}

Expand Down Expand Up @@ -364,6 +428,10 @@ export interface HttpClientOptions {
* This is useful, when dependent services return incorrect status codes than then drive incorrect behavior upstream (e.g. 403 instead of 503)
*/
clientExceptionStatusCodeMapOverride?: Record<number, number>;
/**
* If provided forwards JWT token only to whitelisted domains
*/
whitelistedDomains?: string[];
}

/**
Expand Down
Loading
Loading