Commit iniziale

This commit is contained in:
Paolo A
2025-02-18 22:59:07 +00:00
commit 4bbf35cefb
6879 changed files with 623784 additions and 0 deletions

21
node_modules/@azure/msal-node/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

188
node_modules/@azure/msal-node/README.md generated vendored Normal file
View File

@@ -0,0 +1,188 @@
# Microsoft Authentication Library for Node (msal-node)
[![npm version](https://img.shields.io/npm/v/@azure/msal-node.svg?style=flat)](https://www.npmjs.com/package/@azure/msal-node/)
[![npm version](https://img.shields.io/npm/dm/@azure/msal-node.svg)](https://nodei.co/npm/@azure/msal-node/)
[![codecov](https://codecov.io/gh/AzureAD/microsoft-authentication-library-for-js/branch/dev/graph/badge.svg?flag=msal-node)](https://codecov.io/gh/AzureAD/microsoft-authentication-library-for-js)
| <a href="https://docs.microsoft.com/azure/active-directory/develop/guidedsetups/active-directory-javascriptspa" target="_blank">Getting Started</a> | <a href="https://aka.ms/aaddevv2" target="_blank">AAD Docs</a> | <a href="https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_node.html" target="_blank">Library Reference</a> |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
1. [About](#about)
1. [FAQ](#faq)
1. [Changelog](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/CHANGELOG.md)
1. [Prerequisites](#prerequisites)
1. [Installation](#installation)
1. [Node Version Support](#node-version-support)
1. [Usage](#usage)
1. [Samples](#samples)
1. [Build Library](#build-and-test)
1. [Security Reporting](#security-reporting)
1. [License](#license)
1. [Code of Conduct](#we-value-and-adhere-to-the-microsoft-open-source-code-of-conduct)
## About
MSAL Node enables applications to authenticate users using [Azure AD](https://docs.microsoft.com/azure/active-directory/develop/v2-overview) work and school accounts (AAD), Microsoft personal accounts (MSA) and social identity providers like Facebook, Google, LinkedIn, Microsoft accounts, etc. through [Azure AD B2C](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-overview#identity-providers) service. It also enables your app to get tokens to access [Microsoft Cloud](https://www.microsoft.com/enterprise) services such as [Microsoft Graph](https://graph.microsoft.io).
### OAuth2.0 grant types supported:
The current version supports the following ways of acquiring tokens:
#### Public Client:
- [Authorization Code Grant](https://oauth.net/2/grant-types/authorization-code/) with [PKCE](https://oauth.net/2/pkce/)
- [Device Code Grant](https://oauth.net/2/grant-types/device-code/)
- [Refresh Token Grant](https://oauth.net/2/grant-types/refresh-token/)
- [Silent Flow](https://docs.microsoft.com/azure/active-directory/develop/msal-acquire-cache-tokens#acquiring-tokens-silently-from-the-cache)
- [Username and Password flow](https://docs.microsoft.com/azure/active-directory/develop/msal-authentication-flows#usernamepassword)
#### Confidential Client:
- [Authorization Code Grant](https://oauth.net/2/grant-types/authorization-code/) with a client credential
- [Refresh Token Grant](https://oauth.net/2/grant-types/refresh-token/)
- [Silent Flow](https://docs.microsoft.com/azure/active-directory/develop/msal-acquire-cache-tokens#acquiring-tokens-silently-from-the-cache)
- [Client Credential Grant](https://oauth.net/2/grant-types/client-credentials/)
- [On-behalf-of flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow)
- [Username and Password flow](https://docs.microsoft.com/azure/active-directory/develop/msal-authentication-flows#usernamepassword)
More details on different grant types supported by Microsoft authentication libraries in general can be found [here](https://docs.microsoft.com/azure/active-directory/develop/msal-authentication-flows).
### Scenarios supported:
The scenarios supported with this library are:
- Desktop app that calls web APIs
- Web app that calls web APIs
- Web APIs that call web APIs
- Daemon apps
More details on scenarios and the authentication flows that map to each of them can be found [here](https://docs.microsoft.com/azure/active-directory/develop/authentication-flows-app-scenarios).
## FAQ
See [here](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/faq.md).
## Prerequisites
Before using `@azure/msal-node` you will need to register your app in the azure portal:
- [App registration](https://docs.microsoft.com/graph/auth-register-app-v2)
## Installation
### Via NPM:
```javascript
npm install @azure/msal-node
```
## Node Version Support
MSAL Node will follow the [Long Term Support (LTS) schedule of the Node.js project](https://nodejs.org/about/releases/). Our support plan is as follows.
Any major MSAL Node release:
- Will support stable (even-numbered) Maintenance LTS, Active LTS, and Current versions of Node
- Will drop support for any previously supported Node versions that have reached end of life
- Will not support prerelease/preview/pending versions until they are stable
| MSAL Node version | MSAL support status | Supported Node versions |
| ----------------- | ------------------- | ----------------------- |
| 2.x.x | Active development | 16, 18, 20, 22 |
| 1.x.x | In maintenance | 10, 12, 14, 16, 18 |
**Note:** There have been no functional changes in the MSAL Node v2 release.
## Usage
### MSAL basics
- [Understand difference in between Public Client and Confidential Clients](https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications)
- [Initialize a Public Client Application](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/initialize-public-client-application.md)
- [Initialize a Confidential Client Application](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/initialize-confidential-client-application.md)
- [Configuration](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md)
- [Request](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/request.md)
- [Response](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Response.md)
## Samples
There are multiple [samples](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples) included in the repository that use MSAL Node to acquire tokens. These samples are currently used for manual testing, and are not meant to be a reference of best practices, therefore use judgement and do not blindly copy this code to any production applications.
AAD samples:
- [auth-code](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/auth-code): Express app using OAuth2.0 authorization code flow.
- [auth-code-pkce](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/auth-code-pkce): Express app using OAuth2.0 authorization code flow with PKCE.
- [device-code](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/device-code): Command line app using OAuth 2.0 device code flow.
- [refresh-token](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/refresh-token): Command line app using OAuth 2.0 refresh flow.
- [silent-flow](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/silent-flow): Express app using OAuth2.0 authorization code flow to acquire a token and store in the token cache, and silent flow to use tokens in the token cache.
- [client-credentials](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/client-credentials): Daemon app using OAuth 2.0 client credential grant to acquire a token.
- [on-behalf-of](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/on-behalf-of): Web application using OAuth 2.0 auth code flow to acquire a token for a web API. The web API validates the token, and calls Microsoft Graph on behalf of the user who authenticated in the web application.
- [username-password](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/username-password): Web application using OAuth 2.0 resource owner password credentials (ROPC) flow to acquire a token for a web API.
- [ElectronTestApp](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/ElectronTestApp): Electron desktop application using OAuth 2.0 auth code with PKCE flow to acquire a token for a web API such as Microsoft Graph.
- [Hybrid Spa Sample](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-browser-samples/HybridSample): Sample demonstrating how to use `enableSpaAuthorizationCode` to perform SSO for applications that leverage server-side and client-side authentication using MSAL Browser and MSAL Node.
B2C samples:
- [b2c-user-flows](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-node-samples/b2c-user-flows): Express app using OAuth2.0 authorization code flow.
Others:
- [msal-node-extensions](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/extensions/samples/msal-node-extensions): Uses authorization code flow to acquire tokens and the [msal-extensions](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/extensions/) library to write the MSAL in-memory token cache to disk.
## Build and Test
```javascript
// Install dependencies from root of repo
npm install
// Change to the msal-node package directory
cd lib/msal-node
// To run build for common package & node package
npm run build:all
// To run build only for node package
npm run build
// To run tests
npm run test
```
### Local Development
Below is a list of commands you will probably find useful:
#### `npm run build:modules:watch`
Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for you convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab. The library will be rebuilt if you make edits.
#### `npm run build`
Bundles the package to the `dist` folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).
#### `npm run build:all`
Builds both `msal-common` and `msal-node`
#### `npm run lint`
Runs eslint with Prettier
#### `npm test`, `npm run test:coverage`, `npm run test:watch`
Runs the test watcher (Jest) in an interactive mode.
By default, runs tests related to files changed since the last commit.
Generate code coverage by adding the flag --coverage. No additional setup needed. Jest can collect code coverage information from entire projects, including untested files.
## Security Reporting
If you find a security issue with our libraries or services please report it to [secure@microsoft.com](mailto:secure@microsoft.com) with as much detail as possible. Your submission may be eligible for a bounty through the [Microsoft Bounty](http://aka.ms/bugbounty) program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting [this page](https://technet.microsoft.com/security/dd252948) and subscribing to Security Advisory Alerts.
## License
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.
## We Value and Adhere to the Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

View File

@@ -0,0 +1,16 @@
import { AccountInfo } from "@azure/msal-common/node";
/**
* Token cache interface for the client, giving access to cache APIs
* @public
*/
export interface ITokenCache {
/** API that retrieves all accounts currently in cache to the user */
getAllAccounts(): Promise<AccountInfo[]>;
/** Returns the signed in account matching homeAccountId */
getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>;
/** Returns the signed in account matching localAccountId */
getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>;
/** API to remove a specific account and the relevant data from cache */
removeAccount(account: AccountInfo): Promise<void>;
}
//# sourceMappingURL=ITokenCache.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ITokenCache.d.ts","sourceRoot":"","sources":["../../src/cache/ITokenCache.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,WAAW;IACxB,qEAAqE;IACrE,cAAc,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAEzC,2DAA2D;IAC3D,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAEvE,4DAA4D;IAC5D,mBAAmB,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAEzE,wEAAwE;IACxE,aAAa,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtD"}

View File

@@ -0,0 +1,194 @@
import { TokenKeys, AccountEntity, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, ServerTelemetryEntity, ThrottlingEntity, CacheManager, Logger, ValidCacheType, ICrypto, AuthorityMetadataEntity, ValidCredentialType, StaticAuthorityOptions } from "@azure/msal-common/node";
import { InMemoryCache, JsonCache, CacheKVStore } from "./serializer/SerializerTypes.js";
/**
* This class implements Storage for node, reading cache from user specified storage location or an extension library
* @public
*/
export declare class NodeStorage extends CacheManager {
private logger;
private cache;
private changeEmitters;
constructor(logger: Logger, clientId: string, cryptoImpl: ICrypto, staticAuthorityOptions?: StaticAuthorityOptions);
/**
* Queue up callbacks
* @param func - a callback function for cache change indication
*/
registerChangeEmitter(func: () => void): void;
/**
* Invoke the callback when cache changes
*/
emitChange(): void;
/**
* Converts cacheKVStore to InMemoryCache
* @param cache - key value store
*/
cacheToInMemoryCache(cache: CacheKVStore): InMemoryCache;
/**
* converts inMemoryCache to CacheKVStore
* @param inMemoryCache - kvstore map for inmemory
*/
inMemoryCacheToCache(inMemoryCache: InMemoryCache): CacheKVStore;
/**
* gets the current in memory cache for the client
*/
getInMemoryCache(): InMemoryCache;
/**
* sets the current in memory cache for the client
* @param inMemoryCache - key value map in memory
*/
setInMemoryCache(inMemoryCache: InMemoryCache): void;
/**
* get the current cache key-value store
*/
getCache(): CacheKVStore;
/**
* sets the current cache (key value store)
* @param cacheMap - key value map
*/
setCache(cache: CacheKVStore): void;
/**
* Gets cache item with given key.
* @param key - lookup key for the cache entry
*/
getItem(key: string): ValidCacheType;
/**
* Gets cache item with given key-value
* @param key - lookup key for the cache entry
* @param value - value of the cache entry
*/
setItem(key: string, value: ValidCacheType): void;
getAccountKeys(): string[];
getTokenKeys(): TokenKeys;
/**
* fetch the account entity
* @param accountKey - lookup key to fetch cache type AccountEntity
*/
getAccount(accountKey: string): AccountEntity | null;
/**
* Reads account from cache, builds it into an account entity and returns it.
* @param accountKey - lookup key to fetch cache type AccountEntity
* @returns
*/
getCachedAccountEntity(accountKey: string): AccountEntity | null;
/**
* set account entity
* @param account - cache value to be set of type AccountEntity
*/
setAccount(account: AccountEntity): void;
/**
* fetch the idToken credential
* @param idTokenKey - lookup key to fetch cache type IdTokenEntity
*/
getIdTokenCredential(idTokenKey: string): IdTokenEntity | null;
/**
* set idToken credential
* @param idToken - cache value to be set of type IdTokenEntity
*/
setIdTokenCredential(idToken: IdTokenEntity): void;
/**
* fetch the accessToken credential
* @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity
*/
getAccessTokenCredential(accessTokenKey: string): AccessTokenEntity | null;
/**
* set accessToken credential
* @param accessToken - cache value to be set of type AccessTokenEntity
*/
setAccessTokenCredential(accessToken: AccessTokenEntity): void;
/**
* fetch the refreshToken credential
* @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity
*/
getRefreshTokenCredential(refreshTokenKey: string): RefreshTokenEntity | null;
/**
* set refreshToken credential
* @param refreshToken - cache value to be set of type RefreshTokenEntity
*/
setRefreshTokenCredential(refreshToken: RefreshTokenEntity): void;
/**
* fetch appMetadata entity from the platform cache
* @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity
*/
getAppMetadata(appMetadataKey: string): AppMetadataEntity | null;
/**
* set appMetadata entity to the platform cache
* @param appMetadata - cache value to be set of type AppMetadataEntity
*/
setAppMetadata(appMetadata: AppMetadataEntity): void;
/**
* fetch server telemetry entity from the platform cache
* @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity
*/
getServerTelemetry(serverTelemetrykey: string): ServerTelemetryEntity | null;
/**
* set server telemetry entity to the platform cache
* @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity
* @param serverTelemetry - cache value to be set of type ServerTelemetryEntity
*/
setServerTelemetry(serverTelemetryKey: string, serverTelemetry: ServerTelemetryEntity): void;
/**
* fetch authority metadata entity from the platform cache
* @param key - lookup key to fetch cache type AuthorityMetadataEntity
*/
getAuthorityMetadata(key: string): AuthorityMetadataEntity | null;
/**
* Get all authority metadata keys
*/
getAuthorityMetadataKeys(): Array<string>;
/**
* set authority metadata entity to the platform cache
* @param key - lookup key to fetch cache type AuthorityMetadataEntity
* @param metadata - cache value to be set of type AuthorityMetadataEntity
*/
setAuthorityMetadata(key: string, metadata: AuthorityMetadataEntity): void;
/**
* fetch throttling entity from the platform cache
* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
*/
getThrottlingCache(throttlingCacheKey: string): ThrottlingEntity | null;
/**
* set throttling entity to the platform cache
* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
* @param throttlingCache - cache value to be set of type ThrottlingEntity
*/
setThrottlingCache(throttlingCacheKey: string, throttlingCache: ThrottlingEntity): void;
/**
* Removes the cache item from memory with the given key.
* @param key - lookup key to remove a cache entity
* @param inMemory - key value map of the cache
*/
removeItem(key: string): boolean;
/**
* Remove account entity from the platform cache if it's outdated
* @param accountKey - lookup key to fetch cache type AccountEntity
*/
removeOutdatedAccount(accountKey: string): void;
/**
* Checks whether key is in cache.
* @param key - look up key for a cache entity
*/
containsKey(key: string): boolean;
/**
* Gets all keys in window.
*/
getKeys(): string[];
/**
* Clears all cache entries created by MSAL (except tokens).
*/
clear(): void;
/**
* Initialize in memory cache from an exisiting cache vault
* @param cache - blob formatted cache (JSON)
*/
static generateInMemoryCache(cache: string): InMemoryCache;
/**
* retrieves the final JSON
* @param inMemoryCache - itemised cache read from the JSON
*/
static generateJsonCache(inMemoryCache: InMemoryCache): JsonCache;
/**
* Updates a credential's cache key if the current cache key is outdated
*/
updateCredentialCacheKey(currentCacheKey: string, credential: ValidCredentialType): string;
}
//# sourceMappingURL=NodeStorage.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"NodeStorage.d.ts","sourceRoot":"","sources":["../../src/cache/NodeStorage.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,SAAS,EACT,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AavE;;;;OAIG;IACH,kBAAkB,CACd,kBAAkB,EAAE,MAAM,EAC1B,eAAe,EAAE,gBAAgB,GAClC,IAAI;IAIP;;;;OAIG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAoBhC;;;OAGG;IACH,qBAAqB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAI/C;;;OAGG;IACH,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAIjC;;OAEG;IACH,OAAO,IAAI,MAAM,EAAE;IAQnB;;OAEG;IACH,KAAK,IAAI,IAAI;IAab;;;OAGG;IACH,MAAM,CAAC,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa;IAM1D;;;OAGG;IACH,MAAM,CAAC,iBAAiB,CAAC,aAAa,EAAE,aAAa,GAAG,SAAS;IAIjE;;OAEG;IACH,wBAAwB,CACpB,eAAe,EAAE,MAAM,EACvB,UAAU,EAAE,mBAAmB,GAChC,MAAM;CAqBZ"}

View File

@@ -0,0 +1,432 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { CacheManager, AccountEntity, CacheHelpers } from '@azure/msal-common/node';
import { Deserializer } from './serializer/Deserializer.mjs';
import { Serializer } from './serializer/Serializer.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class implements Storage for node, reading cache from user specified storage location or an extension library
* @public
*/
class NodeStorage extends CacheManager {
constructor(logger, clientId, cryptoImpl, staticAuthorityOptions) {
super(clientId, cryptoImpl, logger, staticAuthorityOptions);
this.cache = {};
this.changeEmitters = [];
this.logger = logger;
}
/**
* Queue up callbacks
* @param func - a callback function for cache change indication
*/
registerChangeEmitter(func) {
this.changeEmitters.push(func);
}
/**
* Invoke the callback when cache changes
*/
emitChange() {
this.changeEmitters.forEach((func) => func.call(null));
}
/**
* Converts cacheKVStore to InMemoryCache
* @param cache - key value store
*/
cacheToInMemoryCache(cache) {
const inMemoryCache = {
accounts: {},
idTokens: {},
accessTokens: {},
refreshTokens: {},
appMetadata: {},
};
for (const key in cache) {
const value = cache[key];
if (typeof value !== "object") {
continue;
}
if (value instanceof AccountEntity) {
inMemoryCache.accounts[key] = value;
}
else if (CacheHelpers.isIdTokenEntity(value)) {
inMemoryCache.idTokens[key] = value;
}
else if (CacheHelpers.isAccessTokenEntity(value)) {
inMemoryCache.accessTokens[key] = value;
}
else if (CacheHelpers.isRefreshTokenEntity(value)) {
inMemoryCache.refreshTokens[key] = value;
}
else if (CacheHelpers.isAppMetadataEntity(key, value)) {
inMemoryCache.appMetadata[key] = value;
}
else {
continue;
}
}
return inMemoryCache;
}
/**
* converts inMemoryCache to CacheKVStore
* @param inMemoryCache - kvstore map for inmemory
*/
inMemoryCacheToCache(inMemoryCache) {
// convert in memory cache to a flat Key-Value map
let cache = this.getCache();
cache = {
...cache,
...inMemoryCache.accounts,
...inMemoryCache.idTokens,
...inMemoryCache.accessTokens,
...inMemoryCache.refreshTokens,
...inMemoryCache.appMetadata,
};
// convert in memory cache to a flat Key-Value map
return cache;
}
/**
* gets the current in memory cache for the client
*/
getInMemoryCache() {
this.logger.trace("Getting in-memory cache");
// convert the cache key value store to inMemoryCache
const inMemoryCache = this.cacheToInMemoryCache(this.getCache());
return inMemoryCache;
}
/**
* sets the current in memory cache for the client
* @param inMemoryCache - key value map in memory
*/
setInMemoryCache(inMemoryCache) {
this.logger.trace("Setting in-memory cache");
// convert and append the inMemoryCache to cacheKVStore
const cache = this.inMemoryCacheToCache(inMemoryCache);
this.setCache(cache);
this.emitChange();
}
/**
* get the current cache key-value store
*/
getCache() {
this.logger.trace("Getting cache key-value store");
return this.cache;
}
/**
* sets the current cache (key value store)
* @param cacheMap - key value map
*/
setCache(cache) {
this.logger.trace("Setting cache key value store");
this.cache = cache;
// mark change in cache
this.emitChange();
}
/**
* Gets cache item with given key.
* @param key - lookup key for the cache entry
*/
getItem(key) {
this.logger.tracePii(`Item key: ${key}`);
// read cache
const cache = this.getCache();
return cache[key];
}
/**
* Gets cache item with given key-value
* @param key - lookup key for the cache entry
* @param value - value of the cache entry
*/
setItem(key, value) {
this.logger.tracePii(`Item key: ${key}`);
// read cache
const cache = this.getCache();
cache[key] = value;
// write to cache
this.setCache(cache);
}
getAccountKeys() {
const inMemoryCache = this.getInMemoryCache();
const accountKeys = Object.keys(inMemoryCache.accounts);
return accountKeys;
}
getTokenKeys() {
const inMemoryCache = this.getInMemoryCache();
const tokenKeys = {
idToken: Object.keys(inMemoryCache.idTokens),
accessToken: Object.keys(inMemoryCache.accessTokens),
refreshToken: Object.keys(inMemoryCache.refreshTokens),
};
return tokenKeys;
}
/**
* fetch the account entity
* @param accountKey - lookup key to fetch cache type AccountEntity
*/
getAccount(accountKey) {
const accountEntity = this.getCachedAccountEntity(accountKey);
if (accountEntity && AccountEntity.isAccountEntity(accountEntity)) {
return this.updateOutdatedCachedAccount(accountKey, accountEntity);
}
return null;
}
/**
* Reads account from cache, builds it into an account entity and returns it.
* @param accountKey - lookup key to fetch cache type AccountEntity
* @returns
*/
getCachedAccountEntity(accountKey) {
const cachedAccount = this.getItem(accountKey);
return cachedAccount
? Object.assign(new AccountEntity(), this.getItem(accountKey))
: null;
}
/**
* set account entity
* @param account - cache value to be set of type AccountEntity
*/
setAccount(account) {
const accountKey = account.generateAccountKey();
this.setItem(accountKey, account);
}
/**
* fetch the idToken credential
* @param idTokenKey - lookup key to fetch cache type IdTokenEntity
*/
getIdTokenCredential(idTokenKey) {
const idToken = this.getItem(idTokenKey);
if (CacheHelpers.isIdTokenEntity(idToken)) {
return idToken;
}
return null;
}
/**
* set idToken credential
* @param idToken - cache value to be set of type IdTokenEntity
*/
setIdTokenCredential(idToken) {
const idTokenKey = CacheHelpers.generateCredentialKey(idToken);
this.setItem(idTokenKey, idToken);
}
/**
* fetch the accessToken credential
* @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity
*/
getAccessTokenCredential(accessTokenKey) {
const accessToken = this.getItem(accessTokenKey);
if (CacheHelpers.isAccessTokenEntity(accessToken)) {
return accessToken;
}
return null;
}
/**
* set accessToken credential
* @param accessToken - cache value to be set of type AccessTokenEntity
*/
setAccessTokenCredential(accessToken) {
const accessTokenKey = CacheHelpers.generateCredentialKey(accessToken);
this.setItem(accessTokenKey, accessToken);
}
/**
* fetch the refreshToken credential
* @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity
*/
getRefreshTokenCredential(refreshTokenKey) {
const refreshToken = this.getItem(refreshTokenKey);
if (CacheHelpers.isRefreshTokenEntity(refreshToken)) {
return refreshToken;
}
return null;
}
/**
* set refreshToken credential
* @param refreshToken - cache value to be set of type RefreshTokenEntity
*/
setRefreshTokenCredential(refreshToken) {
const refreshTokenKey = CacheHelpers.generateCredentialKey(refreshToken);
this.setItem(refreshTokenKey, refreshToken);
}
/**
* fetch appMetadata entity from the platform cache
* @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity
*/
getAppMetadata(appMetadataKey) {
const appMetadata = this.getItem(appMetadataKey);
if (CacheHelpers.isAppMetadataEntity(appMetadataKey, appMetadata)) {
return appMetadata;
}
return null;
}
/**
* set appMetadata entity to the platform cache
* @param appMetadata - cache value to be set of type AppMetadataEntity
*/
setAppMetadata(appMetadata) {
const appMetadataKey = CacheHelpers.generateAppMetadataKey(appMetadata);
this.setItem(appMetadataKey, appMetadata);
}
/**
* fetch server telemetry entity from the platform cache
* @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity
*/
getServerTelemetry(serverTelemetrykey) {
const serverTelemetryEntity = this.getItem(serverTelemetrykey);
if (serverTelemetryEntity &&
CacheHelpers.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {
return serverTelemetryEntity;
}
return null;
}
/**
* set server telemetry entity to the platform cache
* @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity
* @param serverTelemetry - cache value to be set of type ServerTelemetryEntity
*/
setServerTelemetry(serverTelemetryKey, serverTelemetry) {
this.setItem(serverTelemetryKey, serverTelemetry);
}
/**
* fetch authority metadata entity from the platform cache
* @param key - lookup key to fetch cache type AuthorityMetadataEntity
*/
getAuthorityMetadata(key) {
const authorityMetadataEntity = this.getItem(key);
if (authorityMetadataEntity &&
CacheHelpers.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {
return authorityMetadataEntity;
}
return null;
}
/**
* Get all authority metadata keys
*/
getAuthorityMetadataKeys() {
return this.getKeys().filter((key) => {
return this.isAuthorityMetadata(key);
});
}
/**
* set authority metadata entity to the platform cache
* @param key - lookup key to fetch cache type AuthorityMetadataEntity
* @param metadata - cache value to be set of type AuthorityMetadataEntity
*/
setAuthorityMetadata(key, metadata) {
this.setItem(key, metadata);
}
/**
* fetch throttling entity from the platform cache
* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
*/
getThrottlingCache(throttlingCacheKey) {
const throttlingCache = this.getItem(throttlingCacheKey);
if (throttlingCache &&
CacheHelpers.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {
return throttlingCache;
}
return null;
}
/**
* set throttling entity to the platform cache
* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
* @param throttlingCache - cache value to be set of type ThrottlingEntity
*/
setThrottlingCache(throttlingCacheKey, throttlingCache) {
this.setItem(throttlingCacheKey, throttlingCache);
}
/**
* Removes the cache item from memory with the given key.
* @param key - lookup key to remove a cache entity
* @param inMemory - key value map of the cache
*/
removeItem(key) {
this.logger.tracePii(`Item key: ${key}`);
// read inMemoryCache
let result = false;
const cache = this.getCache();
if (!!cache[key]) {
delete cache[key];
result = true;
}
// write to the cache after removal
if (result) {
this.setCache(cache);
this.emitChange();
}
return result;
}
/**
* Remove account entity from the platform cache if it's outdated
* @param accountKey - lookup key to fetch cache type AccountEntity
*/
removeOutdatedAccount(accountKey) {
this.removeItem(accountKey);
}
/**
* Checks whether key is in cache.
* @param key - look up key for a cache entity
*/
containsKey(key) {
return this.getKeys().includes(key);
}
/**
* Gets all keys in window.
*/
getKeys() {
this.logger.trace("Retrieving all cache keys");
// read cache
const cache = this.getCache();
return [...Object.keys(cache)];
}
/**
* Clears all cache entries created by MSAL (except tokens).
*/
clear() {
this.logger.trace("Clearing cache entries created by MSAL");
// read inMemoryCache
const cacheKeys = this.getKeys();
// delete each element
cacheKeys.forEach((key) => {
this.removeItem(key);
});
this.emitChange();
}
/**
* Initialize in memory cache from an exisiting cache vault
* @param cache - blob formatted cache (JSON)
*/
static generateInMemoryCache(cache) {
return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache));
}
/**
* retrieves the final JSON
* @param inMemoryCache - itemised cache read from the JSON
*/
static generateJsonCache(inMemoryCache) {
return Serializer.serializeAllCache(inMemoryCache);
}
/**
* Updates a credential's cache key if the current cache key is outdated
*/
updateCredentialCacheKey(currentCacheKey, credential) {
const updatedCacheKey = CacheHelpers.generateCredentialKey(credential);
if (currentCacheKey !== updatedCacheKey) {
const cacheItem = this.getItem(currentCacheKey);
if (cacheItem) {
this.removeItem(currentCacheKey);
this.setItem(updatedCacheKey, cacheItem);
this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`);
return updatedCacheKey;
}
else {
this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);
}
}
return currentCacheKey;
}
}
export { NodeStorage };
//# sourceMappingURL=NodeStorage.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,91 @@
import { NodeStorage } from "./NodeStorage.js";
import { AccountInfo, Logger, ISerializableTokenCache, ICachePlugin } from "@azure/msal-common/node";
import { CacheKVStore } from "./serializer/SerializerTypes.js";
import { ITokenCache } from "./ITokenCache.js";
/**
* In-memory token cache manager
* @public
*/
export declare class TokenCache implements ISerializableTokenCache, ITokenCache {
private storage;
private cacheHasChanged;
private cacheSnapshot;
private readonly persistence;
private logger;
constructor(storage: NodeStorage, logger: Logger, cachePlugin?: ICachePlugin);
/**
* Set to true if cache state has changed since last time serialize or writeToPersistence was called
*/
hasChanged(): boolean;
/**
* Serializes in memory cache to JSON
*/
serialize(): string;
/**
* Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format
* @param cache - blob formatted cache
*/
deserialize(cache: string): void;
/**
* Fetches the cache key-value map
*/
getKVStore(): CacheKVStore;
/**
* API that retrieves all accounts currently in cache to the user
*/
getAllAccounts(): Promise<AccountInfo[]>;
/**
* Returns the signed in account matching homeAccountId.
* (the account object is created at the time of successful login)
* or null when no matching account is found
* @param homeAccountId - unique identifier for an account (uid.utid)
*/
getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>;
/**
* Returns the signed in account matching localAccountId.
* (the account object is created at the time of successful login)
* or null when no matching account is found
* @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)
*/
getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>;
/**
* API to remove a specific account and the relevant data from cache
* @param account - AccountInfo passed by the user
*/
removeAccount(account: AccountInfo): Promise<void>;
/**
* Called when the cache has changed state.
*/
private handleChangeEvent;
/**
* Merge in memory cache with the cache snapshot.
* @param oldState - cache before changes
* @param currentState - current cache state in the library
*/
private mergeState;
/**
* Deep update of oldState based on newState values
* @param oldState - cache before changes
* @param newState - updated cache
*/
private mergeUpdates;
/**
* Removes entities in oldState that the were removed from newState. If there are any unknown values in root of
* oldState that are not recognized, they are left untouched.
* @param oldState - cache before changes
* @param newState - updated cache
*/
private mergeRemovals;
/**
* Helper to merge new cache with the old one
* @param oldState - cache before changes
* @param newState - updated cache
*/
private mergeRemovalsDict;
/**
* Helper to overlay as a part of cache merge
* @param passedInCache - cache read from the blob
*/
private overlayDefaults;
}
//# sourceMappingURL=TokenCache.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"TokenCache.d.ts","sourceRoot":"","sources":["../../src/cache/TokenCache.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAEH,WAAW,EACX,MAAM,EACN,uBAAuB,EACvB,YAAY,EAEf,MAAM,yBAAyB,CAAC;AACjC,OAA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@@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { TokenCacheContext, AccountEntity } from '@azure/msal-common/node';
import { Deserializer } from './serializer/Deserializer.mjs';
import { Serializer } from './serializer/Serializer.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const defaultSerializedCache = {
Account: {},
IdToken: {},
AccessToken: {},
RefreshToken: {},
AppMetadata: {},
};
/**
* In-memory token cache manager
* @public
*/
class TokenCache {
constructor(storage, logger, cachePlugin) {
this.cacheHasChanged = false;
this.storage = storage;
this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));
if (cachePlugin) {
this.persistence = cachePlugin;
}
this.logger = logger;
}
/**
* Set to true if cache state has changed since last time serialize or writeToPersistence was called
*/
hasChanged() {
return this.cacheHasChanged;
}
/**
* Serializes in memory cache to JSON
*/
serialize() {
this.logger.trace("Serializing in-memory cache");
let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());
// if cacheSnapshot not null or empty, merge
if (this.cacheSnapshot) {
this.logger.trace("Reading cache snapshot from disk");
finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);
}
else {
this.logger.trace("No cache snapshot to merge");
}
this.cacheHasChanged = false;
return JSON.stringify(finalState);
}
/**
* Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format
* @param cache - blob formatted cache
*/
deserialize(cache) {
this.logger.trace("Deserializing JSON to in-memory cache");
this.cacheSnapshot = cache;
if (this.cacheSnapshot) {
this.logger.trace("Reading cache snapshot from disk");
const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));
this.storage.setInMemoryCache(deserializedCache);
}
else {
this.logger.trace("No cache snapshot to deserialize");
}
}
/**
* Fetches the cache key-value map
*/
getKVStore() {
return this.storage.getCache();
}
/**
* API that retrieves all accounts currently in cache to the user
*/
async getAllAccounts() {
this.logger.trace("getAllAccounts called");
let cacheContext;
try {
if (this.persistence) {
cacheContext = new TokenCacheContext(this, false);
await this.persistence.beforeCacheAccess(cacheContext);
}
return this.storage.getAllAccounts();
}
finally {
if (this.persistence && cacheContext) {
await this.persistence.afterCacheAccess(cacheContext);
}
}
}
/**
* Returns the signed in account matching homeAccountId.
* (the account object is created at the time of successful login)
* or null when no matching account is found
* @param homeAccountId - unique identifier for an account (uid.utid)
*/
async getAccountByHomeId(homeAccountId) {
const allAccounts = await this.getAllAccounts();
if (homeAccountId && allAccounts && allAccounts.length) {
return (allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null);
}
else {
return null;
}
}
/**
* Returns the signed in account matching localAccountId.
* (the account object is created at the time of successful login)
* or null when no matching account is found
* @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)
*/
async getAccountByLocalId(localAccountId) {
const allAccounts = await this.getAllAccounts();
if (localAccountId && allAccounts && allAccounts.length) {
return (allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null);
}
else {
return null;
}
}
/**
* API to remove a specific account and the relevant data from cache
* @param account - AccountInfo passed by the user
*/
async removeAccount(account) {
this.logger.trace("removeAccount called");
let cacheContext;
try {
if (this.persistence) {
cacheContext = new TokenCacheContext(this, true);
await this.persistence.beforeCacheAccess(cacheContext);
}
await this.storage.removeAccount(AccountEntity.generateAccountCacheKey(account));
}
finally {
if (this.persistence && cacheContext) {
await this.persistence.afterCacheAccess(cacheContext);
}
}
}
/**
* Called when the cache has changed state.
*/
handleChangeEvent() {
this.cacheHasChanged = true;
}
/**
* Merge in memory cache with the cache snapshot.
* @param oldState - cache before changes
* @param currentState - current cache state in the library
*/
mergeState(oldState, currentState) {
this.logger.trace("Merging in-memory cache with cache snapshot");
const stateAfterRemoval = this.mergeRemovals(oldState, currentState);
return this.mergeUpdates(stateAfterRemoval, currentState);
}
/**
* Deep update of oldState based on newState values
* @param oldState - cache before changes
* @param newState - updated cache
*/
mergeUpdates(oldState, newState) {
Object.keys(newState).forEach((newKey) => {
const newValue = newState[newKey];
// if oldState does not contain value but newValue does, add it
if (!oldState.hasOwnProperty(newKey)) {
if (newValue !== null) {
oldState[newKey] = newValue;
}
}
else {
// both oldState and newState contain the key, do deep update
const newValueNotNull = newValue !== null;
const newValueIsObject = typeof newValue === "object";
const newValueIsNotArray = !Array.isArray(newValue);
const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" &&
oldState[newKey] !== null;
if (newValueNotNull &&
newValueIsObject &&
newValueIsNotArray &&
oldStateNotUndefinedOrNull) {
this.mergeUpdates(oldState[newKey], newValue);
}
else {
oldState[newKey] = newValue;
}
}
});
return oldState;
}
/**
* Removes entities in oldState that the were removed from newState. If there are any unknown values in root of
* oldState that are not recognized, they are left untouched.
* @param oldState - cache before changes
* @param newState - updated cache
*/
mergeRemovals(oldState, newState) {
this.logger.trace("Remove updated entries in cache");
const accounts = oldState.Account
? this.mergeRemovalsDict(oldState.Account, newState.Account)
: oldState.Account;
const accessTokens = oldState.AccessToken
? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken)
: oldState.AccessToken;
const refreshTokens = oldState.RefreshToken
? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken)
: oldState.RefreshToken;
const idTokens = oldState.IdToken
? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken)
: oldState.IdToken;
const appMetadata = oldState.AppMetadata
? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata)
: oldState.AppMetadata;
return {
...oldState,
Account: accounts,
AccessToken: accessTokens,
RefreshToken: refreshTokens,
IdToken: idTokens,
AppMetadata: appMetadata,
};
}
/**
* Helper to merge new cache with the old one
* @param oldState - cache before changes
* @param newState - updated cache
*/
mergeRemovalsDict(oldState, newState) {
const finalState = { ...oldState };
Object.keys(oldState).forEach((oldKey) => {
if (!newState || !newState.hasOwnProperty(oldKey)) {
delete finalState[oldKey];
}
});
return finalState;
}
/**
* Helper to overlay as a part of cache merge
* @param passedInCache - cache read from the blob
*/
overlayDefaults(passedInCache) {
this.logger.trace("Overlaying input cache with the default cache");
return {
Account: {
...defaultSerializedCache.Account,
...passedInCache.Account,
},
IdToken: {
...defaultSerializedCache.IdToken,
...passedInCache.IdToken,
},
AccessToken: {
...defaultSerializedCache.AccessToken,
...passedInCache.AccessToken,
},
RefreshToken: {
...defaultSerializedCache.RefreshToken,
...passedInCache.RefreshToken,
},
AppMetadata: {
...defaultSerializedCache.AppMetadata,
...passedInCache.AppMetadata,
},
};
}
}
export { TokenCache };
//# sourceMappingURL=TokenCache.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
import { ICachePlugin, TokenCacheContext } from "@azure/msal-common/node";
import { IPartitionManager } from "./IPartitionManager.js";
import { ICacheClient } from "./ICacheClient.js";
/**
* Cache plugin that serializes data to the cache and deserializes data from the cache
* @public
*/
export declare class DistributedCachePlugin implements ICachePlugin {
private client;
private partitionManager;
constructor(client: ICacheClient, partitionManager: IPartitionManager);
/**
* Deserializes the cache before accessing it
* @param cacheContext - TokenCacheContext
*/
beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void>;
/**
* Serializes the cache after accessing it
* @param cacheContext - TokenCacheContext
*/
afterCacheAccess(cacheContext: TokenCacheContext): Promise<void>;
}
//# sourceMappingURL=DistributedCachePlugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"DistributedCachePlugin.d.ts","sourceRoot":"","sources":["../../../src/cache/distributed/DistributedCachePlugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,YAAY,EACZ,iBAAiB,EACpB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;GAGG;AACH,qBAAa,sBAAuB,YAAW,YAAY;IACvD,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,gBAAgB,CAAoB;gBAEhC,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB;IAKrE;;;OAGG;IACU,iBAAiB,CAC1B,YAAY,EAAE,iBAAiB,GAChC,OAAO,CAAC,IAAI,CAAC;IAMhB;;;OAGG;IACU,gBAAgB,CACzB,YAAY,EAAE,iBAAiB,GAChC,OAAO,CAAC,IAAI,CAAC;CAyBnB"}

View File

@@ -0,0 +1,49 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { AccountEntity } from '@azure/msal-common/node';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Cache plugin that serializes data to the cache and deserializes data from the cache
* @public
*/
class DistributedCachePlugin {
constructor(client, partitionManager) {
this.client = client;
this.partitionManager = partitionManager;
}
/**
* Deserializes the cache before accessing it
* @param cacheContext - TokenCacheContext
*/
async beforeCacheAccess(cacheContext) {
const partitionKey = await this.partitionManager.getKey();
const cacheData = await this.client.get(partitionKey);
cacheContext.tokenCache.deserialize(cacheData);
}
/**
* Serializes the cache after accessing it
* @param cacheContext - TokenCacheContext
*/
async afterCacheAccess(cacheContext) {
if (cacheContext.cacheHasChanged) {
const kvStore = cacheContext.tokenCache.getKVStore();
const accountEntities = Object.values(kvStore).filter((value) => AccountEntity.isAccountEntity(value));
let partitionKey;
if (accountEntities.length > 0) {
const accountEntity = accountEntities[0];
partitionKey = await this.partitionManager.extractKey(accountEntity);
}
else {
partitionKey = await this.partitionManager.getKey();
}
await this.client.set(partitionKey, cacheContext.tokenCache.serialize());
}
}
}
export { DistributedCachePlugin };
//# sourceMappingURL=DistributedCachePlugin.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"DistributedCachePlugin.mjs","sources":["../../../src/cache/distributed/DistributedCachePlugin.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAAA;;;AAGG;AAWH;;;AAGG;MACU,sBAAsB,CAAA;IAI/B,WAAY,CAAA,MAAoB,EAAE,gBAAmC,EAAA;AACjE,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AACrB,QAAA,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;KAC5C;AAED;;;AAGG;IACI,MAAM,iBAAiB,CAC1B,YAA+B,EAAA;QAE/B,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,CAAC;QAC1D,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;AACtD,QAAA,YAAY,CAAC,UAAU,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;KAClD;AAED;;;AAGG;IACI,MAAM,gBAAgB,CACzB,YAA+B,EAAA;QAE/B,IAAI,YAAY,CAAC,eAAe,EAAE;YAC9B,MAAM,OAAO,GACT,YAAY,CAAC,UAChB,CAAC,UAAU,EAAE,CAAC;YACf,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,KACxD,aAAa,CAAC,eAAe,CAAC,KAAe,CAAC,CACjD,CAAC;AAEF,YAAA,IAAI,YAAoB,CAAC;AACzB,YAAA,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE;AAC5B,gBAAA,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,CAAkB,CAAC;gBAC1D,YAAY,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,UAAU,CACjD,aAAa,CAChB,CAAC;AACL,aAAA;AAAM,iBAAA;gBACH,YAAY,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,CAAC;AACvD,aAAA;AAED,YAAA,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CACjB,YAAY,EACZ,YAAY,CAAC,UAAU,CAAC,SAAS,EAAE,CACtC,CAAC;AACL,SAAA;KACJ;AACJ;;;;"}

View File

@@ -0,0 +1,22 @@
/**
* Interface for the cache that defines a getter and setter
* @public
*/
export interface ICacheClient {
/**
* Retrieve the value from the cache
*
* @param key - key of item in the cache
* @returns Promise<string>
*/
get(key: string): Promise<string>;
/**
* Save the required value using the provided key to cache
*
* @param key - key of item in the cache
* @param value - value of item to be saved in the cache
* @returns Promise<string>
*/
set(key: string, value: string): Promise<string>;
}
//# sourceMappingURL=ICacheClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ICacheClient.d.ts","sourceRoot":"","sources":["../../../src/cache/distributed/ICacheClient.ts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,MAAM,WAAW,YAAY;IACzB;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAElC;;;;;;OAMG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACpD"}

View File

@@ -0,0 +1,33 @@
import { AccountEntity } from "@azure/msal-common/node";
/**
* Interface that defines getter methods to get keys used to identity data in the cache
* @public
*/
export interface IPartitionManager {
/**
* This function should return the correct key from which to read
* the specific user's information from cache.
*
* Example: Your application may be partitioning the user's cache
* information for each user using the homeAccountId and thus
* this function would return the homeAccountId for
* the user in question
*
* @returns Promise<string>
*/
getKey(): Promise<string>;
/**
* This function should return the correct key being used to save each
* user's cache information to cache - given an AccountEntity
*
* Example: Your application may be partitioning the user's cache
* information for each user using the homeAccountId thus
* this function would return the homeAccountId from
* the provided AccountEntity
*
* @param accountEntity - AccountEntity
* @returns Promise<string>
*/
extractKey(accountEntity: AccountEntity): Promise<string>;
}
//# sourceMappingURL=IPartitionManager.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IPartitionManager.d.ts","sourceRoot":"","sources":["../../../src/cache/distributed/IPartitionManager.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAC9B;;;;;;;;;;OAUG;IACH,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAE1B;;;;;;;;;;;OAWG;IACH,UAAU,CAAC,aAAa,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC7D"}

View File

@@ -0,0 +1,44 @@
import { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache } from "@azure/msal-common/node";
import { JsonCache, InMemoryCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from "./SerializerTypes.js";
/**
* This class deserializes cache entities read from the file into in-memory object types defined internally
* @internal
*/
export declare class Deserializer {
/**
* Parse the JSON blob in memory and deserialize the content
* @param cachedJson - JSON blob cache
*/
static deserializeJSONBlob(jsonFile: string): JsonCache;
/**
* Deserializes accounts to AccountEntity objects
* @param accounts - accounts of type SerializedAccountEntity
*/
static deserializeAccounts(accounts: Record<string, SerializedAccountEntity>): AccountCache;
/**
* Deserializes id tokens to IdTokenEntity objects
* @param idTokens - credentials of type SerializedIdTokenEntity
*/
static deserializeIdTokens(idTokens: Record<string, SerializedIdTokenEntity>): IdTokenCache;
/**
* Deserializes access tokens to AccessTokenEntity objects
* @param accessTokens - access tokens of type SerializedAccessTokenEntity
*/
static deserializeAccessTokens(accessTokens: Record<string, SerializedAccessTokenEntity>): AccessTokenCache;
/**
* Deserializes refresh tokens to RefreshTokenEntity objects
* @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity
*/
static deserializeRefreshTokens(refreshTokens: Record<string, SerializedRefreshTokenEntity>): RefreshTokenCache;
/**
* Deserializes appMetadata to AppMetaData objects
* @param appMetadata - app metadata of type SerializedAppMetadataEntity
*/
static deserializeAppMetadata(appMetadata: Record<string, SerializedAppMetadataEntity>): AppMetadataCache;
/**
* Deserialize an inMemory Cache
* @param jsonCache - JSON blob cache
*/
static deserializeAllCache(jsonCache: JsonCache): InMemoryCache;
}
//# sourceMappingURL=Deserializer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Deserializer.d.ts","sourceRoot":"","sources":["../../../src/cache/serializer/Deserializer.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAQnB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,SAAS,EACT,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC9B,MAAM,sBAAsB,CAAC;AAE9B;;;GAGG;AACH,qBAAa,YAAY;IACrB;;;OAGG;IACH,MAAM,CAAC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS;IAKvD;;;OAGG;IACH,MAAM,CAAC,mBAAmB,CACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC,GAClD,YAAY;IA+Bf;;;OAGG;IACH,MAAM,CAAC,mBAAmB,CACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC,GAClD,YAAY;IAoBf;;;OAGG;IACH,MAAM,CAAC,uBAAuB,CAC1B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,GAC1D,gBAAgB;IA+BnB;;;OAGG;IACH,MAAM,CAAC,wBAAwB,CAC3B,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,4BAA4B,CAAC,GAC5D,iBAAiB;IAuBpB;;;OAGG;IACH,MAAM,CAAC,sBAAsB,CACzB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,GACzD,gBAAgB;IAgBnB;;;OAGG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,SAAS,GAAG,aAAa;CAmBlE"}

View File

@@ -0,0 +1,175 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { AccountEntity, CacheManager } from '@azure/msal-common/node';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class deserializes cache entities read from the file into in-memory object types defined internally
* @internal
*/
class Deserializer {
/**
* Parse the JSON blob in memory and deserialize the content
* @param cachedJson - JSON blob cache
*/
static deserializeJSONBlob(jsonFile) {
const deserializedCache = !jsonFile ? {} : JSON.parse(jsonFile);
return deserializedCache;
}
/**
* Deserializes accounts to AccountEntity objects
* @param accounts - accounts of type SerializedAccountEntity
*/
static deserializeAccounts(accounts) {
const accountObjects = {};
if (accounts) {
Object.keys(accounts).map(function (key) {
const serializedAcc = accounts[key];
const mappedAcc = {
homeAccountId: serializedAcc.home_account_id,
environment: serializedAcc.environment,
realm: serializedAcc.realm,
localAccountId: serializedAcc.local_account_id,
username: serializedAcc.username,
authorityType: serializedAcc.authority_type,
name: serializedAcc.name,
clientInfo: serializedAcc.client_info,
lastModificationTime: serializedAcc.last_modification_time,
lastModificationApp: serializedAcc.last_modification_app,
tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => {
return JSON.parse(serializedTenantProfile);
}),
};
const account = new AccountEntity();
CacheManager.toObject(account, mappedAcc);
accountObjects[key] = account;
});
}
return accountObjects;
}
/**
* Deserializes id tokens to IdTokenEntity objects
* @param idTokens - credentials of type SerializedIdTokenEntity
*/
static deserializeIdTokens(idTokens) {
const idObjects = {};
if (idTokens) {
Object.keys(idTokens).map(function (key) {
const serializedIdT = idTokens[key];
const idToken = {
homeAccountId: serializedIdT.home_account_id,
environment: serializedIdT.environment,
credentialType: serializedIdT.credential_type,
clientId: serializedIdT.client_id,
secret: serializedIdT.secret,
realm: serializedIdT.realm,
};
idObjects[key] = idToken;
});
}
return idObjects;
}
/**
* Deserializes access tokens to AccessTokenEntity objects
* @param accessTokens - access tokens of type SerializedAccessTokenEntity
*/
static deserializeAccessTokens(accessTokens) {
const atObjects = {};
if (accessTokens) {
Object.keys(accessTokens).map(function (key) {
const serializedAT = accessTokens[key];
const accessToken = {
homeAccountId: serializedAT.home_account_id,
environment: serializedAT.environment,
credentialType: serializedAT.credential_type,
clientId: serializedAT.client_id,
secret: serializedAT.secret,
realm: serializedAT.realm,
target: serializedAT.target,
cachedAt: serializedAT.cached_at,
expiresOn: serializedAT.expires_on,
extendedExpiresOn: serializedAT.extended_expires_on,
refreshOn: serializedAT.refresh_on,
keyId: serializedAT.key_id,
tokenType: serializedAT.token_type,
requestedClaims: serializedAT.requestedClaims,
requestedClaimsHash: serializedAT.requestedClaimsHash,
userAssertionHash: serializedAT.userAssertionHash,
};
atObjects[key] = accessToken;
});
}
return atObjects;
}
/**
* Deserializes refresh tokens to RefreshTokenEntity objects
* @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity
*/
static deserializeRefreshTokens(refreshTokens) {
const rtObjects = {};
if (refreshTokens) {
Object.keys(refreshTokens).map(function (key) {
const serializedRT = refreshTokens[key];
const refreshToken = {
homeAccountId: serializedRT.home_account_id,
environment: serializedRT.environment,
credentialType: serializedRT.credential_type,
clientId: serializedRT.client_id,
secret: serializedRT.secret,
familyId: serializedRT.family_id,
target: serializedRT.target,
realm: serializedRT.realm,
};
rtObjects[key] = refreshToken;
});
}
return rtObjects;
}
/**
* Deserializes appMetadata to AppMetaData objects
* @param appMetadata - app metadata of type SerializedAppMetadataEntity
*/
static deserializeAppMetadata(appMetadata) {
const appMetadataObjects = {};
if (appMetadata) {
Object.keys(appMetadata).map(function (key) {
const serializedAmdt = appMetadata[key];
appMetadataObjects[key] = {
clientId: serializedAmdt.client_id,
environment: serializedAmdt.environment,
familyId: serializedAmdt.family_id,
};
});
}
return appMetadataObjects;
}
/**
* Deserialize an inMemory Cache
* @param jsonCache - JSON blob cache
*/
static deserializeAllCache(jsonCache) {
return {
accounts: jsonCache.Account
? this.deserializeAccounts(jsonCache.Account)
: {},
idTokens: jsonCache.IdToken
? this.deserializeIdTokens(jsonCache.IdToken)
: {},
accessTokens: jsonCache.AccessToken
? this.deserializeAccessTokens(jsonCache.AccessToken)
: {},
refreshTokens: jsonCache.RefreshToken
? this.deserializeRefreshTokens(jsonCache.RefreshToken)
: {},
appMetadata: jsonCache.AppMetadata
? this.deserializeAppMetadata(jsonCache.AppMetadata)
: {},
};
}
}
export { Deserializer };
//# sourceMappingURL=Deserializer.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Deserializer.mjs","sources":["../../../src/cache/serializer/Deserializer.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAAA;;;AAGG;AA0BH;;;AAGG;MACU,YAAY,CAAA;AACrB;;;AAGG;IACH,OAAO,mBAAmB,CAAC,QAAgB,EAAA;AACvC,QAAA,MAAM,iBAAiB,GAAG,CAAC,QAAQ,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;AAChE,QAAA,OAAO,iBAAiB,CAAC;KAC5B;AAED;;;AAGG;IACH,OAAO,mBAAmB,CACtB,QAAiD,EAAA;QAEjD,MAAM,cAAc,GAAiB,EAAE,CAAC;AACxC,QAAA,IAAI,QAAQ,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,UAAU,GAAG,EAAA;AACnC,gBAAA,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AACpC,gBAAA,MAAM,SAAS,GAAG;oBACd,aAAa,EAAE,aAAa,CAAC,eAAe;oBAC5C,WAAW,EAAE,aAAa,CAAC,WAAW;oBACtC,KAAK,EAAE,aAAa,CAAC,KAAK;oBAC1B,cAAc,EAAE,aAAa,CAAC,gBAAgB;oBAC9C,QAAQ,EAAE,aAAa,CAAC,QAAQ;oBAChC,aAAa,EAAE,aAAa,CAAC,cAAc;oBAC3C,IAAI,EAAE,aAAa,CAAC,IAAI;oBACxB,UAAU,EAAE,aAAa,CAAC,WAAW;oBACrC,oBAAoB,EAAE,aAAa,CAAC,sBAAsB;oBAC1D,mBAAmB,EAAE,aAAa,CAAC,qBAAqB;oBACxD,cAAc,EAAE,aAAa,CAAC,cAAc,EAAE,GAAG,CAC7C,CAAC,uBAAuB,KAAI;AACxB,wBAAA,OAAO,IAAI,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AAS,CAAC,YAAY;kBAC/B,IAAI,CAAC,wBAAwB,CAAC,SAAS,CAAC,YAAY,CAAC;AACvD,kBAAE,EAAE;YACR,WAAW,EAAE,SAAS,CAAC,WAAW;kBAC5B,IAAI,CAAC,sBAAsB,CAAC,SAAS,CAAC,WAAW,CAAC;AACpD,kBAAE,EAAE;SACX,CAAC;KACL;AACJ;;;;"}

View File

@@ -0,0 +1,44 @@
import { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache } from "@azure/msal-common/node";
import { InMemoryCache, JsonCache, SerializedAccountEntity, SerializedIdTokenEntity, SerializedAccessTokenEntity, SerializedRefreshTokenEntity, SerializedAppMetadataEntity } from "./SerializerTypes.js";
/**
* This class serializes cache entities to be saved into in-memory object types defined internally
* @internal
*/
export declare class Serializer {
/**
* serialize the JSON blob
* @param data - JSON blob cache
*/
static serializeJSONBlob(data: JsonCache): string;
/**
* Serialize Accounts
* @param accCache - cache of accounts
*/
static serializeAccounts(accCache: AccountCache): Record<string, SerializedAccountEntity>;
/**
* Serialize IdTokens
* @param idTCache - cache of ID tokens
*/
static serializeIdTokens(idTCache: IdTokenCache): Record<string, SerializedIdTokenEntity>;
/**
* Serializes AccessTokens
* @param atCache - cache of access tokens
*/
static serializeAccessTokens(atCache: AccessTokenCache): Record<string, SerializedAccessTokenEntity>;
/**
* Serialize refreshTokens
* @param rtCache - cache of refresh tokens
*/
static serializeRefreshTokens(rtCache: RefreshTokenCache): Record<string, SerializedRefreshTokenEntity>;
/**
* Serialize amdtCache
* @param amdtCache - cache of app metadata
*/
static serializeAppMetadata(amdtCache: AppMetadataCache): Record<string, SerializedAppMetadataEntity>;
/**
* Serialize the cache
* @param inMemCache - itemised cache read from the JSON
*/
static serializeAllCache(inMemCache: InMemoryCache): JsonCache;
}
//# sourceMappingURL=Serializer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Serializer.d.ts","sourceRoot":"","sources":["../../../src/cache/serializer/Serializer.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EACnB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,aAAa,EACb,SAAS,EACT,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,4BAA4B,EAC5B,2BAA2B,EAC9B,MAAM,sBAAsB,CAAC;AAE9B;;;GAGG;AACH,qBAAa,UAAU;IACnB;;;OAGG;IACH,MAAM,CAAC,iBAAiB,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM;IAIjD;;;OAGG;IACH,MAAM,CAAC,iBAAiB,CACpB,QAAQ,EAAE,YAAY,GACvB,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC;IA0B1C;;;OAGG;IACH,MAAM,CAAC,iBAAiB,CACpB,QAAQ,EAAE,YAAY,GACvB,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAAC;IAiB1C;;;OAGG;IACH,MAAM,CAAC,qBAAqB,CACxB,OAAO,EAAE,gBAAgB,GAC1B,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC;IA2B9C;;;OAGG;IACH,MAAM,CAAC,sBAAsB,CACzB,OAAO,EAAE,iBAAiB,GAC3B,MAAM,CAAC,MAAM,EAAE,4BAA4B,CAAC;IAmB/C;;;OAGG;IACH,MAAM,CAAC,oBAAoB,CACvB,SAAS,EAAE,gBAAgB,GAC5B,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC;IAc9C;;;OAGG;IACH,MAAM,CAAC,iBAAiB,CAAC,UAAU,EAAE,aAAa,GAAG,SAAS;CASjE"}

View File

@@ -0,0 +1,146 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class serializes cache entities to be saved into in-memory object types defined internally
* @internal
*/
class Serializer {
/**
* serialize the JSON blob
* @param data - JSON blob cache
*/
static serializeJSONBlob(data) {
return JSON.stringify(data);
}
/**
* Serialize Accounts
* @param accCache - cache of accounts
*/
static serializeAccounts(accCache) {
const accounts = {};
Object.keys(accCache).map(function (key) {
const accountEntity = accCache[key];
accounts[key] = {
home_account_id: accountEntity.homeAccountId,
environment: accountEntity.environment,
realm: accountEntity.realm,
local_account_id: accountEntity.localAccountId,
username: accountEntity.username,
authority_type: accountEntity.authorityType,
name: accountEntity.name,
client_info: accountEntity.clientInfo,
last_modification_time: accountEntity.lastModificationTime,
last_modification_app: accountEntity.lastModificationApp,
tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => {
return JSON.stringify(tenantProfile);
}),
};
});
return accounts;
}
/**
* Serialize IdTokens
* @param idTCache - cache of ID tokens
*/
static serializeIdTokens(idTCache) {
const idTokens = {};
Object.keys(idTCache).map(function (key) {
const idTEntity = idTCache[key];
idTokens[key] = {
home_account_id: idTEntity.homeAccountId,
environment: idTEntity.environment,
credential_type: idTEntity.credentialType,
client_id: idTEntity.clientId,
secret: idTEntity.secret,
realm: idTEntity.realm,
};
});
return idTokens;
}
/**
* Serializes AccessTokens
* @param atCache - cache of access tokens
*/
static serializeAccessTokens(atCache) {
const accessTokens = {};
Object.keys(atCache).map(function (key) {
const atEntity = atCache[key];
accessTokens[key] = {
home_account_id: atEntity.homeAccountId,
environment: atEntity.environment,
credential_type: atEntity.credentialType,
client_id: atEntity.clientId,
secret: atEntity.secret,
realm: atEntity.realm,
target: atEntity.target,
cached_at: atEntity.cachedAt,
expires_on: atEntity.expiresOn,
extended_expires_on: atEntity.extendedExpiresOn,
refresh_on: atEntity.refreshOn,
key_id: atEntity.keyId,
token_type: atEntity.tokenType,
requestedClaims: atEntity.requestedClaims,
requestedClaimsHash: atEntity.requestedClaimsHash,
userAssertionHash: atEntity.userAssertionHash,
};
});
return accessTokens;
}
/**
* Serialize refreshTokens
* @param rtCache - cache of refresh tokens
*/
static serializeRefreshTokens(rtCache) {
const refreshTokens = {};
Object.keys(rtCache).map(function (key) {
const rtEntity = rtCache[key];
refreshTokens[key] = {
home_account_id: rtEntity.homeAccountId,
environment: rtEntity.environment,
credential_type: rtEntity.credentialType,
client_id: rtEntity.clientId,
secret: rtEntity.secret,
family_id: rtEntity.familyId,
target: rtEntity.target,
realm: rtEntity.realm,
};
});
return refreshTokens;
}
/**
* Serialize amdtCache
* @param amdtCache - cache of app metadata
*/
static serializeAppMetadata(amdtCache) {
const appMetadata = {};
Object.keys(amdtCache).map(function (key) {
const amdtEntity = amdtCache[key];
appMetadata[key] = {
client_id: amdtEntity.clientId,
environment: amdtEntity.environment,
family_id: amdtEntity.familyId,
};
});
return appMetadata;
}
/**
* Serialize the cache
* @param inMemCache - itemised cache read from the JSON
*/
static serializeAllCache(inMemCache) {
return {
Account: this.serializeAccounts(inMemCache.accounts),
IdToken: this.serializeIdTokens(inMemCache.idTokens),
AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),
RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),
AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata),
};
}
}
export { Serializer };
//# sourceMappingURL=Serializer.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Serializer.mjs","sources":["../../../src/cache/serializer/Serializer.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAAA;;;AAGG;AAmBH;;;AAGG;MACU,UAAU,CAAA;AACnB;;;AAGG;IACH,OAAO,iBAAiB,CAAC,IAAe,EAAA;AACpC,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC/B;AAED;;;AAGG;IACH,OAAO,iBAAiB,CACpB,QAAsB,EAAA;QAEtB,MAAM,QAAQ,GAA4C,EAAE,CAAC;QAC7D,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,UAAU,GAAG,EAAA;AACnC,YAAA,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;YACpC,QAAQ,CAAC,GAAG,CAAC,GAAG;gBACZ,eAAe,EA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@ -0,0 +1,103 @@
import { AccountCache, IdTokenCache, AccessTokenCache, RefreshTokenCache, AppMetadataCache, ValidCacheType } from "@azure/msal-common/node";
/**
* Key value store for in-memory cache
* @public
*/
export type CacheKVStore = Record<string, ValidCacheType>;
/**
* Cache format read from the cache blob provided to the configuration during app instantiation
* @public
*/
export type JsonCache = {
Account: Record<string, SerializedAccountEntity>;
IdToken: Record<string, SerializedIdTokenEntity>;
AccessToken: Record<string, SerializedAccessTokenEntity>;
RefreshToken: Record<string, SerializedRefreshTokenEntity>;
AppMetadata: Record<string, SerializedAppMetadataEntity>;
};
/**
* Intermittent type to handle in-memory data objects with defined types
* @public
*/
export type InMemoryCache = {
accounts: AccountCache;
idTokens: IdTokenCache;
accessTokens: AccessTokenCache;
refreshTokens: RefreshTokenCache;
appMetadata: AppMetadataCache;
};
/**
* Account type
* @public
*/
export type SerializedAccountEntity = {
home_account_id: string;
environment: string;
realm: string;
local_account_id: string;
username: string;
authority_type: string;
name?: string;
client_info?: string;
last_modification_time?: string;
last_modification_app?: string;
tenantProfiles?: string[];
};
/**
* Idtoken credential type
* @public
*/
export type SerializedIdTokenEntity = {
home_account_id: string;
environment: string;
credential_type: string;
client_id: string;
secret: string;
realm: string;
};
/**
* Access token credential type
* @public
*/
export type SerializedAccessTokenEntity = {
home_account_id: string;
environment: string;
credential_type: string;
client_id: string;
secret: string;
realm: string;
target: string;
cached_at: string;
expires_on: string;
extended_expires_on?: string;
refresh_on?: string;
key_id?: string;
token_type?: string;
requestedClaims?: string;
requestedClaimsHash?: string;
userAssertionHash?: string;
};
/**
* Refresh token credential type
* @public
*/
export type SerializedRefreshTokenEntity = {
home_account_id: string;
environment: string;
credential_type: string;
client_id: string;
secret: string;
family_id?: string;
target?: string;
realm?: string;
};
/**
* AppMetadata type
* @public
*/
export type SerializedAppMetadataEntity = {
client_id: string;
environment: string;
family_id?: string;
};
//# sourceMappingURL=SerializerTypes.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Serializer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,2BAA2B,GAAG;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC"}

View File

@@ -0,0 +1,144 @@
import { ClientConfiguration, AuthenticationResult, BaseAuthRequest, Logger, ServerTelemetryManager, AzureRegionConfiguration, AzureCloudOptions, AuthorizationCodePayload, ClientAssertionCallback } from "@azure/msal-common/node";
import { Configuration, NodeConfiguration } from "../config/Configuration.js";
import { CryptoProvider } from "../crypto/CryptoProvider.js";
import { NodeStorage } from "../cache/NodeStorage.js";
import { TokenCache } from "../cache/TokenCache.js";
import { ClientAssertion } from "./ClientAssertion.js";
import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
import { RefreshTokenRequest } from "../request/RefreshTokenRequest.js";
import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
import { UsernamePasswordRequest } from "../request/UsernamePasswordRequest.js";
/**
* Base abstract class for all ClientApplications - public and confidential
* @public
*/
export declare abstract class ClientApplication {
protected readonly cryptoProvider: CryptoProvider;
private tokenCache;
/**
* Platform storage object
*/
protected storage: NodeStorage;
/**
* Logger object to log the application flow
*/
protected logger: Logger;
/**
* Platform configuration initialized by the application
*/
protected config: NodeConfiguration;
/**
* Client assertion passed by the user for confidential client flows
*/
protected clientAssertion: ClientAssertion;
protected developerProvidedClientAssertion: string | ClientAssertionCallback;
/**
* Client secret passed by the user for confidential client flows
*/
protected clientSecret: string;
/**
* Constructor for the ClientApplication
*/
protected constructor(configuration: Configuration);
/**
* Creates the URL of the authorization request, letting the user input credentials and consent to the
* application. The URL targets the /authorize endpoint of the authority configured in the
* application object.
*
* Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
* sent in the request and should contain an authorization code, which can then be used to acquire tokens via
* `acquireTokenByCode(AuthorizationCodeRequest)`.
*/
getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
/**
* Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
* Authorization Code flow.
*
* `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
* Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
* AuthorizationCodeRequest are the same.
*/
acquireTokenByCode(request: AuthorizationCodeRequest, authCodePayLoad?: AuthorizationCodePayload): Promise<AuthenticationResult>;
/**
* Acquires a token by exchanging the refresh token provided for a new set of tokens.
*
* This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
* recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
* handle the caching and refreshing of tokens automatically.
*/
acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null>;
/**
* Acquires a token silently when a user specifies the account the token is requested for.
*
* This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
* There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
* In case the refresh_token is expired or not found, an error is thrown
* and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
*/
acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>;
/**
* Acquires tokens with password grant by exchanging client applications username and password for credentials
*
* The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
* More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
* Microsoft's documentation and recommendations are at:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
*
* @param request - UsenamePasswordRequest
*/
acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null>;
/**
* Gets the token cache for the application.
*/
getTokenCache(): TokenCache;
/**
* Validates OIDC state by comparing the user cached state with the state received from the server.
*
* This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
* CSRF attacks.
* For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
* @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow
* @param cachedState - This string is sent back by the server with the authorization code
*/
protected validateState(state: string, cachedState: string): void;
/**
* Returns the logger instance
*/
getLogger(): Logger;
/**
* Replaces the default logger set in configurations with new Logger with new configurations
* @param logger - Logger instance
*/
setLogger(logger: Logger): void;
/**
* Builds the common configuration to be passed to the common component based on the platform configurarion
* @param authority - user passed authority in configuration
* @param serverTelemetryManager - initializes servertelemetry if passed
*/
protected buildOauthClientConfiguration(authority: string, requestCorrelationId: string, redirectUri: string, serverTelemetryManager?: ServerTelemetryManager, azureRegionConfiguration?: AzureRegionConfiguration, azureCloudOptions?: AzureCloudOptions): Promise<ClientConfiguration>;
private getClientAssertion;
/**
* Generates a request with the default scopes & generates a correlationId.
* @param authRequest - BaseAuthRequest for initialization
*/
protected initializeBaseRequest(authRequest: Partial<BaseAuthRequest>): Promise<BaseAuthRequest>;
/**
* Initializes the server telemetry payload
* @param apiId - Id for a specific request
* @param correlationId - GUID
* @param forceRefresh - boolean to indicate network call
*/
protected initializeServerTelemetryManager(apiId: number, correlationId: string, forceRefresh?: boolean): ServerTelemetryManager;
/**
* Create authority instance. If authority not passed in request, default to authority set on the application
* object. If no authority set in application object, then default to common authority.
* @param authorityString - authority from user configuration
*/
private createAuthority;
/**
* Clear the cache
*/
clearCache(): void;
}
//# sourceMappingURL=ClientApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ClientApplication.d.ts","sourceRoot":"","sources":["../../src/client/ClientApplication.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,mBAAmB,EAEnB,oBAAoB,EAGpB,eAAe,EAEf,MAAM,EACN,sBAAsB,EAWtB,wBAAwB,EAExB,iBAAiB,EACjB,wBAAwB,EAQxB,uBAAuB,EAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,aAAa,EAEb,iBAAiB,EACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC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oB,GAAG,IAAI,CAAC;IA0CvC;;;;;;;OAOG;IACG,kBAAkB,CACpB,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,CAAC;IAuChC;;;;;;;;;OASG;IACG,8BAA8B,CAChC,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAwCvC;;OAEG;IACH,aAAa,IAAI,UAAU;IAK3B;;;;;;;;OAQG;IACH,SAAS,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI;IAUjE;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B;;;;OAIG;cACa,6BAA6B,CACzC,SAAS,EAAE,MAAM,EACjB,oBAAoB,EAAE,MAAM,EAC5B,WAAW,EAAE,MAAM,EACnB,sBAAsB,CAAC,EAAE,sBAAsB,EAC/C,wBAAwB,CAAC,EAAE,wBAAwB,EACnD,iBAAiB,CAAC,EAAE,iBAAiB,GACtC,OAAO,CAAC,mBAAmB,CAAC;YAsEjB,kBAAkB;IAyBhC;;;OAGG;cACa,qBAAqB,CACjC,WAAW,EAAE,OAAO,CAAC,eAAe,CAAC,GACtC,OAAO,CAAC,eAAe,CAAC;IA0C3B;;;;;OAKG;IACH,SAAS,CAAC,gCAAgC,CACtC,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,MAAM,EACrB,YAAY,CAAC,EAAE,OAAO,GACvB,sBAAsB;IAWzB;;;;OAIG;YACW,eAAe;IAkC7B;;OAEG;IACH,UAAU,IAAI,IAAI;CAGrB"}

View File

@@ -0,0 +1,351 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { Logger, buildStaticAuthorityOptions, ResponseMode, AuthenticationScheme, AuthorizationCodeClient, AuthError, RefreshTokenClient, SilentFlowClient, createClientAuthError, ClientAuthErrorCodes, Constants as Constants$1, getClientAssertion, StringUtils, OIDC_DEFAULT_SCOPES, ServerTelemetryManager, Authority, AuthorityFactory } from '@azure/msal-common/node';
import { buildAppConfiguration } from '../config/Configuration.mjs';
import { CryptoProvider } from '../crypto/CryptoProvider.mjs';
import { NodeStorage } from '../cache/NodeStorage.mjs';
import { ApiId, Constants } from '../utils/Constants.mjs';
import { TokenCache } from '../cache/TokenCache.mjs';
import { ClientAssertion } from './ClientAssertion.mjs';
import { name, version } from '../packageMetadata.mjs';
import { NodeAuthError } from '../error/NodeAuthError.mjs';
import { UsernamePasswordClient } from './UsernamePasswordClient.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Base abstract class for all ClientApplications - public and confidential
* @public
*/
class ClientApplication {
/**
* Constructor for the ClientApplication
*/
constructor(configuration) {
this.config = buildAppConfiguration(configuration);
this.cryptoProvider = new CryptoProvider();
this.logger = new Logger(this.config.system.loggerOptions, name, version);
this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth));
this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
}
/**
* Creates the URL of the authorization request, letting the user input credentials and consent to the
* application. The URL targets the /authorize endpoint of the authority configured in the
* application object.
*
* Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
* sent in the request and should contain an authorization code, which can then be used to acquire tokens via
* `acquireTokenByCode(AuthorizationCodeRequest)`.
*/
async getAuthCodeUrl(request) {
this.logger.info("getAuthCodeUrl called", request.correlationId);
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
responseMode: request.responseMode || ResponseMode.QUERY,
authenticationScheme: AuthenticationScheme.BEARER,
};
const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, validRequest.redirectUri, undefined, undefined, request.azureCloudOptions);
const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig);
this.logger.verbose("Auth code client created", validRequest.correlationId);
return authorizationCodeClient.getAuthCodeUrl(validRequest);
}
/**
* Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
* Authorization Code flow.
*
* `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
* Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
* AuthorizationCodeRequest are the same.
*/
async acquireTokenByCode(request, authCodePayLoad) {
this.logger.info("acquireTokenByCode called");
if (request.state && authCodePayLoad) {
this.logger.info("acquireTokenByCode - validating state");
this.validateState(request.state, authCodePayLoad.state || "");
// eslint-disable-next-line no-param-reassign
authCodePayLoad = { ...authCodePayLoad, state: "" };
}
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
authenticationScheme: AuthenticationScheme.BEARER,
};
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);
try {
const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager, undefined, request.azureCloudOptions);
const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig);
this.logger.verbose("Auth code client created", validRequest.correlationId);
return await authorizationCodeClient.acquireToken(validRequest, authCodePayLoad);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Acquires a token by exchanging the refresh token provided for a new set of tokens.
*
* This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
* recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
* handle the caching and refreshing of tokens automatically.
*/
async acquireTokenByRefreshToken(request) {
this.logger.info("acquireTokenByRefreshToken called", request.correlationId);
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
authenticationScheme: AuthenticationScheme.BEARER,
};
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
try {
const refreshTokenClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager, undefined, request.azureCloudOptions);
const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig);
this.logger.verbose("Refresh token client created", validRequest.correlationId);
return await refreshTokenClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Acquires a token silently when a user specifies the account the token is requested for.
*
* This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
* There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
* In case the refresh_token is expired or not found, an error is thrown
* and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
*/
async acquireTokenSilent(request) {
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
forceRefresh: request.forceRefresh || false,
};
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
try {
const silentFlowClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager, undefined, request.azureCloudOptions);
const silentFlowClient = new SilentFlowClient(silentFlowClientConfig);
this.logger.verbose("Silent flow client created", validRequest.correlationId);
return await silentFlowClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Acquires tokens with password grant by exchanging client applications username and password for credentials
*
* The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
* More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
* Microsoft's documentation and recommendations are at:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
*
* @param request - UsenamePasswordRequest
*/
async acquireTokenByUsernamePassword(request) {
this.logger.info("acquireTokenByUsernamePassword called", request.correlationId);
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
};
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
try {
const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, "", serverTelemetryManager, undefined, request.azureCloudOptions);
const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);
this.logger.verbose("Username password client created", validRequest.correlationId);
return await usernamePasswordClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Gets the token cache for the application.
*/
getTokenCache() {
this.logger.info("getTokenCache called");
return this.tokenCache;
}
/**
* Validates OIDC state by comparing the user cached state with the state received from the server.
*
* This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
* CSRF attacks.
* For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
* @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow
* @param cachedState - This string is sent back by the server with the authorization code
*/
validateState(state, cachedState) {
if (!state) {
throw NodeAuthError.createStateNotFoundError();
}
if (state !== cachedState) {
throw createClientAuthError(ClientAuthErrorCodes.stateMismatch);
}
}
/**
* Returns the logger instance
*/
getLogger() {
return this.logger;
}
/**
* Replaces the default logger set in configurations with new Logger with new configurations
* @param logger - Logger instance
*/
setLogger(logger) {
this.logger = logger;
}
/**
* Builds the common configuration to be passed to the common component based on the platform configurarion
* @param authority - user passed authority in configuration
* @param serverTelemetryManager - initializes servertelemetry if passed
*/
async buildOauthClientConfiguration(authority, requestCorrelationId, redirectUri, serverTelemetryManager, azureRegionConfiguration, azureCloudOptions) {
this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
// precedence - azureCloudInstance + tenant >> authority and request >> config
const userAzureCloudOptions = azureCloudOptions
? azureCloudOptions
: this.config.auth.azureCloudOptions;
// using null assertion operator as we ensure that all config values have default values in buildConfiguration()
const discoveredAuthority = await this.createAuthority(authority, requestCorrelationId, azureRegionConfiguration, userAzureCloudOptions);
this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId);
serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
const clientConfiguration = {
authOptions: {
clientId: this.config.auth.clientId,
authority: discoveredAuthority,
clientCapabilities: this.config.auth.clientCapabilities,
redirectUri,
},
loggerOptions: {
logLevel: this.config.system.loggerOptions.logLevel,
loggerCallback: this.config.system.loggerOptions.loggerCallback,
piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
correlationId: requestCorrelationId,
},
cacheOptions: {
claimsBasedCachingEnabled: this.config.cache.claimsBasedCachingEnabled,
},
cryptoInterface: this.cryptoProvider,
networkInterface: this.config.system.networkClient,
storageInterface: this.storage,
serverTelemetryManager: serverTelemetryManager,
clientCredentials: {
clientSecret: this.clientSecret,
clientAssertion: await this.getClientAssertion(discoveredAuthority),
},
libraryInfo: {
sku: Constants.MSAL_SKU,
version: version,
cpu: process.arch || Constants$1.EMPTY_STRING,
os: process.platform || Constants$1.EMPTY_STRING,
},
telemetry: this.config.telemetry,
persistencePlugin: this.config.cache.cachePlugin,
serializableCache: this.tokenCache,
};
return clientConfiguration;
}
async getClientAssertion(authority) {
if (this.developerProvidedClientAssertion) {
this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint));
}
return (this.clientAssertion && {
assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
assertionType: Constants.JWT_BEARER_ASSERTION_TYPE,
});
}
/**
* Generates a request with the default scopes & generates a correlationId.
* @param authRequest - BaseAuthRequest for initialization
*/
async initializeBaseRequest(authRequest) {
this.logger.verbose("initializeRequestScopes called", authRequest.correlationId);
// Default authenticationScheme to Bearer, log that POP isn't supported yet
if (authRequest.authenticationScheme &&
authRequest.authenticationScheme === AuthenticationScheme.POP) {
this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId);
}
authRequest.authenticationScheme = AuthenticationScheme.BEARER;
// Set requested claims hash if claims-based caching is enabled and claims were requested
if (this.config.cache.claimsBasedCachingEnabled &&
authRequest.claims &&
// Checks for empty stringified object "{}" which doesn't qualify as requested claims
!StringUtils.isEmptyObj(authRequest.claims)) {
authRequest.requestedClaimsHash =
await this.cryptoProvider.hashString(authRequest.claims);
}
return {
...authRequest,
scopes: [
...((authRequest && authRequest.scopes) || []),
...OIDC_DEFAULT_SCOPES,
],
correlationId: (authRequest && authRequest.correlationId) ||
this.cryptoProvider.createNewGuid(),
authority: authRequest.authority || this.config.auth.authority,
};
}
/**
* Initializes the server telemetry payload
* @param apiId - Id for a specific request
* @param correlationId - GUID
* @param forceRefresh - boolean to indicate network call
*/
initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
const telemetryPayload = {
clientId: this.config.auth.clientId,
correlationId: correlationId,
apiId: apiId,
forceRefresh: forceRefresh || false,
};
return new ServerTelemetryManager(telemetryPayload, this.storage);
}
/**
* Create authority instance. If authority not passed in request, default to authority set on the application
* object. If no authority set in application object, then default to common authority.
* @param authorityString - authority from user configuration
*/
async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) {
this.logger.verbose("createAuthority called", requestCorrelationId);
// build authority string based on auth params - azureCloudInstance is prioritized if provided
const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions);
const authorityOptions = {
protocolMode: this.config.auth.protocolMode,
knownAuthorities: this.config.auth.knownAuthorities,
cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
authorityMetadata: this.config.auth.authorityMetadata,
azureRegionConfiguration,
skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache,
};
return AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId);
}
/**
* Clear the cache
*/
clearCache() {
this.storage.clear();
}
}
export { ClientApplication };
//# sourceMappingURL=ClientApplication.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,56 @@
import { CryptoProvider } from "../crypto/CryptoProvider.js";
/**
* Client assertion of type jwt-bearer used in confidential client flows
* @public
*/
export declare class ClientAssertion {
private jwt;
private privateKey;
private thumbprint;
private useSha256;
private expirationTime;
private issuer;
private jwtAudience;
private publicCertificate;
/**
* Initialize the ClientAssertion class from the clientAssertion passed by the user
* @param assertion - refer https://tools.ietf.org/html/rfc7521
*/
static fromAssertion(assertion: string): ClientAssertion;
/**
* @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint
* Initialize the ClientAssertion class from the certificate passed by the user
* @param thumbprint - identifier of a certificate
* @param privateKey - secret key
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static fromCertificate(thumbprint: string, privateKey: string, publicCertificate?: string): ClientAssertion;
/**
* Initialize the ClientAssertion class from the certificate passed by the user
* @param thumbprint - identifier of a certificate
* @param privateKey - secret key
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static fromCertificateWithSha256Thumbprint(thumbprint: string, privateKey: string, publicCertificate?: string): ClientAssertion;
/**
* Update JWT for certificate based clientAssertion, if passed by the user, uses it as is
* @param cryptoProvider - library's crypto helper
* @param issuer - iss claim
* @param jwtAudience - aud claim
*/
getJwt(cryptoProvider: CryptoProvider, issuer: string, jwtAudience: string): string;
/**
* JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
*/
private createJwt;
/**
* Utility API to check expiration
*/
private isExpired;
/**
* Extracts the raw certs from a given certificate string and returns them in an array.
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static parseCertificate(publicCertificate: string): Array<string>;
}
//# sourceMappingURL=ClientAssertion.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ClientAssertion.d.ts","sourceRoot":"","sources":["../../src/client/ClientAssertion.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAI7D;;;GAGG;AACH,qBAAa,eAAe;IACxB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAU;IAC3B,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,iBAAiB,CAAgB;IAEzC;;;OAGG;WACW,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,eAAe;IAM/D;;;;;;OAMG;WACW,eAAe,CACzB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,MAAM,GAC3B,eAAe;IAYlB;;;;;OAKG;WACW,mCAAmC,CAC7C,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,iBAAiB,CAAC,EAAE,MAAM,GAC3B,eAAe;IAYlB;;;;;OAKG;IACI,MAAM,CACT,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GACpB,MAAM;IA0BT;;OAEG;IACH,OAAO,CAAC,SAAS;IA8CjB;;OAEG;IACH,OAAO,CAAC,SAAS;IAIjB;;;OAGG;WACW,gBAAgB,CAAC,iBAAiB,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;CAoB3E"}

View File

@@ -0,0 +1,153 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import jwt from 'jsonwebtoken';
import { createClientAuthError, ClientAuthErrorCodes, TimeUtils, Constants } from '@azure/msal-common/node';
import { EncodingUtils } from '../utils/EncodingUtils.mjs';
import { JwtConstants } from '../utils/Constants.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Client assertion of type jwt-bearer used in confidential client flows
* @public
*/
class ClientAssertion {
/**
* Initialize the ClientAssertion class from the clientAssertion passed by the user
* @param assertion - refer https://tools.ietf.org/html/rfc7521
*/
static fromAssertion(assertion) {
const clientAssertion = new ClientAssertion();
clientAssertion.jwt = assertion;
return clientAssertion;
}
/**
* @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint
* Initialize the ClientAssertion class from the certificate passed by the user
* @param thumbprint - identifier of a certificate
* @param privateKey - secret key
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static fromCertificate(thumbprint, privateKey, publicCertificate) {
const clientAssertion = new ClientAssertion();
clientAssertion.privateKey = privateKey;
clientAssertion.thumbprint = thumbprint;
clientAssertion.useSha256 = false;
if (publicCertificate) {
clientAssertion.publicCertificate =
this.parseCertificate(publicCertificate);
}
return clientAssertion;
}
/**
* Initialize the ClientAssertion class from the certificate passed by the user
* @param thumbprint - identifier of a certificate
* @param privateKey - secret key
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) {
const clientAssertion = new ClientAssertion();
clientAssertion.privateKey = privateKey;
clientAssertion.thumbprint = thumbprint;
clientAssertion.useSha256 = true;
if (publicCertificate) {
clientAssertion.publicCertificate =
this.parseCertificate(publicCertificate);
}
return clientAssertion;
}
/**
* Update JWT for certificate based clientAssertion, if passed by the user, uses it as is
* @param cryptoProvider - library's crypto helper
* @param issuer - iss claim
* @param jwtAudience - aud claim
*/
getJwt(cryptoProvider, issuer, jwtAudience) {
// if assertion was created from certificate, check if jwt is expired and create new one.
if (this.privateKey && this.thumbprint) {
if (this.jwt &&
!this.isExpired() &&
issuer === this.issuer &&
jwtAudience === this.jwtAudience) {
return this.jwt;
}
return this.createJwt(cryptoProvider, issuer, jwtAudience);
}
/*
* if assertion was created by caller, then we just append it. It is up to the caller to
* ensure that it contains necessary claims and that it is not expired.
*/
if (this.jwt) {
return this.jwt;
}
throw createClientAuthError(ClientAuthErrorCodes.invalidAssertion);
}
/**
* JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
*/
createJwt(cryptoProvider, issuer, jwtAudience) {
this.issuer = issuer;
this.jwtAudience = jwtAudience;
const issuedAt = TimeUtils.nowSeconds();
this.expirationTime = issuedAt + 600;
const algorithm = this.useSha256
? JwtConstants.PSS_256
: JwtConstants.RSA_256;
const header = {
alg: algorithm,
};
const thumbprintHeader = this.useSha256
? JwtConstants.X5T_256
: JwtConstants.X5T;
Object.assign(header, {
[thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, "hex"),
});
if (this.publicCertificate) {
Object.assign(header, {
[JwtConstants.X5C]: this.publicCertificate,
});
}
const payload = {
[JwtConstants.AUDIENCE]: this.jwtAudience,
[JwtConstants.EXPIRATION_TIME]: this.expirationTime,
[JwtConstants.ISSUER]: this.issuer,
[JwtConstants.SUBJECT]: this.issuer,
[JwtConstants.NOT_BEFORE]: issuedAt,
[JwtConstants.JWT_ID]: cryptoProvider.createNewGuid(),
};
this.jwt = jwt.sign(payload, this.privateKey, { header });
return this.jwt;
}
/**
* Utility API to check expiration
*/
isExpired() {
return this.expirationTime < TimeUtils.nowSeconds();
}
/**
* Extracts the raw certs from a given certificate string and returns them in an array.
* @param publicCertificate - electronic document provided to prove the ownership of the public key
*/
static parseCertificate(publicCertificate) {
/**
* This is regex to identify the certs in a given certificate string.
* We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.
* The information in parens "(.+?)" is the capture group to represent the cert we want isolated.
* "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
* The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
*/
const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
const certs = [];
let matches;
while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
// matches[1] represents the first parens capture group in the regex.
certs.push(matches[1].replace(/\r*\n/g, Constants.EMPTY_STRING));
}
return certs;
}
}
export { ClientAssertion };
//# sourceMappingURL=ClientAssertion.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ClientAssertion.mjs","sources":["../../src/client/ClientAssertion.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;;AAAA;;;AAGG;AAaH;;;AAGG;MACU,eAAe,CAAA;AAUxB;;;AAGG;IACI,OAAO,aAAa,CAAC,SAAiB,EAAA;AACzC,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAC9C,QAAA,eAAe,CAAC,GAAG,GAAG,SAAS,CAAC;AAChC,QAAA,OAAO,eAAe,CAAC;KAC1B;AAED;;;;;;AAMG;AACI,IAAA,OAAO,eAAe,CACzB,UAAkB,EAClB,UAAkB,EAClB,iBAA0B,EAAA;AAE1B,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAC9C,QAAA,eAAe,CAAC,UAAU,GAAG,UAAU,CAAC;AACxC,QAAA,eAAe,CAAC,UAAU,GAAG,UAAU,CAAC;AACxC,QAAA,eAAe,CAAC,SAAS,GAAG,KAAK,CAAC;AAClC,QAAA,IAAI,iBAAiB,EAAE;AACnB,YAAA,eAAe,CAAC,iBAAiB;AAC7B,gBAAA,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,CAAC,CAAC;AAChD,SAAA;AACD,QAAA,OAAO,eAAe,CAAC;KAC1B;AAED;;;;;AAKG;AACI,IAAA,OAAO,mCAAmC,CAC7C,UAAkB,EAClB,UAAkB,EAClB,iBAA0B,EAAA;AAE1B,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAC9C,QAAA,eAAe,CAAC,UAAU,GAAG,UAAU,CAAC;AACxC,QAAA,eAAe,CAAC,UAAU,GAAG,UAAU,CAAC;AACxC,QAAA,eAAe,CAAC,SAAS,GAAG,IAAI,CAAC;AACjC,QAAA,IAAI,iBAAiB,EAAE;AACnB,YAAA,eAAe,CAAC,iBAAiB;AAC7B,gBAAA,IAAI,CA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CAAC;AACZ,QAAA,OAAO,CAAC,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,IAAI,EAAE;;AAElE,YAAA,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC;AACpE,SAAA;AAED,QAAA,OAAO,KAAK,CAAC;KAChB;AACJ;;;;"}

View File

@@ -0,0 +1,35 @@
import { AuthenticationResult, Authority, BaseClient, CacheManager, CacheOutcome, ClientConfiguration, CommonClientCredentialRequest, IAppTokenProvider, ICrypto, ServerTelemetryManager } from "@azure/msal-common/node";
import { ManagedIdentityConfiguration } from "../config/Configuration.js";
/**
* OAuth2.0 client credential grant
* @public
*/
export declare class ClientCredentialClient extends BaseClient {
private readonly appTokenProvider?;
constructor(configuration: ClientConfiguration, appTokenProvider?: IAppTokenProvider);
/**
* Public API to acquire a token with ClientCredential Flow for Confidential clients
* @param request - CommonClientCredentialRequest provided by the developer
*/
acquireToken(request: CommonClientCredentialRequest): Promise<AuthenticationResult | null>;
/**
* looks up cache if the tokens are cached already
*/
getCachedAuthenticationResult(request: CommonClientCredentialRequest, config: ClientConfiguration | ManagedIdentityConfiguration, cryptoUtils: ICrypto, authority: Authority, cacheManager: CacheManager, serverTelemetryManager?: ServerTelemetryManager | null): Promise<[AuthenticationResult | null, CacheOutcome]>;
/**
* Reads access token from the cache
*/
private readAccessTokenFromCache;
/**
* Makes a network call to request the token from the service
* @param request - CommonClientCredentialRequest provided by the developer
* @param authority - authority object
*/
private executeTokenRequest;
/**
* generate the request to the server in the acceptable format
* @param request - CommonClientCredentialRequest provided by the developer
*/
private createTokenRequestBody;
}
//# sourceMappingURL=ClientCredentialClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ClientCredentialClient.d.ts","sourceRoot":"","sources":["../../src/client/ClientCredentialClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,oBAAoB,EAEpB,SAAS,EACT,UAAU,EACV,YAAY,EACZ,YAAY,EAEZ,mBAAmB,EACnB,6BAA6B,EAM7B,iBAAiB,EACjB,OAAO,EAMP,sBAAsB,EAQzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,4BAA4B,EAE/B,MAAM,4BAA4B,CAAC;AAEpC;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;IAClD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAoB;gBAGlD,aAAa,EAAE,mBAAmB,EAClC,gBAAgB,CAAC,EAAE,iBAAiB;IAMxC;;;OAGG;IACU,YAAY,CACrB,OAAO,EAAE,6BAA6B,GACvC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAsCvC;;OAEG;IACU,6BAA6B,CACtC,OAAO,EAAE,6BAA6B,EACtC,MAAM,EAAE,mBAAmB,GAAG,4BAA4B,EAC1D,WAAW,EAAE,OAAO,EACpB,SAAS,EAAE,SAAS,EACpB,YAAY,EAAE,YAAY,EAC1B,sBAAsB,CAAC,EAAE,sBAAsB,GAAG,IAAI,GACvD,OAAO,CAAC,CAAC,oBAAoB,GAAG,IAAI,EAAE,YAAY,CAAC,CAAC;IA2FvD;;OAEG;IACH,OAAO,CAAC,wBAAwB;IA4BhC;;;;OAIG;YACW,mBAAmB;IA6FjC;;;OAGG;YACW,sBAAsB;CAgEvC"}

View File

@@ -0,0 +1,202 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { BaseClient, CacheOutcome, TokenCacheContext, ScopeSet, TimeUtils, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, ResponseHandler, Constants, CredentialType, createClientAuthError, ClientAuthErrorCodes, UrlString, RequestParameterBuilder, GrantType, getClientAssertion, StringUtils, AuthenticationScheme } from '@azure/msal-common/node';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* OAuth2.0 client credential grant
* @public
*/
class ClientCredentialClient extends BaseClient {
constructor(configuration, appTokenProvider) {
super(configuration);
this.appTokenProvider = appTokenProvider;
}
/**
* Public API to acquire a token with ClientCredential Flow for Confidential clients
* @param request - CommonClientCredentialRequest provided by the developer
*/
async acquireToken(request) {
if (request.skipCache || request.claims) {
return this.executeTokenRequest(request, this.authority);
}
const [cachedAuthenticationResult, lastCacheOutcome] = await this.getCachedAuthenticationResult(request, this.config, this.cryptoUtils, this.authority, this.cacheManager, this.serverTelemetryManager);
if (cachedAuthenticationResult) {
// if the token is not expired but must be refreshed; get a new one in the background
if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");
// refresh the access token in the background
const refreshAccessToken = true;
await this.executeTokenRequest(request, this.authority, refreshAccessToken);
}
// return the cached token
return cachedAuthenticationResult;
}
else {
return this.executeTokenRequest(request, this.authority);
}
}
/**
* looks up cache if the tokens are cached already
*/
async getCachedAuthenticationResult(request, config, cryptoUtils, authority, cacheManager, serverTelemetryManager) {
const clientConfiguration = config;
const managedIdentityConfiguration = config;
let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
// read the user-supplied cache into memory, if applicable
let cacheContext;
if (clientConfiguration.serializableCache &&
clientConfiguration.persistencePlugin) {
cacheContext = new TokenCacheContext(clientConfiguration.serializableCache, false);
await clientConfiguration.persistencePlugin.beforeCacheAccess(cacheContext);
}
const cachedAccessToken = this.readAccessTokenFromCache(authority, managedIdentityConfiguration.managedIdentityId?.id ||
clientConfiguration.authOptions.clientId, new ScopeSet(request.scopes || []), cacheManager);
if (clientConfiguration.serializableCache &&
clientConfiguration.persistencePlugin &&
cacheContext) {
await clientConfiguration.persistencePlugin.afterCacheAccess(cacheContext);
}
// must refresh due to non-existent access_token
if (!cachedAccessToken) {
serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN];
}
// must refresh due to the expires_in value
if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, clientConfiguration.systemOptions?.tokenRenewalOffsetSeconds ||
DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];
}
// must refresh (in the background) due to the refresh_in value
if (cachedAccessToken.refreshOn &&
TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)) {
lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
serverTelemetryManager?.setCacheOutcome(CacheOutcome.PROACTIVELY_REFRESHED);
}
return [
await ResponseHandler.generateAuthenticationResult(cryptoUtils, authority, {
account: null,
idToken: null,
accessToken: cachedAccessToken,
refreshToken: null,
appMetadata: null,
}, true, request),
lastCacheOutcome,
];
}
/**
* Reads access token from the cache
*/
readAccessTokenFromCache(authority, id, scopeSet, cacheManager) {
const accessTokenFilter = {
homeAccountId: Constants.EMPTY_STRING,
environment: authority.canonicalAuthorityUrlComponents.HostNameAndPort,
credentialType: CredentialType.ACCESS_TOKEN,
clientId: id,
realm: authority.tenant,
target: ScopeSet.createSearchScopes(scopeSet.asArray()),
};
const accessTokens = cacheManager.getAccessTokensByFilter(accessTokenFilter);
if (accessTokens.length < 1) {
return null;
}
else if (accessTokens.length > 1) {
throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens);
}
return accessTokens[0];
}
/**
* Makes a network call to request the token from the service
* @param request - CommonClientCredentialRequest provided by the developer
* @param authority - authority object
*/
async executeTokenRequest(request, authority, refreshAccessToken) {
let serverTokenResponse;
let reqTimestamp;
if (this.appTokenProvider) {
this.logger.info("Using appTokenProvider extensibility.");
const appTokenPropviderParameters = {
correlationId: request.correlationId,
tenantId: this.config.authOptions.authority.tenant,
scopes: request.scopes,
claims: request.claims,
};
reqTimestamp = TimeUtils.nowSeconds();
const appTokenProviderResult = await this.appTokenProvider(appTokenPropviderParameters);
serverTokenResponse = {
access_token: appTokenProviderResult.accessToken,
expires_in: appTokenProviderResult.expiresInSeconds,
refresh_in: appTokenProviderResult.refreshInSeconds,
token_type: AuthenticationScheme.BEARER,
};
}
else {
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await this.createTokenRequestBody(request);
const headers = this.createTokenRequestHeaders();
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
this.logger.info("Sending token request to endpoint: " + authority.tokenEndpoint);
reqTimestamp = TimeUtils.nowSeconds();
const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
serverTokenResponse = response.body;
serverTokenResponse.status = response.status;
}
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken);
const tokenResponse = await responseHandler.handleServerTokenResponse(serverTokenResponse, this.authority, reqTimestamp, request);
return tokenResponse;
}
/**
* generate the request to the server in the acceptable format
* @param request - CommonClientCredentialRequest provided by the developer
*/
async createTokenRequestBody(request) {
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes, false);
parameterBuilder.addGrantType(GrantType.CLIENT_CREDENTIALS_GRANT);
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
// Use clientAssertion from request, fallback to client assertion in base configuration
const clientAssertion = request.clientAssertion ||
this.config.clientCredentials.clientAssertion;
if (clientAssertion) {
parameterBuilder.addClientAssertion(await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return parameterBuilder.createQueryString();
}
}
export { ClientCredentialClient };
//# sourceMappingURL=ClientCredentialClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,59 @@
import { ClientApplication } from "./ClientApplication.js";
import { Configuration } from "../config/Configuration.js";
import { AuthenticationResult, IAppTokenProvider } from "@azure/msal-common/node";
import { IConfidentialClientApplication } from "./IConfidentialClientApplication.js";
import { OnBehalfOfRequest } from "../request/OnBehalfOfRequest.js";
import { ClientCredentialRequest } from "../request/ClientCredentialRequest.js";
/**
* This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications
* will configure application secrets, client certificates/assertions as applicable
* @public
*/
export declare class ConfidentialClientApplication extends ClientApplication implements IConfidentialClientApplication {
private appTokenProvider?;
/**
* Constructor for the ConfidentialClientApplication
*
* Required attributes in the Configuration object are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
* - authority: the authority URL for your application.
* - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
*
* In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
* Full B2C functionality will be available in this library in future versions.
*
* @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
*/
constructor(configuration: Configuration);
/**
* This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
* is meant for Azure SDK to enhance Managed Identity support.
*
* @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
*/
SetAppTokenProvider(provider: IAppTokenProvider): void;
/**
* Acquires tokens from the authority for the application (not for an end user).
*/
acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null>;
/**
* Acquires tokens from the authority for the application.
*
* Used in scenarios where the current app is a middle-tier service which was called with a token
* representing an end user. The current app can use the token (oboAssertion) to request another
* token to access downstream web API, on behalf of that user.
*
* The current middle-tier app has no user interaction to obtain consent.
* See how to gain consent upfront for your middle-tier app from this article.
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
*/
acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null>;
private setClientCredential;
}
//# sourceMappingURL=ConfidentialClientApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConfidentialClientApplication.d.ts","sourceRoot":"","sources":["../../src/client/ConfidentialClientApplication.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAQ3D,OAAO,EAGH,oBAAoB,EAGpB,iBAAiB,EASpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAIhF;;;;GAIG;AACH,qBAAa,6BACT,SAAQ,iBACR,YAAW,8BAA8B;IAEzC,OAAO,CAAC,gBAAgB,CAAC,CAAoB;IAE7C;;;;;;;;;;;;;;;;;;OAkBG;gBACS,aAAa,EAAE,aAAa;IAMxC;;;;;OAKG;IACH,mBAAmB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;IAItD;;OAEG;IACU,8BAA8B,CACvC,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAyGvC;;;;;;;;;;OAUG;IACU,sBAAsB,CAC/B,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAgCvC,OAAO,CAAC,mBAAmB;CA0D9B"}

View File

@@ -0,0 +1,195 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { ClientApplication } from './ClientApplication.mjs';
import { ClientAssertion } from './ClientAssertion.mjs';
import { Constants, MSAL_FORCE_REGION, REGION_ENVIRONMENT_VARIABLE, ApiId } from '../utils/Constants.mjs';
import { getClientAssertion, OIDC_DEFAULT_SCOPES, UrlString, AADAuthorityConstants, createClientAuthError, ClientAuthErrorCodes, AuthError } from '@azure/msal-common/node';
import { ClientCredentialClient } from './ClientCredentialClient.mjs';
import { OnBehalfOfClient } from './OnBehalfOfClient.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// AADAuthorityConstants
/**
* This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications
* will configure application secrets, client certificates/assertions as applicable
* @public
*/
class ConfidentialClientApplication extends ClientApplication {
/**
* Constructor for the ConfidentialClientApplication
*
* Required attributes in the Configuration object are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
* - authority: the authority URL for your application.
* - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
*
* In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
* Full B2C functionality will be available in this library in future versions.
*
* @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
*/
constructor(configuration) {
super(configuration);
this.setClientCredential();
this.appTokenProvider = undefined;
}
/**
* This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
* is meant for Azure SDK to enhance Managed Identity support.
*
* @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
*/
SetAppTokenProvider(provider) {
this.appTokenProvider = provider;
}
/**
* Acquires tokens from the authority for the application (not for an end user).
*/
async acquireTokenByClientCredential(request) {
this.logger.info("acquireTokenByClientCredential called", request.correlationId);
// If there is a client assertion present in the request, it overrides the one present in the client configuration
let clientAssertion;
if (request.clientAssertion) {
clientAssertion = {
assertion: await getClientAssertion(request.clientAssertion, this.config.auth.clientId
// tokenEndpoint will be undefined. resourceRequestUri is omitted in ClientCredentialRequest
),
assertionType: Constants.JWT_BEARER_ASSERTION_TYPE,
};
}
const baseRequest = await this.initializeBaseRequest(request);
// valid base request should not contain oidc scopes in this grant type
const validBaseRequest = {
...baseRequest,
scopes: baseRequest.scopes.filter((scope) => !OIDC_DEFAULT_SCOPES.includes(scope)),
};
const validRequest = {
...request,
...validBaseRequest,
clientAssertion,
};
/*
* valid request should not have "common" or "organizations" in lieu of the tenant_id in the authority in the auth configuration
* example authority: "https://login.microsoftonline.com/TenantId",
*/
const authority = new UrlString(validRequest.authority);
const tenantId = authority.getUrlComponents().PathSegments[0];
if (Object.values(AADAuthorityConstants).includes(tenantId)) {
throw createClientAuthError(ClientAuthErrorCodes.missingTenantIdError);
}
/*
* if this env variable is set, and the developer provided region isn't defined and isn't "DisableMsalForceRegion",
* MSAL shall opt-in to ESTS-R with the value of this variable
*/
const ENV_MSAL_FORCE_REGION = process.env[MSAL_FORCE_REGION];
let region;
if (validRequest.azureRegion !== "DisableMsalForceRegion") {
if (!validRequest.azureRegion && ENV_MSAL_FORCE_REGION) {
region = ENV_MSAL_FORCE_REGION;
}
else {
region = validRequest.azureRegion;
}
}
const azureRegionConfiguration = {
azureRegion: region,
environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE],
};
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);
try {
const clientCredentialConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, "", serverTelemetryManager, azureRegionConfiguration, request.azureCloudOptions);
const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);
this.logger.verbose("Client credential client created", validRequest.correlationId);
return await clientCredentialClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Acquires tokens from the authority for the application.
*
* Used in scenarios where the current app is a middle-tier service which was called with a token
* representing an end user. The current app can use the token (oboAssertion) to request another
* token to access downstream web API, on behalf of that user.
*
* The current middle-tier app has no user interaction to obtain consent.
* See how to gain consent upfront for your middle-tier app from this article.
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
*/
async acquireTokenOnBehalfOf(request) {
this.logger.info("acquireTokenOnBehalfOf called", request.correlationId);
const validRequest = {
...request,
...(await this.initializeBaseRequest(request)),
};
try {
const onBehalfOfConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, "", undefined, undefined, request.azureCloudOptions);
const oboClient = new OnBehalfOfClient(onBehalfOfConfig);
this.logger.verbose("On behalf of client created", validRequest.correlationId);
return await oboClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
throw e;
}
}
setClientCredential() {
const clientSecretNotEmpty = !!this.config.auth.clientSecret;
const clientAssertionNotEmpty = !!this.config.auth.clientAssertion;
const certificateNotEmpty = (!!this.config.auth.clientCertificate?.thumbprint ||
!!this.config.auth.clientCertificate?.thumbprintSha256) &&
!!this.config.auth.clientCertificate?.privateKey;
/*
* If app developer configures this callback, they don't need a credential
* i.e. AzureSDK can get token from Managed Identity without a cert / secret
*/
if (this.appTokenProvider) {
return;
}
// Check that at most one credential is set on the application
if ((clientSecretNotEmpty && clientAssertionNotEmpty) ||
(clientAssertionNotEmpty && certificateNotEmpty) ||
(clientSecretNotEmpty && certificateNotEmpty)) {
throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential);
}
if (this.config.auth.clientSecret) {
this.clientSecret = this.config.auth.clientSecret;
return;
}
if (this.config.auth.clientAssertion) {
this.developerProvidedClientAssertion =
this.config.auth.clientAssertion;
return;
}
if (!certificateNotEmpty) {
throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential);
}
else {
this.clientAssertion = !!this.config.auth.clientCertificate
.thumbprintSha256
? ClientAssertion.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c)
: ClientAssertion.fromCertificate(
// guaranteed to be a string, due to prior error checking in this function
this.config.auth.clientCertificate.thumbprint, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c);
}
}
}
export { ConfidentialClientApplication };
//# sourceMappingURL=ConfidentialClientApplication.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConfidentialClientApplication.mjs","sources":["../../src/client/ConfidentialClientApplication.ts"],"sourcesContent":[null],"names":["NodeConstants"],"mappings":";;;;;;;;;AAAA;;;AAGG;AAEH;AAiCA;;;;AAIG;AACG,MAAO,6BACT,SAAQ,iBAAiB,CAAA;AAKzB;;;;;;;;;;;;;;;;;;AAkBG;AACH,IAAA,WAAA,CAAY,aAA4B,EAAA;QACpC,KAAK,CAAC,aAAa,CAAC,CAAC;QACrB,IAAI,CAAC,mBAAmB,EAAE,CAAC;AAC3B,QAAA,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;KACrC;AAED;;;;;AAKG;AACH,IAAA,mBAAmB,CAAC,QAA2B,EAAA;AAC3C,QAAA,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;KACpC;AAED;;AAEG;IACI,MAAM,8BAA8B,CACvC,OAAgC,EAAA;QAEhC,IAAI,CAAC,MAAM,CAAC,IAAI,CACZ,uCAAuC,EACvC,OAAO,CAAC,aAAa,CACxB,CAAC;;AAGF,QAAA,IAAI,eAAgD,CAAC;QACrD,IAAI,OAAO,CAAC,eAAe,EAAE;AACzB,YAAA,eAAe,GAAG;AACd,gBAAA,SAAS,EAAE,MAAM,kBAAkB,CAC/B,OAAO,CAAC,eAAe,EACvB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ;;AAE5B,iBAAA;gBACD,aAAa,EAAEA,SAAa,CAAC,yBAAyB;aACzD,CAAC;AACL,SAAA;QAED,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;;AAG9D,QAAA,MAAM,gBAAgB,GAAG;AACrB,YAAA,GAAG,WAAW;AACd,YAAA,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,MAAM,CAC7B,CAAC,KAAa,KAAK,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAC1D;SACJ,CAAC;AAE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,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC;YACrC,OAAO;AACV,SAAA;QAED,IAAI,CAAC,mBAAmB,EAAE;AACtB,YAAA,MAAM,qBAAqB,CACvB,oBAAoB,CAAC,uBAAuB,CAC/C,CAAC;AACL,SAAA;AAAM,aAAA;YACH,IAAI,CAAC,eAAe,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB;iBACtD,gBAAgB;AACjB,kBAAE,eAAe,CAAC,mCAAmC,CAC/C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,gBAAgB,EACnD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAC7C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CACzC;kBACD,eAAe,CAAC,eAAe;;AAE3B,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,UAAoB,EACvD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAC7C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CACzC,CAAC;AACX,SAAA;KACJ;AACJ;;;;"}

View File

@@ -0,0 +1,58 @@
import { AuthenticationResult, BaseClient, ClientConfiguration, CommonDeviceCodeRequest } from "@azure/msal-common/node";
/**
* OAuth2.0 Device code client
* @public
*/
export declare class DeviceCodeClient extends BaseClient {
constructor(configuration: ClientConfiguration);
/**
* Gets device code from device code endpoint, calls back to with device code response, and
* polls token endpoint to exchange device code for tokens
* @param request - developer provided CommonDeviceCodeRequest
*/
acquireToken(request: CommonDeviceCodeRequest): Promise<AuthenticationResult | null>;
/**
* Creates device code request and executes http GET
* @param request - developer provided CommonDeviceCodeRequest
*/
private getDeviceCode;
/**
* Creates query string for the device code request
* @param request - developer provided CommonDeviceCodeRequest
*/
createExtraQueryParameters(request: CommonDeviceCodeRequest): string;
/**
* Executes POST request to device code endpoint
* @param deviceCodeEndpoint - token endpoint
* @param queryString - string to be used in the body of the request
* @param headers - headers for the request
* @param thumbprint - unique request thumbprint
* @param correlationId - correlation id to be used in the request
*/
private executePostRequestToDeviceCodeEndpoint;
/**
* Create device code endpoint query parameters and returns string
* @param request - developer provided CommonDeviceCodeRequest
*/
private createQueryString;
/**
* Breaks the polling with specific conditions
* @param deviceCodeExpirationTime - expiration time for the device code request
* @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime
* @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request
*/
private continuePolling;
/**
* Creates token request with device code response and polls token endpoint at interval set by the device code response
* @param request - developer provided CommonDeviceCodeRequest
* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
*/
private acquireTokenWithDeviceCode;
/**
* Creates query parameters and converts to string.
* @param request - developer provided CommonDeviceCodeRequest
* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
*/
private createTokenRequestBody;
}
//# sourceMappingURL=DeviceCodeClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"DeviceCodeClient.d.ts","sourceRoot":"","sources":["../../src/client/DeviceCodeClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,oBAAoB,EACpB,UAAU,EAEV,mBAAmB,EACnB,uBAAuB,EAc1B,MAAM,yBAAyB,CAAC;AAEjC;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;gBAChC,aAAa,EAAE,mBAAmB;IAI9C;;;;OAIG;IACU,YAAY,CACrB,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IA4BvC;;;OAGG;YACW,aAAa;IA+B3B;;;OAGG;IACI,0BAA0B,CAC7B,OAAO,EAAE,uBAAuB,GACjC,MAAM;IAYT;;;;;;;OAOG;YACW,sCAAsC;IAoCpD;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IA2BzB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAqCvB;;;;OAIG;YACW,0BAA0B;IAwFxC;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;CAqCjC"}

View File

@@ -0,0 +1,218 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { BaseClient, TimeUtils, ResponseHandler, UrlString, RequestParameterBuilder, createClientAuthError, ClientAuthErrorCodes, Constants, createAuthError, AuthErrorCodes, GrantType, StringUtils } from '@azure/msal-common/node';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* OAuth2.0 Device code client
* @public
*/
class DeviceCodeClient extends BaseClient {
constructor(configuration) {
super(configuration);
}
/**
* Gets device code from device code endpoint, calls back to with device code response, and
* polls token endpoint to exchange device code for tokens
* @param request - developer provided CommonDeviceCodeRequest
*/
async acquireToken(request) {
const deviceCodeResponse = await this.getDeviceCode(request);
request.deviceCodeCallback(deviceCodeResponse);
const reqTimestamp = TimeUtils.nowSeconds();
const response = await this.acquireTokenWithDeviceCode(request, deviceCodeResponse);
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response);
return responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request);
}
/**
* Creates device code request and executes http GET
* @param request - developer provided CommonDeviceCodeRequest
*/
async getDeviceCode(request) {
const queryParametersString = this.createExtraQueryParameters(request);
const endpoint = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString);
const queryString = this.createQueryString(request);
const headers = this.createTokenRequestHeaders();
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
return this.executePostRequestToDeviceCodeEndpoint(endpoint, queryString, headers, thumbprint, request.correlationId);
}
/**
* Creates query string for the device code request
* @param request - developer provided CommonDeviceCodeRequest
*/
createExtraQueryParameters(request) {
const parameterBuilder = new RequestParameterBuilder();
if (request.extraQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
}
return parameterBuilder.createQueryString();
}
/**
* Executes POST request to device code endpoint
* @param deviceCodeEndpoint - token endpoint
* @param queryString - string to be used in the body of the request
* @param headers - headers for the request
* @param thumbprint - unique request thumbprint
* @param correlationId - correlation id to be used in the request
*/
async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) {
const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message, }, } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, {
body: queryString,
headers: headers,
}, correlationId);
return {
userCode,
deviceCode,
verificationUri,
expiresIn,
interval,
message,
};
}
/**
* Create device code endpoint query parameters and returns string
* @param request - developer provided CommonDeviceCodeRequest
*/
createQueryString(request) {
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addClientId(this.config.authOptions.clientId);
if (request.extraQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
}
if (request.claims ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return parameterBuilder.createQueryString();
}
/**
* Breaks the polling with specific conditions
* @param deviceCodeExpirationTime - expiration time for the device code request
* @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime
* @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request
*/
continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) {
if (userSpecifiedCancelFlag) {
this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true");
throw createClientAuthError(ClientAuthErrorCodes.deviceCodePollingCancelled);
}
else if (userSpecifiedTimeout &&
userSpecifiedTimeout < deviceCodeExpirationTime &&
TimeUtils.nowSeconds() > userSpecifiedTimeout) {
this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`);
throw createClientAuthError(ClientAuthErrorCodes.userTimeoutReached);
}
else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {
if (userSpecifiedTimeout) {
this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`);
}
this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`);
throw createClientAuthError(ClientAuthErrorCodes.deviceCodeExpired);
}
return true;
}
/**
* Creates token request with device code response and polls token endpoint at interval set by the device code response
* @param request - developer provided CommonDeviceCodeRequest
* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
*/
async acquireTokenWithDeviceCode(request, deviceCodeResponse) {
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString);
const requestBody = this.createTokenRequestBody(request, deviceCodeResponse);
const headers = this.createTokenRequestHeaders();
const userSpecifiedTimeout = request.timeout
? TimeUtils.nowSeconds() + request.timeout
: undefined;
const deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;
const pollingIntervalMilli = deviceCodeResponse.interval * 1000;
/*
* Poll token endpoint while (device code is not expired AND operation has not been cancelled by
* setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli
*/
while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) {
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
if (response.body && response.body.error) {
// user authorization is pending. Sleep for polling interval and try again
if (response.body.error === Constants.AUTHORIZATION_PENDING) {
this.logger.info("Authorization pending. Continue polling.");
await TimeUtils.delay(pollingIntervalMilli);
}
else {
// for any other error, throw
this.logger.info("Unexpected error in polling from the server");
throw createAuthError(AuthErrorCodes.postRequestFailed, response.body.error);
}
}
else {
this.logger.verbose("Authorization completed successfully. Polling stopped.");
return response.body;
}
}
/*
* The above code should've thrown by this point, but to satisfy TypeScript,
* and in the rare case the conditionals in continuePolling() may not catch everything...
*/
this.logger.error("Polling stopped for unknown reasons.");
throw createClientAuthError(ClientAuthErrorCodes.deviceCodeUnknownError);
}
/**
* Creates query parameters and converts to string.
* @param request - developer provided CommonDeviceCodeRequest
* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
*/
createTokenRequestBody(request, deviceCodeResponse) {
const requestParameters = new RequestParameterBuilder();
requestParameters.addScopes(request.scopes);
requestParameters.addClientId(this.config.authOptions.clientId);
requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);
requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
requestParameters.addCorrelationId(correlationId);
requestParameters.addClientInfo();
requestParameters.addLibraryInfo(this.config.libraryInfo);
requestParameters.addApplicationTelemetry(this.config.telemetry.application);
requestParameters.addThrottling();
if (this.serverTelemetryManager) {
requestParameters.addServerTelemetry(this.serverTelemetryManager);
}
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
requestParameters.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return requestParameters.createQueryString();
}
}
export { DeviceCodeClient };
//# sourceMappingURL=DeviceCodeClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,40 @@
import { AuthenticationResult, IAppTokenProvider, Logger } from "@azure/msal-common/node";
import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
import { ClientCredentialRequest } from "../request/ClientCredentialRequest.js";
import { OnBehalfOfRequest } from "../request/OnBehalfOfRequest.js";
import { RefreshTokenRequest } from "../request/RefreshTokenRequest.js";
import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
import { UsernamePasswordRequest } from "../request/UsernamePasswordRequest.js";
import { TokenCache } from "../cache/TokenCache.js";
/**
* Interface for the ConfidentialClientApplication class defining the public API signatures
* @public
*/
export interface IConfidentialClientApplication {
/** Creates the URL of the authorization request */
getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
/** Acquires a token by exchanging the authorization code received from the first step of OAuth 2.0 Authorization Code Flow */
acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>;
/** Acquires a token silently when a user specifies the account the token is requested for */
acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult | null>;
/** Acquires a token by exchanging the refresh token provided for a new set of tokens */
acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null>;
/** Acquires tokens from the authority for the application (not for an end user) */
acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult | null>;
/** Acquires tokens from the authority for the application */
acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult | null>;
/** Acquires tokens with password grant by exchanging client applications username and password for credentials */
acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null>;
/** Gets the token cache for the application */
getTokenCache(): TokenCache;
/** Returns the logger instance */
getLogger(): Logger;
/** Replaces the default logger set in configurations with new Logger with new configurations */
setLogger(logger: Logger): void;
/** Clear the cache */
clearCache(): void;
/** This extensibility point is meant for Azure SDK to enhance Managed Identity support */
SetAppTokenProvider(provider: IAppTokenProvider): void;
}
//# sourceMappingURL=IConfidentialClientApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IConfidentialCl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kH;IAClH,8BAA8B,CAC1B,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAExC,+CAA+C;IAC/C,aAAa,IAAI,UAAU,CAAC;IAE5B,kCAAkC;IAClC,SAAS,IAAI,MAAM,CAAC;IAEpB,gGAAgG;IAChG,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEhC,sBAAsB;IACtB,UAAU,IAAI,IAAI,CAAC;IAEnB,0FAA0F;IAC1F,mBAAmB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC1D"}

View File

@@ -0,0 +1,43 @@
import { AccountInfo, AuthenticationResult, Logger } from "@azure/msal-common/node";
import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
import { DeviceCodeRequest } from "../request/DeviceCodeRequest.js";
import { RefreshTokenRequest } from "../request/RefreshTokenRequest.js";
import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
import { UsernamePasswordRequest } from "../request/UsernamePasswordRequest.js";
import { TokenCache } from "../cache/TokenCache.js";
import { InteractiveRequest } from "../request/InteractiveRequest.js";
import { SignOutRequest } from "../request/SignOutRequest.js";
/**
* Interface for the PublicClientApplication class defining the public API signatures
* @public
*/
export interface IPublicClientApplication {
/** Creates the URL of the authorization request */
getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>;
/** Acquires a token by exchanging the authorization code received from the first step of OAuth 2.0 Authorization Code Flow */
acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>;
/** Acquires a token interactively */
acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult>;
/** Acquires a token silently when a user specifies the account the token is requested for */
acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>;
/** Acquires a token by exchanging the refresh token provided for a new set of tokens */
acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult | null>;
/** Acquires a token from the authority using OAuth2.0 device code flow */
acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null>;
/** Acquires tokens with password grant by exchanging client applications username and password for credentials */
acquireTokenByUsernamePassword(request: UsernamePasswordRequest): Promise<AuthenticationResult | null>;
/** Gets the token cache for the application */
getTokenCache(): TokenCache;
/** Returns the logger instance */
getLogger(): Logger;
/** Replaces the default logger set in configurations with new Logger with new configurations */
setLogger(logger: Logger): void;
/** Clear the cache */
clearCache(): void;
/** Gets all cached accounts */
getAllAccounts(): Promise<AccountInfo[]>;
/** Removes cache artifacts associated with the given account */
signOut(request: SignOutRequest): Promise<void>;
}
//# sourceMappingURL=IPublicClientApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"IPublicClientApplication.d.ts","sourceRoot":"","sources":["../../src/client/IPublicClientApplication.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,WAAW,EACX,oBAAoB,EACpB,MAAM,EACT,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,wCAAwC,CAAC;AAClF,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACrC,mDAAmD;IACnD,cAAc,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAElE,8HAA8H;IAC9H,kBAAkB,CACd,OAAO,EAAE,wBAAwB,GAClC,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAEjC,qCAAqC;IACrC,uBAAuB,CACnB,OAAO,EAAE,kBAAkB,GAC5B,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAEjC,6FAA6F;IAC7F,kBAAkB,CACd,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAEjC,wFAAwF;IACxF,0BAA0B,CACtB,OAAO,EAAE,mBAAmB,GAC7B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAExC,0EAA0E;IAC1E,wBAAwB,CACpB,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAExC,kHAAkH;IAClH,8BAA8B,CAC1B,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAExC,+CAA+C;IAC/C,aAAa,IAAI,UAAU,CAAC;IAE5B,kCAAkC;IAClC,SAAS,IAAI,MAAM,CAAC;IAEpB,gGAAgG;IAChG,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEhC,sBAAsB;IACtB,UAAU,IAAI,IAAI,CAAC;IAEnB,+BAA+B;IAC/B,cAAc,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAEzC,gEAAgE;IAChE,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnD"}

View File

@@ -0,0 +1,31 @@
import { AuthenticationResult } from "@azure/msal-common/node";
import { ManagedIdentityConfiguration } from "../config/Configuration.js";
import { ManagedIdentityRequestParams } from "../request/ManagedIdentityRequestParams.js";
import { ManagedIdentitySourceNames } from "../utils/Constants.js";
/**
* Class to initialize a managed identity and identify the service
* @public
*/
export declare class ManagedIdentityApplication {
private config;
private logger;
private static nodeStorage?;
private networkClient;
private cryptoProvider;
private fakeAuthority;
private fakeClientCredentialClient;
private managedIdentityClient;
constructor(configuration?: ManagedIdentityConfiguration);
/**
* Acquire an access token from the cache or the managed identity
* @param managedIdentityRequest - the ManagedIdentityRequestParams object passed in by the developer
* @returns the access token
*/
acquireToken(managedIdentityRequestParams: ManagedIdentityRequestParams): Promise<AuthenticationResult>;
/**
* Determine the Managed Identity Source based on available environment variables. This API is consumed by Azure Identity SDK.
* @returns ManagedIdentitySourceNames - The Managed Identity source's name
*/
getManagedIdentitySource(): ManagedIdentitySourceNames;
}
//# sourceMappingURL=ManagedIdentityApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ManagedIdentityApplication.d.ts","sourceRoot":"","sources":["../../src/client/ManagedIdentityApplication.ts"],"names":[],"mappings":"AAKA,OAAO,EAYH,oBAAoB,EAGvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,4BAA4B,EAG/B,MAAM,4BAA4B,CAAC;AAMpC,OAAO,EAAE,4BAA4B,EAAE,MAAM,4CAA4C,CAAC;AAE1F,OAAO,EAEH,0BAA0B,EAC7B,MAAM,uBAAuB,CAAC;AAE/B;;;GAGG;AACH,qBAAa,0BAA0B;IACnC,OAAO,CAAC,MAAM,CAAmC;IAEjD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAc;IACzC,OAAO,CAAC,aAAa,CAAiB;IACtC,OAAO,CAAC,cAAc,CAAiB;IAGvC,OAAO,CAAC,aAAa,CAAY;IAGjC,OAAO,CAAC,0BAA0B,CAAyB;IAE3D,OAAO,CAAC,qBAAqB,CAAwB;gBAEzC,aAAa,CAAC,EAAE,4BAA4B;IA2DxD;;;;OAIG;IACU,YAAY,CACrB,4BAA4B,EAAE,4BAA4B,GAC3D,OAAO,CAAC,oBAAoB,CAAC;IAqEhC;;;OAGG;IACI,wBAAwB,IAAI,0BAA0B;CAMhE"}

View File

@@ -0,0 +1,99 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { Logger, DEFAULT_CRYPTO_IMPLEMENTATION, Authority, createClientConfigurationError, ClientConfigurationErrorCodes, CacheOutcome, Constants, ProtocolMode } from '@azure/msal-common/node';
import { buildManagedIdentityConfiguration } from '../config/Configuration.mjs';
import { name, version } from '../packageMetadata.mjs';
import { CryptoProvider } from '../crypto/CryptoProvider.mjs';
import { ClientCredentialClient } from './ClientCredentialClient.mjs';
import { ManagedIdentityClient } from './ManagedIdentityClient.mjs';
import { NodeStorage } from '../cache/NodeStorage.mjs';
import { DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY } from '../utils/Constants.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Class to initialize a managed identity and identify the service
* @public
*/
class ManagedIdentityApplication {
constructor(configuration) {
// undefined config means the managed identity is system-assigned
this.config = buildManagedIdentityConfiguration(configuration || {});
this.logger = new Logger(this.config.system.loggerOptions, name, version);
const fakeStatusAuthorityOptions = {
canonicalAuthority: Constants.DEFAULT_AUTHORITY,
};
if (!ManagedIdentityApplication.nodeStorage) {
ManagedIdentityApplication.nodeStorage = new NodeStorage(this.logger, this.config.managedIdentityId.id, DEFAULT_CRYPTO_IMPLEMENTATION, fakeStatusAuthorityOptions);
}
this.networkClient = this.config.system.networkClient;
this.cryptoProvider = new CryptoProvider();
const fakeAuthorityOptions = {
protocolMode: ProtocolMode.AAD,
knownAuthorities: [DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY],
cloudDiscoveryMetadata: "",
authorityMetadata: "",
};
this.fakeAuthority = new Authority(DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, this.networkClient, ManagedIdentityApplication.nodeStorage, fakeAuthorityOptions, this.logger, this.cryptoProvider.createNewGuid(), // correlationID
undefined, true);
this.fakeClientCredentialClient = new ClientCredentialClient({
authOptions: {
clientId: this.config.managedIdentityId.id,
authority: this.fakeAuthority,
},
});
this.managedIdentityClient = new ManagedIdentityClient(this.logger, ManagedIdentityApplication.nodeStorage, this.networkClient, this.cryptoProvider);
}
/**
* Acquire an access token from the cache or the managed identity
* @param managedIdentityRequest - the ManagedIdentityRequestParams object passed in by the developer
* @returns the access token
*/
async acquireToken(managedIdentityRequestParams) {
if (!managedIdentityRequestParams.resource) {
throw createClientConfigurationError(ClientConfigurationErrorCodes.urlEmptyError);
}
const managedIdentityRequest = {
forceRefresh: managedIdentityRequestParams.forceRefresh,
resource: managedIdentityRequestParams.resource.replace("/.default", ""),
scopes: [
managedIdentityRequestParams.resource.replace("/.default", ""),
],
authority: this.fakeAuthority.canonicalAuthority,
correlationId: this.cryptoProvider.createNewGuid(),
};
if (managedIdentityRequestParams.claims ||
managedIdentityRequest.forceRefresh) {
// make a network call to the managed identity source
return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
}
const [cachedAuthenticationResult, lastCacheOutcome] = await this.fakeClientCredentialClient.getCachedAuthenticationResult(managedIdentityRequest, this.config, this.cryptoProvider, this.fakeAuthority, ManagedIdentityApplication.nodeStorage);
if (cachedAuthenticationResult) {
// if the token is not expired but must be refreshed; get a new one in the background
if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");
// make a network call to the managed identity source; refresh the access token in the background
const refreshAccessToken = true;
await this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority, refreshAccessToken);
}
return cachedAuthenticationResult;
}
else {
// make a network call to the managed identity source
return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
}
}
/**
* Determine the Managed Identity Source based on available environment variables. This API is consumed by Azure Identity SDK.
* @returns ManagedIdentitySourceNames - The Managed Identity source's name
*/
getManagedIdentitySource() {
return (ManagedIdentityClient.sourceName ||
this.managedIdentityClient.getManagedIdentitySource());
}
}
export { ManagedIdentityApplication };
//# sourceMappingURL=ManagedIdentityApplication.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ManagedIdentityApplication.mjs","sources":["../../src/client/ManagedIdentityApplication.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;;;;;;AAAA;;;AAGG;AAmCH;;;AAGG;MACU,0BAA0B,CAAA;AAgBnC,IAAA,WAAA,CAAY,aAA4C,EAAA;;QAEpD,IAAI,CAAC,MAAM,GAAG,iCAAiC,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC;AAErE,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CACpB,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,EAChC,IAAI,EACJ,OAAO,CACV,CAAC;AAEF,QAAA,MAAM,0BAA0B,GAA2B;YACvD,kBAAkB,EAAE,SAAS,CAAC,iBAAiB;SAClD,CAAC;AAEF,QAAA,IAAI,CAAC,0BAA0B,CAAC,WAAW,EAAE;YACzC,0BAA0B,CAAC,WAAW,GAAG,IAAI,WAAW,CACpD,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC,EAAE,EAChC,6BAA6B,EAC7B,0BAA0B,CAC7B,CAAC;AACL,SAAA;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC;AAEtD,QAAA,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC;AAE3C,QAAA,MAAM,oBAAoB,GAAqB;YAC3C,YAAY,EAAE,YAAY,CAAC,GAAG;YAC9B,gBAAgB,EAAE,CAAC,sCAAsC,CAAC;AAC1D,YAAA,sBAAsB,EAAE,EAAE;AAC1B,YAAA,iBAAiB,EAAE,EAAE;SACxB,CAAC;AACF,QAAA,IAAI,CAAC,aAAa,GAAG,IAAI,SAAS,CAC9B,sCAAsC,EACtC,IAAI,CAAC,aAAa,EA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B,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAC7B,IAAI,CAAC,aAAa,CACrB,CAAC;AACL,SAAA;AAED,QAAA,MAAM,CAAC,0BAA0B,EAAE,gBAAgB,CAAC,GAChD,MAAM,IAAI,CAAC,0BAA0B,CAAC,6BAA6B,CAC/D,sBAAsB,EACtB,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,cAAc,EACnB,IAAI,CAAC,aAAa,EAClB,0BAA0B,CAAC,WAA0B,CACxD,CAAC;AAEN,QAAA,IAAI,0BAA0B,EAAE;;AAE5B,YAAA,IAAI,gBAAgB,KAAK,YAAY,CAAC,qBAAqB,EAAE;AACzD,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CACZ,8JAA8J,CACjK,CAAC;;gBAGF,MAAM,kBAAkB,GAAG,IAAI,CAAC;gBAChC,MAAM,IAAI,CAAC,qBAAqB,CAAC,+BAA+B,CAC5D,sBAAsB,EACtB,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAC7B,IAAI,CAAC,aAAa,EAClB,kBAAkB,CACrB,CAAC;AACL,aAAA;AAED,YAAA,OAAO,0BAA0B,CAAC;AACrC,SAAA;AAAM,aAAA;;AAEH,YAAA,OAAO,IAAI,CAAC,qBAAqB,CAAC,+BAA+B,CAC7D,sBAAsB,EACtB,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAC7B,IAAI,CAAC,aAAa,CACrB,CAAC;AACL,SAAA;KACJ;AAED;;;AAGG;IACI,wBAAwB,GAAA;QAC3B,QACI,qBAAqB,CAAC,UAAU;AAChC,YAAA,IAAI,CAAC,qBAAqB,CAAC,wBAAwB,EAAE,EACvD;KACL;AACJ;;;;"}

View File

@@ -0,0 +1,28 @@
import { Authority, INetworkModule, Logger, AuthenticationResult } from "@azure/msal-common/node";
import { CryptoProvider } from "../crypto/CryptoProvider.js";
import { ManagedIdentityRequest } from "../request/ManagedIdentityRequest.js";
import { ManagedIdentityId } from "../config/ManagedIdentityId.js";
import { NodeStorage } from "../cache/NodeStorage.js";
import { ManagedIdentitySourceNames } from "../utils/Constants.js";
export declare class ManagedIdentityClient {
private logger;
private nodeStorage;
private networkClient;
private cryptoProvider;
private static identitySource?;
static sourceName?: ManagedIdentitySourceNames;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider);
sendManagedIdentityTokenRequest(managedIdentityRequest: ManagedIdentityRequest, managedIdentityId: ManagedIdentityId, fakeAuthority: Authority, refreshAccessToken?: boolean): Promise<AuthenticationResult>;
private allEnvironmentVariablesAreDefined;
/**
* Determine the Managed Identity Source based on available environment variables. This API is consumed by ManagedIdentityApplication's getManagedIdentitySource.
* @returns ManagedIdentitySourceNames - The Managed Identity source's name
*/
getManagedIdentitySource(): ManagedIdentitySourceNames;
/**
* Tries to create a managed identity source for all sources
* @returns the managed identity Source
*/
private selectManagedIdentitySource;
}
//# sourceMappingURL=ManagedIdentityClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ManagedIdentityClient.d.ts","sourceRoot":"","sources":["../../src/client/ManagedIdentityClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,SAAS,EACT,cAAc,EACd,MAAM,EACN,oBAAoB,EACvB,MAAM,yBAAyB,CAAC;AAMjC,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAK7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAMnE,qBAAa,qBAAqB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,aAAa,CAAiB;IACtC,OAAO,CAAC,cAAc,CAAiB;IAEvC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAA4B;IAC1D,OAAc,UAAU,CAAC,EAAE,0BAA0B,CAAC;gBAGlD,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc;IAQrB,+BAA+B,CACxC,sBAAsB,EAAE,sBAAsB,EAC9C,iBAAiB,EAAE,iBAAiB,EACpC,aAAa,EAAE,SAAS,EACxB,kBAAkB,CAAC,EAAE,OAAO,GAC7B,OAAO,CAAC,oBAAoB,CAAC;IAoBhC,OAAO,CAAC,iCAAiC;IAUzC;;;OAGG;IACI,wBAAwB,IAAI,0BAA0B;IAuB7D;;;OAGG;IACH,OAAO,CAAC,2BAA2B;CA2CtC"}

View File

@@ -0,0 +1,74 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { AppService } from './ManagedIdentitySources/AppService.mjs';
import { AzureArc } from './ManagedIdentitySources/AzureArc.mjs';
import { CloudShell } from './ManagedIdentitySources/CloudShell.mjs';
import { Imds } from './ManagedIdentitySources/Imds.mjs';
import { ServiceFabric } from './ManagedIdentitySources/ServiceFabric.mjs';
import { createManagedIdentityError } from '../error/ManagedIdentityError.mjs';
import { ManagedIdentitySourceNames } from '../utils/Constants.mjs';
import { unableToCreateSource } from '../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Class to initialize a managed identity and identify the service.
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ManagedIdentityClient.cs
*/
class ManagedIdentityClient {
constructor(logger, nodeStorage, networkClient, cryptoProvider) {
this.logger = logger;
this.nodeStorage = nodeStorage;
this.networkClient = networkClient;
this.cryptoProvider = cryptoProvider;
}
async sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
if (!ManagedIdentityClient.identitySource) {
ManagedIdentityClient.identitySource =
this.selectManagedIdentitySource(this.logger, this.nodeStorage, this.networkClient, this.cryptoProvider, managedIdentityId);
}
return ManagedIdentityClient.identitySource.acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken);
}
allEnvironmentVariablesAreDefined(environmentVariables) {
return Object.values(environmentVariables).every((environmentVariable) => {
return environmentVariable !== undefined;
});
}
/**
* Determine the Managed Identity Source based on available environment variables. This API is consumed by ManagedIdentityApplication's getManagedIdentitySource.
* @returns ManagedIdentitySourceNames - The Managed Identity source's name
*/
getManagedIdentitySource() {
ManagedIdentityClient.sourceName =
this.allEnvironmentVariablesAreDefined(ServiceFabric.getEnvironmentVariables())
? ManagedIdentitySourceNames.SERVICE_FABRIC
: this.allEnvironmentVariablesAreDefined(AppService.getEnvironmentVariables())
? ManagedIdentitySourceNames.APP_SERVICE
: this.allEnvironmentVariablesAreDefined(CloudShell.getEnvironmentVariables())
? ManagedIdentitySourceNames.CLOUD_SHELL
: this.allEnvironmentVariablesAreDefined(AzureArc.getEnvironmentVariables())
? ManagedIdentitySourceNames.AZURE_ARC
: ManagedIdentitySourceNames.DEFAULT_TO_IMDS;
return ManagedIdentityClient.sourceName;
}
/**
* Tries to create a managed identity source for all sources
* @returns the managed identity Source
*/
selectManagedIdentitySource(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) {
const source = ServiceFabric.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) ||
AppService.tryCreate(logger, nodeStorage, networkClient, cryptoProvider) ||
CloudShell.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) ||
AzureArc.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) ||
Imds.tryCreate(logger, nodeStorage, networkClient, cryptoProvider);
if (!source) {
throw createManagedIdentityError(unableToCreateSource);
}
return source;
}
}
export { ManagedIdentityClient };
//# sourceMappingURL=ManagedIdentityClient.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ManagedIdentityClient.mjs","sources":["../../src/client/ManagedIdent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zC,IAAI,CAAC,iCAAiC,CAClC,UAAU,CAAC,uBAAuB,EAAE,CACvC;sBACD,0BAA0B,CAAC,WAAW;sBACtC,IAAI,CAAC,iCAAiC,CAClC,UAAU,CAAC,uBAAuB,EAAE,CACvC;0BACD,0BAA0B,CAAC,WAAW;0BACtC,IAAI,CAAC,iCAAiC,CAClC,QAAQ,CAAC,uBAAuB,EAAE,CACrC;8BACD,0BAA0B,CAAC,SAAS;AACtC,8BAAE,0BAA0B,CAAC,eAAe,CAAC;QAErD,OAAO,qBAAqB,CAAC,UAAU,CAAC;KAC3C;AAED;;;AAGG;IACK,2BAA2B,CAC/B,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAC9B,iBAAoC,EAAA;AAEpC,QAAA,MAAM,MAAM,GACR,aAAa,CAAC,SAAS,CACnB,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,iBAAiB,CACpB;YACD,UAAU,CAAC,SAAS,CAChB,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,CACjB;AACD,YAAA,UAAU,CAAC,SAAS,CAChB,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,iBAAiB,CACpB;AACD,YAAA,QAAQ,CAAC,SAAS,CACd,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,iBAAiB,CACpB;YACD,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;QACvE,IAAI,CAAC,MAAM,EAAE;AACT,YAAA,MAAM,0BAA0B,CAC5BA,oBAA8C,CACjD,CAAC;AACL,SAAA;AACD,QAAA,OAAO,MAAM,CAAC;KACjB;AACJ;;;;"}

View File

@@ -0,0 +1,18 @@
import { INetworkModule, Logger } from "@azure/msal-common/node";
import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs
*/
export declare class AppService extends BaseManagedIdentitySource {
private identityEndpoint;
private identityHeader;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, identityEndpoint: string, identityHeader: string);
static getEnvironmentVariables(): Array<string | undefined>;
static tryCreate(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider): AppService | null;
createRequest(resource: string, managedIdentityId: ManagedIdentityId): ManagedIdentityRequestParameters;
}
//# sourceMappingURL=AppService.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AppService.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/AppService.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAU3E,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAChE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAKzD;;GAEG;AACH,qBAAa,UAAW,SAAQ,yBAAyB;IACrD,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,cAAc,CAAS;gBAG3B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,gBAAgB,EAAE,MAAM,EACxB,cAAc,EAAE,MAAM;WAQZ,uBAAuB,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC;WAapD,SAAS,CACnB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,GAC/B,UAAU,GAAG,IAAI;IAkCb,aAAa,CAChB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,iBAAiB,GACrC,gCAAgC;CA4BtC"}

View File

@@ -0,0 +1,54 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, APP_SERVICE_SECRET_HEADER_NAME, API_VERSION_QUERY_PARAMETER_NAME, RESOURCE_BODY_OR_QUERY_PARAMETER_NAME, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity
const APP_SERVICE_MSI_API_VERSION = "2019-08-01";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs
*/
class AppService extends BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint, identityHeader) {
super(logger, nodeStorage, networkClient, cryptoProvider);
this.identityEndpoint = identityEndpoint;
this.identityHeader = identityHeader;
}
static getEnvironmentVariables() {
const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
return [identityEndpoint, identityHeader];
}
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider) {
const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables();
// if either of the identity endpoint or identity header variables are undefined, this MSI provider is unavailable.
if (!identityEndpoint || !identityHeader) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`);
return null;
}
const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`);
return new AppService(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint, identityHeader);
}
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[APP_SERVICE_SECRET_HEADER_NAME] = this.identityHeader;
request.queryParameters[API_VERSION_QUERY_PARAMETER_NAME] =
APP_SERVICE_MSI_API_VERSION;
request.queryParameters[RESOURCE_BODY_OR_QUERY_PARAMETER_NAME] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { AppService };
//# sourceMappingURL=AppService.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AppService.mjs","sources":["../../../src/client/ManagedIdentitySources/AppService.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;AAAA;;;AAGG;AAkBH;AACA,MAAM,2BAA2B,GAAW,YAAY,CAAC;AAEzD;;AAEG;AACG,MAAO,UAAW,SAAQ,yBAAyB,CAAA;IAIrD,WACI,CAAA,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cA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P,CAAC;AAEF,QAAA,OAAO,IAAI,UAAU,CACjB,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,cAAc,CACjB,CAAC;KACL;IAEM,aAAa,CAChB,QAAgB,EAChB,iBAAoC,EAAA;AAEpC,QAAA,MAAM,OAAO,GACT,IAAI,gCAAgC,CAChC,UAAU,CAAC,GAAG,EACd,IAAI,CAAC,gBAAgB,CACxB,CAAC;QAEN,OAAO,CAAC,OAAO,CAAC,8BAA8B,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC;AAEtE,QAAA,OAAO,CAAC,eAAe,CAAC,gCAAgC,CAAC;AACrD,YAAA,2BAA2B,CAAC;AAChC,QAAA,OAAO,CAAC,eAAe,CAAC,qCAAqC,CAAC;AAC1D,YAAA,QAAQ,CAAC;AAEb,QAAA,IACI,iBAAiB,CAAC,MAAM,KAAK,qBAAqB,CAAC,eAAe,EACpE;AACE,YAAA,OAAO,CAAC,eAAe,CACnB,IAAI,CAAC,iDAAiD,CAClD,iBAAiB,CAAC,MAAM,CAC3B,CACJ,GAAG,iBAAiB,CAAC,EAAE,CAAC;AAC5B,SAAA;;AAID,QAAA,OAAO,OAAO,CAAC;KAClB;AACJ;;;;"}

View File

@@ -0,0 +1,28 @@
import { INetworkModule, NetworkResponse, NetworkRequestOptions, Logger, ServerAuthorizationTokenResponse } from "@azure/msal-common/node";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
import { ManagedIdentityTokenResponse } from "../../response/ManagedIdentityTokenResponse.js";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
export declare const ARC_API_VERSION: string;
export declare const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT: string;
type FilePathMap = {
win32: string;
linux: string;
};
export declare const SUPPORTED_AZURE_ARC_PLATFORMS: FilePathMap;
export declare const AZURE_ARC_FILE_DETECTION: FilePathMap;
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs
*/
export declare class AzureArc extends BaseManagedIdentitySource {
private identityEndpoint;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, identityEndpoint: string);
static getEnvironmentVariables(): Array<string | undefined>;
static tryCreate(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, managedIdentityId: ManagedIdentityId): AzureArc | null;
createRequest(resource: string): ManagedIdentityRequestParameters;
getServerTokenResponseAsync(originalResponse: NetworkResponse<ManagedIdentityTokenResponse>, networkClient: INetworkModule, networkRequest: ManagedIdentityRequestParameters, networkRequestOptions: NetworkRequestOptions): Promise<ServerAuthorizationTokenResponse>;
}
export {};
//# sourceMappingURL=AzureArc.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AzureArc.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/AzureArc.ts"],"names":[],"mappings":"AAKA,OAAO,EAKH,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,MAAM,EACN,gCAAgC,EACnC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAgBhE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAOzD,OAAO,EAAE,4BAA4B,EAAE,MAAM,gDAAgD,CAAC;AAC9F,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAGtE,eAAO,MAAM,eAAe,EAAE,MAAqB,CAAC;AACpD,eAAO,MAAM,mCAAmC,EAAE,MACS,CAAC;AAG5D,KAAK,WAAW,GAAG;IACf,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,6BAA6B,EAAE,WAG3C,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,WAGtC,CAAC;AAEF;;GAEG;AACH,qBAAa,QAAS,SAAQ,yBAAyB;IACnD,OAAO,CAAC,gBAAgB,CAAS;gBAG7B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,gBAAgB,EAAE,MAAM;WAOd,uBAAuB,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC;WAoCpD,SAAS,CACnB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,iBAAiB,EAAE,iBAAiB,GACrC,QAAQ,GAAG,IAAI;IA8DX,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,gCAAgC;IAmB3D,2BAA2B,CACpC,gBAAgB,EAAE,eAAe,CAAC,4BAA4B,CAAC,EAC/D,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,gCAAgC,EAChD,qBAAqB,EAAE,qBAAqB,GAC7C,OAAO,CAAC,gCAAgC,CAAC;CA0G/C"}

View File

@@ -0,0 +1,167 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { HttpStatus, AuthError, createClientAuthError, ClientAuthErrorCodes } from '@azure/msal-common/node';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod, METADATA_HEADER_NAME, API_VERSION_QUERY_PARAMETER_NAME, RESOURCE_BODY_OR_QUERY_PARAMETER_NAME, AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES, AUTHORIZATION_HEADER_NAME } from '../../utils/Constants.mjs';
import { accessSync, constants, statSync, readFileSync } from 'fs';
import path from 'path';
import { unableToCreateAzureArc, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat, platformNotSupported, invalidFileExtension, invalidFilePath, unableToReadSecretFile, invalidSecret } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const ARC_API_VERSION = "2019-11-01";
const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token";
const HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists";
const SUPPORTED_AZURE_ARC_PLATFORMS = {
win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`,
linux: "/var/opt/azcmagent/tokens/",
};
const AZURE_ARC_FILE_DETECTION = {
win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`,
linux: "/opt/azcmagent/bin/himds",
};
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs
*/
class AzureArc extends BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider);
this.identityEndpoint = identityEndpoint;
}
static getEnvironmentVariables() {
let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT];
// if either of the identity or imds endpoints are undefined, check if the himds executable exists
if (!identityEndpoint || !imdsEndpoint) {
// get the expected Windows or Linux file path of the himds executable
const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform];
try {
/*
* check if the himds executable exists and its permissions allow it to be read
* returns undefined if true, throws an error otherwise
*/
accessSync(fileDetectionPath, constants.F_OK | constants.R_OK);
identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT;
imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING;
}
catch (err) {
/*
* do nothing
* accessSync returns undefined on success, and throws an error on failure
*/
}
}
return [identityEndpoint, imdsEndpoint];
}
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) {
const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables();
// if either of the identity or imds endpoints are undefined (even after himds file detection)
if (!identityEndpoint || !imdsEndpoint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`);
return null;
}
// check if the imds endpoint is set to the default for file detection
if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`);
}
else {
// otherwise, both the identity and imds endpoints are defined without file detection; validate them
const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
// remove trailing slash
validatedIdentityEndpoint.endsWith("/")
? validatedIdentityEndpoint.slice(0, -1)
: validatedIdentityEndpoint;
AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`);
}
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
throw createManagedIdentityError(unableToCreateAzureArc);
}
return new AzureArc(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint);
}
createRequest(resource) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint.replace("localhost", "127.0.0.1"));
request.headers[METADATA_HEADER_NAME] = "true";
request.queryParameters[API_VERSION_QUERY_PARAMETER_NAME] =
ARC_API_VERSION;
request.queryParameters[RESOURCE_BODY_OR_QUERY_PARAMETER_NAME] =
resource;
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) {
let retryResponse;
if (originalResponse.status === HttpStatus.UNAUTHORIZED) {
const wwwAuthHeader = originalResponse.headers["www-authenticate"];
if (!wwwAuthHeader) {
throw createManagedIdentityError(wwwAuthenticateHeaderMissing);
}
if (!wwwAuthHeader.includes("Basic realm=")) {
throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat);
}
const secretFilePath = wwwAuthHeader.split("Basic realm=")[1];
// throw an error if the managed identity application is not being run on Windows or Linux
if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) {
throw createManagedIdentityError(platformNotSupported);
}
// get the expected Windows or Linux file path
const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform];
// throw an error if the file in the file path is not a .key file
const fileName = path.basename(secretFilePath);
if (!fileName.endsWith(".key")) {
throw createManagedIdentityError(invalidFileExtension);
}
/*
* throw an error if the file path from the www-authenticate header does not match the
* expected file path for the platform (Windows or Linux) the managed identity application
* is running on
*/
if (expectedSecretFilePath + fileName !== secretFilePath) {
throw createManagedIdentityError(invalidFilePath);
}
let secretFileSize;
// attempt to get the secret file's size, in bytes
try {
secretFileSize = await statSync(secretFilePath).size;
}
catch (e) {
throw createManagedIdentityError(unableToReadSecretFile);
}
// throw an error if the secret file's size is greater than 4096 bytes
if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) {
throw createManagedIdentityError(invalidSecret);
}
// attempt to read the contents of the secret file
let secret;
try {
secret = readFileSync(secretFilePath, "utf-8");
}
catch (e) {
throw createManagedIdentityError(unableToReadSecretFile);
}
const authHeaderValue = `Basic ${secret}`;
this.logger.info(`[Managed Identity] Adding authorization header to the request.`);
networkRequest.headers[AUTHORIZATION_HEADER_NAME] = authHeaderValue;
try {
retryResponse =
await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
}
catch (error) {
if (error instanceof AuthError) {
throw error;
}
else {
throw createClientAuthError(ClientAuthErrorCodes.networkError);
}
}
}
return this.getServerTokenResponse(retryResponse || originalResponse);
}
}
export { ARC_API_VERSION, AZURE_ARC_FILE_DETECTION, AzureArc, DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT, SUPPORTED_AZURE_ARC_PLATFORMS };
//# sourceMappingURL=AzureArc.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import { Authority, INetworkModule, Logger, NetworkRequestOptions, NetworkResponse, ServerAuthorizationTokenResponse, AuthenticationResult } from "@azure/msal-common/node";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
import { ManagedIdentityRequest } from "../../request/ManagedIdentityRequest.js";
import { ManagedIdentityIdType } from "../../utils/Constants.js";
import { ManagedIdentityTokenResponse } from "../../response/ManagedIdentityTokenResponse.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
/**
* Managed Identity User Assigned Id Query Parameter Names
*/
export declare const ManagedIdentityUserAssignedIdQueryParameterNames: {
readonly MANAGED_IDENTITY_CLIENT_ID: "client_id";
readonly MANAGED_IDENTITY_OBJECT_ID: "object_id";
readonly MANAGED_IDENTITY_RESOURCE_ID: "mi_res_id";
};
export type ManagedIdentityUserAssignedIdQueryParameterNames = (typeof ManagedIdentityUserAssignedIdQueryParameterNames)[keyof typeof ManagedIdentityUserAssignedIdQueryParameterNames];
export declare abstract class BaseManagedIdentitySource {
protected logger: Logger;
private nodeStorage;
private networkClient;
private cryptoProvider;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider);
abstract createRequest(request: string, managedIdentityId: ManagedIdentityId): ManagedIdentityRequestParameters;
getServerTokenResponseAsync(response: NetworkResponse<ManagedIdentityTokenResponse>, _networkClient: INetworkModule, _networkRequest: ManagedIdentityRequestParameters, _networkRequestOptions: NetworkRequestOptions): Promise<ServerAuthorizationTokenResponse>;
getServerTokenResponse(response: NetworkResponse<ManagedIdentityTokenResponse>): ServerAuthorizationTokenResponse;
acquireTokenWithManagedIdentity(managedIdentityRequest: ManagedIdentityRequest, managedIdentityId: ManagedIdentityId, fakeAuthority: Authority, refreshAccessToken?: boolean): Promise<AuthenticationResult>;
getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType: ManagedIdentityIdType): string;
static getValidatedEnvVariableUrlString: (envVariableStringName: string, envVariable: string, sourceName: string, logger: Logger) => string;
}
//# sourceMappingURL=BaseManagedIdentitySource.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BaseManagedIdentitySource.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/BaseManagedIdentitySource.ts"],"names":[],"mappings":"AAKA,OAAO,EAEH,SAAS,EAIT,cAAc,EACd,MAAM,EACN,qBAAqB,EACrB,eAAe,EAEf,gCAAgC,EAGhC,oBAAoB,EAEvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MA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B,EAAE,qBAAqB,GAC7C,MAAM;IA0BT,OAAc,gCAAgC,0BACnB,MAAM,eAChB,MAAM,cACP,MAAM,UACV,MAAM,KACf,MAAM,CAeP;CACL"}

View File

@@ -0,0 +1,132 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { TimeUtils, HeaderNames, Constants, AuthError, createClientAuthError, ClientAuthErrorCodes, ResponseHandler, UrlString } from '@azure/msal-common/node';
import { HttpMethod, ManagedIdentityIdType } from '../../utils/Constants.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { invalidManagedIdentityIdType, MsiEnvironmentVariableUrlMalformedErrorCodes } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Managed Identity User Assigned Id Query Parameter Names
*/
const ManagedIdentityUserAssignedIdQueryParameterNames = {
MANAGED_IDENTITY_CLIENT_ID: "client_id",
MANAGED_IDENTITY_OBJECT_ID: "object_id",
MANAGED_IDENTITY_RESOURCE_ID: "mi_res_id",
};
class BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider) {
this.logger = logger;
this.nodeStorage = nodeStorage;
this.networkClient = networkClient;
this.cryptoProvider = cryptoProvider;
}
async getServerTokenResponseAsync(response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkClient,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkRequest,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_networkRequestOptions) {
return this.getServerTokenResponse(response);
}
getServerTokenResponse(response) {
let refreshIn, expiresIn;
if (response.body.expires_on) {
expiresIn = response.body.expires_on - TimeUtils.nowSeconds();
// compute refresh_in as 1/2 of expires_in, but only if expires_in > 2h
if (expiresIn > 2 * 3600) {
refreshIn = expiresIn / 2;
}
}
const serverTokenResponse = {
status: response.status,
// success
access_token: response.body.access_token,
expires_in: expiresIn,
scope: response.body.resource,
token_type: response.body.token_type,
refresh_in: refreshIn,
// error
correlation_id: response.body.correlation_id || response.body.correlationId,
error: typeof response.body.error === "string"
? response.body.error
: response.body.error?.code,
error_description: response.body.message ||
(typeof response.body.error === "string"
? response.body.error_description
: response.body.error?.message),
error_codes: response.body.error_codes,
timestamp: response.body.timestamp,
trace_id: response.body.trace_id,
};
return serverTokenResponse;
}
async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId);
const headers = networkRequest.headers;
headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;
const networkRequestOptions = { headers };
if (Object.keys(networkRequest.bodyParameters).length) {
networkRequestOptions.body =
networkRequest.computeParametersBodyString();
}
const reqTimestamp = TimeUtils.nowSeconds();
let response;
try {
// Sources that send POST requests: Cloud Shell
if (networkRequest.httpMethod === HttpMethod.POST) {
response =
await this.networkClient.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions);
// Sources that send GET requests: App Service, Azure Arc, IMDS, Service Fabric
}
else {
response =
await this.networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
}
}
catch (error) {
if (error instanceof AuthError) {
throw error;
}
else {
throw createClientAuthError(ClientAuthErrorCodes.networkError);
}
}
const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, null, null);
const serverTokenResponse = await this.getServerTokenResponseAsync(response, this.networkClient, networkRequest, networkRequestOptions);
responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken);
// caches the token
return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest);
}
getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType) {
switch (managedIdentityIdType) {
case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID:
this.logger.info("[Managed Identity] Adding user assigned client id to the request.");
return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID;
case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID:
this.logger.info("[Managed Identity] Adding user assigned resource id to the request.");
return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID;
case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID:
this.logger.info("[Managed Identity] Adding user assigned object id to the request.");
return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID;
default:
throw createManagedIdentityError(invalidManagedIdentityIdType);
}
}
}
BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger) => {
try {
return new UrlString(envVariable).urlString;
}
catch (error) {
logger.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`);
throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]);
}
};
export { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames };
//# sourceMappingURL=BaseManagedIdentitySource.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BaseManagedIdentitySource.mjs","sources":["../../../src/client/ManagedIdentitySources/BaseManagedIdentitySource.ts"],"sourcesContent":[null],"names":["ManagedIdentityErrorCodes.invalidManagedIdentityIdType","ManagedIdentityErrorCodes\r\n .MsiEnvironmentVariableUrlMalformedErrorCodes"],"mappings":";;;;;;;AAAA;;;AAGG;AA+BH;;AAEG;AACU,MAAA,gDAAgD,GAAG;AAC5D,IAAA,0BAA0B,EAAE,WAAW;AACvC,IAAA,0BAA0B,EAAE,WAAW;AACvC,IAAA,4BAA4B,EAAE,WAAW;EAClC;MAIW,yBAAyB,CAAA;AAM3C,IAAA,WAAA,CACI,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAAA;AAE9B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AACrB,QAAA,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;AAC/B,QAAA,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AAC,uBAAuB;AAC9C,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CACZ,mEAAmE,CACtE,CAAC;gBACF,OAAO,gDAAgD,CAAC,0BAA0B,CAAC;AACvF,YAAA;AACI,gBAAA,MAAM,0BAA0B,CAC5BA,4BAAsD,CACzD,CAAC;AACT,SAAA;KACJ;;AAEa,yBAAgC,CAAA,gCAAA,GAAG,CAC7C,qBAA6B,EAC7B,WAAmB,EACnB,UAAkB,EAClB,MAAc,KACN;IACR,IAAI;AACA,QAAA,OAAO,IAAI,SAAS,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC;AAC/C,KAAA;AAAC,IAAA,OAAO,KAAK,EAAE;QACZ,MAAM,CAAC,IAAI,CACP,CAAA,mBAAA,EAAsB,UAAU,CAAiD,8CAAA,EAAA,qBAAqB,CAAsC,oCAAA,CAAA,CAC/I,CAAC;QAEF,MAAM,0BAA0B,CAC5BC,4CACiD,CAC7C,qBAAqB,CACxB,CACJ,CAAC;AACL,KAAA;AACL,CAAC;;;;"}

View File

@@ -0,0 +1,17 @@
import { INetworkModule, Logger } from "@azure/msal-common/node";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs
*/
export declare class CloudShell extends BaseManagedIdentitySource {
private msiEndpoint;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, msiEndpoint: string);
static getEnvironmentVariables(): Array<string | undefined>;
static tryCreate(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, managedIdentityId: ManagedIdentityId): CloudShell | null;
createRequest(resource: string): ManagedIdentityRequestParameters;
}
//# sourceMappingURL=CloudShell.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CloudShell.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/CloudShell.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAahE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAEtE;;GAEG;AACH,qBAAa,UAAW,SAAQ,yBAAyB;IACrD,OAAO,CAAC,WAAW,CAAS;gBAGxB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,WAAW,EAAE,MAAM;WAOT,uBAAuB,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC;WAOpD,SAAS,CACnB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,iBAAiB,EAAE,iBAAiB,GACrC,UAAU,GAAG,IAAI;IAwCb,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,gCAAgC;CAc3E"}

View File

@@ -0,0 +1,49 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, METADATA_HEADER_NAME, RESOURCE_BODY_OR_QUERY_PARAMETER_NAME, HttpMethod } from '../../utils/Constants.mjs';
import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs';
import { unableToCreateCloudShell } from '../../error/ManagedIdentityErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs
*/
class CloudShell extends BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider, msiEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider);
this.msiEndpoint = msiEndpoint;
}
static getEnvironmentVariables() {
const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT];
return [msiEndpoint];
}
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) {
const [msiEndpoint] = CloudShell.getEnvironmentVariables();
// if the msi endpoint environment variable is undefined, this MSI provider is unavailable.
if (!msiEndpoint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`);
return null;
}
const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger);
logger.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`);
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
throw createManagedIdentityError(unableToCreateCloudShell);
}
return new CloudShell(logger, nodeStorage, networkClient, cryptoProvider, msiEndpoint);
}
createRequest(resource) {
const request = new ManagedIdentityRequestParameters(HttpMethod.POST, this.msiEndpoint);
request.headers[METADATA_HEADER_NAME] = "true";
request.bodyParameters[RESOURCE_BODY_OR_QUERY_PARAMETER_NAME] =
resource;
return request;
}
}
export { CloudShell };
//# sourceMappingURL=CloudShell.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CloudShell.mjs","sources":["../../../src/client/ManagedIdentitySources/CloudShell.ts"],"sourcesContent":[null],"names":["ManagedIdentityErrorCodes.unableToCreateCloudShell"],"mappings":";;;;;;;;AAAA;;;AAGG;AAqBH;;AAEG;AACG,MAAO,UAAW,SAAQ,yBAAyB,CAAA;IAGrD,WACI,CAAA,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAC9B,WAAmB,EAAA;QAEnB,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AAE1D,QAAA,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;KAClC;AAEM,IAAA,OAAO,uBAAuB,GAAA;QACjC,MAAM,WAAW,GACb,OAAO,CAAC,GAAG,CAAC,uCAAuC,CAAC,YAAY,CAAC,CAAC;QAEtE,OAAO,CAAC,WAAW,CAAC,CAAC;KACxB;IAEM,OAAO,SAAS,CACnB,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAC9B,iBAAoC,EAAA;QAEpC,MAAM,CAAC,WAAW,CAAC,GAAG,UAAU,CAAC,uBAAuB,EAAE,CAAC;;QAG3D,IAAI,CAAC,WAAW,EAAE;AACd,YAAA,MAAM,CAAC,IAAI,CACP,CAAA,mBAAA,EAAsB,0BAA0B,CAAC,WAAW,CAAA,8CAAA,EAAiD,uCAAuC,CAAC,YAAY,CAAA,qCAAA,CAAuC,CAC3M,CAAC;AACF,YAAA,OAAO,IAAI,CAAC;AACf,SAAA;AAED,QAAA,MAAM,oBAAoB,GACtB,UAAU,CAAC,gCAAgC,CACvC,uCAAuC,CAAC,YAAY,EACpD,WAAW,EACX,0BAA0B,CAAC,WAAW,EACtC,MAAM,CACT,CAAC;AAEN,QAAA,MAAM,CAAC,IAAI,CACP,CAAA,8DAAA,EAAiE,0BAA0B,CAAC,WAAW,CAAoC,iCAAA,EAAA,oBAAoB,cAAc,0BAA0B,CAAC,WAAW,CAAA,kBAAA,CAAoB,CAC1O,CAAC;AAEF,QAAA,IACI,iBAAiB,CAAC,MAAM,KAAK,qBAAqB,CAAC,eAAe,EACpE;AACE,YAAA,MAAM,0BAA0B,CAC5BA,wBAAkD,CACrD,CAAC;AACL,SAAA;AAED,QAAA,OAAO,IAAI,UAAU,CACjB,MAAM,EACN,WAAW,EACX,aAAa,EACb,cAAc,EACd,WAAW,CACd,CAAC;KACL;AAEM,IAAA,aAAa,CAAC,QAAgB,EAAA;AACjC,QAAA,MAAM,OAAO,GACT,IAAI,gCAAgC,CAChC,UAAU,CAAC,IAAI,EACf,IAAI,CAAC,WAAW,CACnB,CAAC;AAEN,QAAA,OAAO,CAAC,OAAO,CAAC,oBAAoB,CAAC,GAAG,MAAM,CAAC;AAE/C,QAAA,OAAO,CAAC,cAAc,CAAC,qCAAqC,CAAC;AACzD,YAAA,QAAQ,CAAC;AAEb,QAAA,OAAO,OAAO,CAAC;KAClB;AACJ;;;;"}

View File

@@ -0,0 +1,13 @@
import { INetworkModule, Logger } from "@azure/msal-common/node";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
export declare class Imds extends BaseManagedIdentitySource {
private identityEndpoint;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, identityEndpoint: string);
static tryCreate(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider): Imds;
createRequest(resource: string, managedIdentityId: ManagedIdentityId): ManagedIdentityRequestParameters;
}
//# sourceMappingURL=Imds.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Imds.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/Imds.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAUhE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AASzD,qBAAa,IAAK,SAAQ,yBAAyB;IAC/C,OAAO,CAAC,gBAAgB,CAAS;gBAG7B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,gBAAgB,EAAE,MAAM;WAOd,SAAS,CACnB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,GAC/B,IAAI;IA8CA,aAAa,CAChB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,iBAAiB,GACrC,gCAAgC;CA4BtC"}

View File

@@ -0,0 +1,52 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, METADATA_HEADER_NAME, API_VERSION_QUERY_PARAMETER_NAME, RESOURCE_BODY_OR_QUERY_PARAMETER_NAME, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// IMDS constants. Docs for IMDS are available here https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http
const IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token";
const DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`;
const IMDS_API_VERSION = "2018-02-01";
// Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ImdsManagedIdentitySource.cs
class Imds extends BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint) {
super(logger, nodeStorage, networkClient, cryptoProvider);
this.identityEndpoint = identityEndpoint;
}
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider) {
let validatedIdentityEndpoint;
if (process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]) {
logger.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`);
validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames
.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH}`, ManagedIdentitySourceNames.IMDS, logger);
}
else {
logger.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`);
validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT;
}
return new Imds(logger, nodeStorage, networkClient, cryptoProvider, validatedIdentityEndpoint);
}
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[METADATA_HEADER_NAME] = "true";
request.queryParameters[API_VERSION_QUERY_PARAMETER_NAME] =
IMDS_API_VERSION;
request.queryParameters[RESOURCE_BODY_OR_QUERY_PARAMETER_NAME] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { Imds };
//# sourceMappingURL=Imds.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Imds.mjs","sources":["../../../src/client/ManagedIdentitySources/Imds.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;AAAA;;;AAGG;AAkBH;AACA,MAAM,eAAe,GAAW,iCAAiC,CAAC;AAClE,MAAM,qBAAqB,GAAW,CAAyB,sBAAA,EAAA,eAAe,EAAE,CAAC;AAEjF,MAAM,gBAAgB,GAAW,YAAY,CAAC;AAE9C;AACM,MAAO,IAAK,SAAQ,yBAAyB,CAAA;IAG/C,WACI,CAAA,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAC9B,gBAAwB,EAAA;QAExB,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AAE1D,QAAA,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;KAC5C;IAEM,OAAO,SAAS,CACnB,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAAA;AAE9B,QAAA,IAAI,yBAAiC,CAAC;AAEtC,QAAA,IACI,OAAO,CAAC,GAAG,CACP,uCAAuC;AAClC,aAAA,iCAAiC,CACzC,EACH;AACE,YAAA,MAAM,CAAC,IAAI,CACP,CACI,wCAAA,EAAA,uCAAuC,CAAC,iCAC5C,CAAA,KAAA,EAAQ,0BAA0B,CAAC,IAAI,CACnC,oBAAA,EAAA,OAAO,CAAC,GAAG,CACP,u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;;;"}

View File

@@ -0,0 +1,18 @@
import { INetworkModule, Logger } from "@azure/msal-common/node";
import { ManagedIdentityId } from "../../config/ManagedIdentityId.js";
import { ManagedIdentityRequestParameters } from "../../config/ManagedIdentityRequestParameters.js";
import { BaseManagedIdentitySource } from "./BaseManagedIdentitySource.js";
import { NodeStorage } from "../../cache/NodeStorage.js";
import { CryptoProvider } from "../../crypto/CryptoProvider.js";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs
*/
export declare class ServiceFabric extends BaseManagedIdentitySource {
private identityEndpoint;
private identityHeader;
constructor(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, identityEndpoint: string, identityHeader: string);
static getEnvironmentVariables(): Array<string | undefined>;
static tryCreate(logger: Logger, nodeStorage: NodeStorage, networkClient: INetworkModule, cryptoProvider: CryptoProvider, managedIdentityId: ManagedIdentityId): ServiceFabric | null;
createRequest(resource: string, managedIdentityId: ManagedIdentityId): ManagedIdentityRequestParameters;
}
//# sourceMappingURL=ServiceFabric.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ServiceFabric.d.ts","sourceRoot":"","sources":["../../../src/client/ManagedIdentitySources/ServiceFabric.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,kDAAkD,CAAC;AACpG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAchE;;GAEG;AACH,qBAAa,aAAc,SAAQ,yBAAyB;IACxD,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,cAAc,CAAS;gBAG3B,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,gBAAgB,EAAE,MAAM,EACxB,cAAc,EAAE,MAAM;WAQZ,uBAAuB,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC;WAkBpD,SAAS,CACnB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,cAAc,EAC7B,cAAc,EAAE,cAAc,EAC9B,iBAAiB,EAAE,iBAAiB,GACrC,aAAa,GAAG,IAAI;IA6ChB,aAAa,CAChB,QAAQ,EAAE,MAAM,EAChB,iBAAiB,EAAE,iBAAiB,GACrC,gCAAgC;CA6BtC"}

View File

@@ -0,0 +1,63 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs';
import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs';
import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, SERVICE_FABRIC_SECRET_HEADER_NAME, API_VERSION_QUERY_PARAMETER_NAME, RESOURCE_BODY_OR_QUERY_PARAMETER_NAME, HttpMethod } from '../../utils/Constants.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity
const SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview";
/**
* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs
*/
class ServiceFabric extends BaseManagedIdentitySource {
constructor(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint, identityHeader) {
super(logger, nodeStorage, networkClient, cryptoProvider);
this.identityEndpoint = identityEndpoint;
this.identityHeader = identityHeader;
}
static getEnvironmentVariables() {
const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER];
const identityServerThumbprint = process.env[ManagedIdentityEnvironmentVariableNames
.IDENTITY_SERVER_THUMBPRINT];
return [identityEndpoint, identityHeader, identityServerThumbprint];
}
static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, managedIdentityId) {
const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables();
/*
* if either of the identity endpoint, identity header, or identity server thumbprint
* environment variables are undefined, this MSI provider is unavailable.
*/
if (!identityEndpoint || !identityHeader || !identityServerThumbprint) {
logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`);
return null;
}
const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger);
logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`);
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
logger.warning(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`);
}
return new ServiceFabric(logger, nodeStorage, networkClient, cryptoProvider, identityEndpoint, identityHeader);
}
createRequest(resource, managedIdentityId) {
const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
request.headers[SERVICE_FABRIC_SECRET_HEADER_NAME] =
this.identityHeader;
request.queryParameters[API_VERSION_QUERY_PARAMETER_NAME] =
SERVICE_FABRIC_MSI_API_VERSION;
request.queryParameters[RESOURCE_BODY_OR_QUERY_PARAMETER_NAME] =
resource;
if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) {
request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
}
// bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity
return request;
}
}
export { ServiceFabric };
//# sourceMappingURL=ServiceFabric.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ServiceFabric.mjs","sources":["../../../src/client/ManagedIdentitySources/ServiceFabric.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;AAAA;;;AAGG;AAkBH;AACA,MAAM,8BAA8B,GAAW,oBAAoB,CAAC;AAEpE;;AAEG;AACG,MAAO,aAAc,SAAQ,yBAAyB,CAAA;IAIxD,WACI,CAAA,MAAc,EACd,WAAwB,EACxB,aAA6B,EAC7B,cAA8B,EAC9B,gBAAwB,EACxB,cAAsB,EAAA;QAEtB,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,CAAC,CAAC;AAE1D,QAAA,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;AACzC,QAAA,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;KACxC;AAEM,IAAA,OAAO,uBAAuB,GAAA;QACjC,MAAM,gBAAgB,GAClB,OAAO,CAAC,GAAG,CACP,uCAAuC,CAAC,iBAAiB,CAC5D,CAAC;QACN,MAAM,cAAc,GAChB,OAAO,CAAC,GAAG,CACP,uCAAuC,CAAC,eAAe,CAC1D,CAAC;AACN,QAAA,MAAM,wBAAwB,GAC1B,OAAO,CAAC,GAAG,CACP,uCAAuC;AAClC,aAAA,0BAA0B,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;IAEM,aAAa,CAChB,QAAgB,EAChB,iBAAoC,EAAA;AAEpC,QAAA,MAAM,OAAO,GACT,IAAI,gCAAgC,CAChC,UAAU,CAAC,GAAG,EACd,IAAI,CAAC,gBAAgB,CACxB,CAAC;AAEN,QAAA,OAAO,CAAC,OAAO,CAAC,iCAAiC,CAAC;YAC9C,IAAI,CAAC,cAAc,CAAC;AAExB,QAAA,OAAO,CAAC,eAAe,CAAC,gCAAgC,CAAC;AACrD,YAAA,8BAA8B,CAAC;AACnC,QAAA,OAAO,CAAC,eAAe,CAAC,qCAAqC,CAAC;AAC1D,YAAA,QAAQ,CAAC;AAEb,QAAA,IACI,iBAAiB,CAAC,MAAM,KAAK,qBAAqB,CAAC,eAAe,EACpE;AACE,YAAA,OAAO,CAAC,eAAe,CACnB,IAAI,CAAC,iDAAiD,CAClD,iBAAiB,CAAC,MAAM,CAC3B,CACJ,GAAG,iBAAiB,CAAC,EAAE,CAAC;AAC5B,SAAA;;AAID,QAAA,OAAO,OAAO,CAAC;KAClB;AACJ;;;;"}

View File

@@ -0,0 +1,48 @@
import { AuthenticationResult, BaseClient, ClientConfiguration, CommonOnBehalfOfRequest } from "@azure/msal-common/node";
/**
* On-Behalf-Of client
* @public
*/
export declare class OnBehalfOfClient extends BaseClient {
private scopeSet;
private userAssertionHash;
constructor(configuration: ClientConfiguration);
/**
* Public API to acquire tokens with on behalf of flow
* @param request - developer provided CommonOnBehalfOfRequest
*/
acquireToken(request: CommonOnBehalfOfRequest): Promise<AuthenticationResult | null>;
/**
* look up cache for tokens
* Find idtoken in the cache
* Find accessToken based on user assertion and account info in the cache
* Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires
* This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session
* @param request - developer provided CommonOnBehalfOfRequest
*/
private getCachedAuthenticationResult;
/**
* read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager
* Certain use cases of OBO flow do not expect an idToken in the cache/or from the service
* @param atHomeAccountId - account id
*/
private readIdTokenFromCacheForOBO;
/**
* Fetches the cached access token based on incoming assertion
* @param clientId - client id
* @param request - developer provided CommonOnBehalfOfRequest
*/
private readAccessTokenFromCacheForOBO;
/**
* Make a network call to the server requesting credentials
* @param request - developer provided CommonOnBehalfOfRequest
* @param authority - authority object
*/
private executeTokenRequest;
/**
* generate a server request in accepable format
* @param request - developer provided CommonOnBehalfOfRequest
*/
private createTokenRequestBody;
}
//# sourceMappingURL=OnBehalfOfClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"OnBehalfOfClient.d.ts","sourceRoot":"","sources":["../../src/client/OnBehalfOfClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAKH,oBAAoB,EAIpB,UAAU,EAGV,mBAAmB,EACnB,uBAAuB,EAgB1B,MAAM,yBAAyB,CAAC;AAGjC;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAC5C,OAAO,CAAC,QAAQ,CAAW;IAC3B,OAAO,CAAC,iBAAiB,CAAS;gBAEtB,aAAa,EAAE,mBAAmB;IAI9C;;;OAGG;IACU,YAAY,CACrB,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IA4BvC;;;;;;;OAOG;YACW,6BAA6B;IAiF3C;;;;OAIG;IACH,OAAO,CAAC,0BAA0B;IAsBlC;;;;OAIG;IACH,OAAO,CAAC,8BAA8B;IA0CtC;;;;OAIG;YACW,mBAAmB;IAwDjC;;;OAGG;YACW,sBAAsB;CAmEvC"}

View File

@@ -0,0 +1,210 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { BaseClient, ScopeSet, CacheOutcome, createClientAuthError, ClientAuthErrorCodes, TimeUtils, AuthToken, ResponseHandler, AuthenticationScheme, CredentialType, UrlString, RequestParameterBuilder, GrantType, AADServerParamKeys, getClientAssertion, Constants } from '@azure/msal-common/node';
import { EncodingUtils } from '../utils/EncodingUtils.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* On-Behalf-Of client
* @public
*/
class OnBehalfOfClient extends BaseClient {
constructor(configuration) {
super(configuration);
}
/**
* Public API to acquire tokens with on behalf of flow
* @param request - developer provided CommonOnBehalfOfRequest
*/
async acquireToken(request) {
this.scopeSet = new ScopeSet(request.scopes || []);
// generate the user_assertion_hash for OBOAssertion
this.userAssertionHash = await this.cryptoUtils.hashString(request.oboAssertion);
if (request.skipCache || request.claims) {
return this.executeTokenRequest(request, this.authority, this.userAssertionHash);
}
try {
return await this.getCachedAuthenticationResult(request);
}
catch (e) {
// Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT
return await this.executeTokenRequest(request, this.authority, this.userAssertionHash);
}
}
/**
* look up cache for tokens
* Find idtoken in the cache
* Find accessToken based on user assertion and account info in the cache
* Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires
* This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session
* @param request - developer provided CommonOnBehalfOfRequest
*/
async getCachedAuthenticationResult(request) {
// look in the cache for the access_token which matches the incoming_assertion
const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request);
if (!cachedAccessToken) {
// Must refresh due to non-existent access_token.
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
}
else if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// Access token expired, will need to renewed
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`);
throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired);
}
// fetch the idToken from cache
const cachedIdToken = this.readIdTokenFromCacheForOBO(cachedAccessToken.homeAccountId);
let idTokenClaims;
let cachedAccount = null;
if (cachedIdToken) {
idTokenClaims = AuthToken.extractTokenClaims(cachedIdToken.secret, EncodingUtils.base64Decode);
const localAccountId = idTokenClaims.oid || idTokenClaims.sub;
const accountInfo = {
homeAccountId: cachedIdToken.homeAccountId,
environment: cachedIdToken.environment,
tenantId: cachedIdToken.realm,
username: Constants.EMPTY_STRING,
localAccountId: localAccountId || Constants.EMPTY_STRING,
};
cachedAccount = this.cacheManager.readAccountFromCache(accountInfo);
}
// increment telemetry cache hit counter
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
account: cachedAccount,
accessToken: cachedAccessToken,
idToken: cachedIdToken,
refreshToken: null,
appMetadata: null,
}, true, request, idTokenClaims);
}
/**
* read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager
* Certain use cases of OBO flow do not expect an idToken in the cache/or from the service
* @param atHomeAccountId - account id
*/
readIdTokenFromCacheForOBO(atHomeAccountId) {
const idTokenFilter = {
homeAccountId: atHomeAccountId,
environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
credentialType: CredentialType.ID_TOKEN,
clientId: this.config.authOptions.clientId,
realm: this.authority.tenant,
};
const idTokenMap = this.cacheManager.getIdTokensByFilter(idTokenFilter);
// When acquiring a token on behalf of an application, there might not be an id token in the cache
if (Object.values(idTokenMap).length < 1) {
return null;
}
return Object.values(idTokenMap)[0];
}
/**
* Fetches the cached access token based on incoming assertion
* @param clientId - client id
* @param request - developer provided CommonOnBehalfOfRequest
*/
readAccessTokenFromCacheForOBO(clientId, request) {
const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
/*
* Distinguish between Bearer and PoP/SSH token cache types
* Cast to lowercase to handle "bearer" from ADFS
*/
const credentialType = authScheme &&
authScheme.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()
? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME
: CredentialType.ACCESS_TOKEN;
const accessTokenFilter = {
credentialType: credentialType,
clientId,
target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),
tokenType: authScheme,
keyId: request.sshKid,
requestedClaimsHash: request.requestedClaimsHash,
userAssertionHash: this.userAssertionHash,
};
const accessTokens = this.cacheManager.getAccessTokensByFilter(accessTokenFilter);
const numAccessTokens = accessTokens.length;
if (numAccessTokens < 1) {
return null;
}
else if (numAccessTokens > 1) {
throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens);
}
return accessTokens[0];
}
/**
* Make a network call to the server requesting credentials
* @param request - developer provided CommonOnBehalfOfRequest
* @param authority - authority object
*/
async executeTokenRequest(request, authority, userAssertionHash) {
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await this.createTokenRequestBody(request);
const headers = this.createTokenRequestHeaders();
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
const reqTimestamp = TimeUtils.nowSeconds();
const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
const tokenResponse = await responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, userAssertionHash);
return tokenResponse;
}
/**
* generate a server request in accepable format
* @param request - developer provided CommonOnBehalfOfRequest
*/
async createTokenRequestBody(request) {
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addGrantType(GrantType.JWT_BEARER);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
parameterBuilder.addRequestTokenUse(AADServerParamKeys.ON_BEHALF_OF);
parameterBuilder.addOboAssertion(request.oboAssertion);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
const clientAssertion = this.config.clientCredentials.clientAssertion;
if (clientAssertion) {
parameterBuilder.addClientAssertion(await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (request.claims ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return parameterBuilder.createQueryString();
}
}
export { OnBehalfOfClient };
//# sourceMappingURL=OnBehalfOfClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,73 @@
import { AuthenticationResult, AccountInfo } from "@azure/msal-common/node";
import { Configuration } from "../config/Configuration.js";
import { ClientApplication } from "./ClientApplication.js";
import { IPublicClientApplication } from "./IPublicClientApplication.js";
import { DeviceCodeRequest } from "../request/DeviceCodeRequest.js";
import { InteractiveRequest } from "../request/InteractiveRequest.js";
import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
import { SignOutRequest } from "../request/SignOutRequest.js";
/**
* This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications
* are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
* @public
*/
export declare class PublicClientApplication extends ClientApplication implements IPublicClientApplication {
private nativeBrokerPlugin?;
private readonly skus;
/**
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
* - authority: the authority URL for your application.
*
* AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
* its own authority. You will have to set the all of the knownAuthorities at the time of the client application
* construction.
*
* ADFS authorities are of the form https://\{instance\}/adfs.
*/
constructor(configuration: Configuration);
/**
* Acquires a token from the authority using OAuth2.0 device code flow.
* This flow is designed for devices that do not have access to a browser or have input constraints.
* The authorization server issues a DeviceCode object with a verification code, an end-user code,
* and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
* instructed to use another device to navigate to the verification URI to input credentials.
* Since the client cannot receive incoming requests, it polls the authorization server repeatedly
* until the end-user completes input of credentials.
*/
acquireTokenByDeviceCode(request: DeviceCodeRequest): Promise<AuthenticationResult | null>;
/**
* Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.
*/
acquireTokenInteractive(request: InteractiveRequest): Promise<AuthenticationResult>;
/**
* Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.
* @param request - developer provided SilentFlowRequest
* @returns
*/
acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>;
/**
* Removes cache artifacts associated with the given account
* @param request - developer provided SignOutRequest
* @returns
*/
signOut(request: SignOutRequest): Promise<void>;
/**
* Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.
* @returns
*/
getAllAccounts(): Promise<AccountInfo[]>;
/**
* Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.
* @param loopbackClient - developer provided custom loopback server implementation
* @returns
*/
private waitForRedirectUri;
}
//# sourceMappingURL=PublicClientApplication.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"PublicClientApplication.d.ts","sourceRoot":"","sources":["../../src/client/PublicClientApplication.ts"],"names":[],"mappings":"AAUA,OAAO,EACH,oBAAoB,EAUpB,WAAW,EAKd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAGpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AAGtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAK9D;;;;GAIG;AACH,qBAAa,uBACT,SAAQ,iBACR,YAAW,wBAAwB;IAEnC,OAAO,CAAC,kBAAkB,CAAC,CAAsB;IACjD,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAC9B;;;;;;;;;;;;;;;;OAgBG;gBACS,aAAa,EAAE,aAAa;IAoBxC;;;;;;;;OAQG;IACU,wBAAwB,CACjC,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAqCvC;;OAEG;IACG,uBAAuB,CACzB,OAAO,EAAE,kBAAkB,GAC5B,OAAO,CAAC,oBAAoB,CAAC;IAgGhC;;;;OAIG;IACG,kBAAkB,CACpB,OAAO,EAAE,iBAAiB,GAC3B,OAAO,CAAC,oBAAoB,CAAC;IA0BhC;;;;OAIG;IACG,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAerD;;;OAGG;IACG,cAAc,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;IAY9C;;;;OAIG;YACW,kBAAkB;CAsCnC"}

View File

@@ -0,0 +1,250 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { Constants, ApiId, LOOPBACK_SERVER_CONSTANTS } from '../utils/Constants.mjs';
import { ServerTelemetryManager, AuthError, OIDC_DEFAULT_SCOPES, ResponseMode, CodeChallengeMethodValues, ServerError, Constants as Constants$1, AADServerParamKeys } from '@azure/msal-common/node';
import { ClientApplication } from './ClientApplication.mjs';
import { NodeAuthError, NodeAuthErrorMessage } from '../error/NodeAuthError.mjs';
import { LoopbackClient } from '../network/LoopbackClient.mjs';
import { DeviceCodeClient } from './DeviceCodeClient.mjs';
import { version } from '../packageMetadata.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications
* are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
* @public
*/
class PublicClientApplication extends ClientApplication {
/**
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
* - authority: the authority URL for your application.
*
* AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
* - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
* its own authority. You will have to set the all of the knownAuthorities at the time of the client application
* construction.
*
* ADFS authorities are of the form https://\{instance\}/adfs.
*/
constructor(configuration) {
super(configuration);
if (this.config.broker.nativeBrokerPlugin) {
if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {
this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;
this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions);
}
else {
this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.");
}
}
this.skus = ServerTelemetryManager.makeExtraSkuString({
libraryName: Constants.MSAL_SKU,
libraryVersion: version,
});
}
/**
* Acquires a token from the authority using OAuth2.0 device code flow.
* This flow is designed for devices that do not have access to a browser or have input constraints.
* The authorization server issues a DeviceCode object with a verification code, an end-user code,
* and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
* instructed to use another device to navigate to the verification URI to input credentials.
* Since the client cannot receive incoming requests, it polls the authorization server repeatedly
* until the end-user completes input of credentials.
*/
async acquireTokenByDeviceCode(request) {
this.logger.info("acquireTokenByDeviceCode called", request.correlationId);
const validRequest = Object.assign(request, await this.initializeBaseRequest(request));
const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);
try {
const deviceCodeConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, "", serverTelemetryManager, undefined, request.azureCloudOptions);
const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);
this.logger.verbose("Device code client created", validRequest.correlationId);
return await deviceCodeClient.acquireToken(validRequest);
}
catch (e) {
if (e instanceof AuthError) {
e.setCorrelationId(validRequest.correlationId);
}
serverTelemetryManager.cacheFailedRequest(e);
throw e;
}
}
/**
* Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.
*/
async acquireTokenInteractive(request) {
const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
this.logger.trace("acquireTokenInteractive called", correlationId);
const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request;
if (this.nativeBrokerPlugin) {
const brokerRequest = {
...remainingProperties,
clientId: this.config.auth.clientId,
scopes: request.scopes || OIDC_DEFAULT_SCOPES,
redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
authority: request.authority || this.config.auth.authority,
correlationId: correlationId,
extraParameters: {
...remainingProperties.extraQueryParameters,
...remainingProperties.tokenQueryParameters,
[AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus,
},
accountId: remainingProperties.account?.nativeAccountId,
};
return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle);
}
const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();
const loopbackClient = customLoopbackClient || new LoopbackClient();
let authCodeResponse = {};
let authCodeListenerError = null;
try {
const authCodeListener = loopbackClient
.listenForAuthCode(successTemplate, errorTemplate)
.then((response) => {
authCodeResponse = response;
})
.catch((e) => {
// Store the promise instead of throwing so we can control when its thrown
authCodeListenerError = e;
});
// Wait for server to be listening
const redirectUri = await this.waitForRedirectUri(loopbackClient);
const validRequest = {
...remainingProperties,
correlationId: correlationId,
scopes: request.scopes || OIDC_DEFAULT_SCOPES,
redirectUri: redirectUri,
responseMode: ResponseMode.QUERY,
codeChallenge: challenge,
codeChallengeMethod: CodeChallengeMethodValues.S256,
};
const authCodeUrl = await this.getAuthCodeUrl(validRequest);
await openBrowser(authCodeUrl);
await authCodeListener;
if (authCodeListenerError) {
throw authCodeListenerError;
}
if (authCodeResponse.error) {
throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
}
else if (!authCodeResponse.code) {
throw NodeAuthError.createNoAuthCodeInResponseError();
}
const clientInfo = authCodeResponse.client_info;
const tokenRequest = {
code: authCodeResponse.code,
codeVerifier: verifier,
clientInfo: clientInfo || Constants$1.EMPTY_STRING,
...validRequest,
};
return await this.acquireTokenByCode(tokenRequest); // Await this so the server doesn't close prematurely
}
finally {
loopbackClient.closeServer();
}
}
/**
* Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.
* @param request - developer provided SilentFlowRequest
* @returns
*/
async acquireTokenSilent(request) {
const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
this.logger.trace("acquireTokenSilent called", correlationId);
if (this.nativeBrokerPlugin) {
const brokerRequest = {
...request,
clientId: this.config.auth.clientId,
scopes: request.scopes || OIDC_DEFAULT_SCOPES,
redirectUri: `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}`,
authority: request.authority || this.config.auth.authority,
correlationId: correlationId,
extraParameters: {
...request.tokenQueryParameters,
[AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus,
},
accountId: request.account.nativeAccountId,
forceRefresh: request.forceRefresh || false,
};
return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);
}
return super.acquireTokenSilent(request);
}
/**
* Removes cache artifacts associated with the given account
* @param request - developer provided SignOutRequest
* @returns
*/
async signOut(request) {
if (this.nativeBrokerPlugin && request.account.nativeAccountId) {
const signoutRequest = {
clientId: this.config.auth.clientId,
accountId: request.account.nativeAccountId,
correlationId: request.correlationId ||
this.cryptoProvider.createNewGuid(),
};
await this.nativeBrokerPlugin.signOut(signoutRequest);
}
await this.getTokenCache().removeAccount(request.account);
}
/**
* Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.
* @returns
*/
async getAllAccounts() {
if (this.nativeBrokerPlugin) {
const correlationId = this.cryptoProvider.createNewGuid();
return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId);
}
return this.getTokenCache().getAllAccounts();
}
/**
* Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.
* @param loopbackClient - developer provided custom loopback server implementation
* @returns
*/
async waitForRedirectUri(loopbackClient) {
return new Promise((resolve, reject) => {
let ticks = 0;
const id = setInterval(() => {
if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS /
LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS <
ticks) {
clearInterval(id);
reject(NodeAuthError.createLoopbackServerTimeoutError());
return;
}
try {
const r = loopbackClient.getRedirectUri();
clearInterval(id);
resolve(r);
return;
}
catch (e) {
if (e instanceof AuthError &&
e.errorCode ===
NodeAuthErrorMessage.noLoopbackServerExists.code) {
// Loopback server is not listening yet
ticks++;
return;
}
clearInterval(id);
reject(e);
return;
}
}, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
});
}
}
export { PublicClientApplication };
//# sourceMappingURL=PublicClientApplication.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { AuthenticationResult, BaseClient, ClientConfiguration, CommonUsernamePasswordRequest } from "@azure/msal-common/node";
/**
* Oauth2.0 Password grant client
* Note: We are only supporting public clients for password grant and for purely testing purposes
* @public
*/
export declare class UsernamePasswordClient extends BaseClient {
constructor(configuration: ClientConfiguration);
/**
* API to acquire a token by passing the username and password to the service in exchage of credentials
* password_grant
* @param request - CommonUsernamePasswordRequest
*/
acquireToken(request: CommonUsernamePasswordRequest): Promise<AuthenticationResult | null>;
/**
* Executes POST request to token endpoint
* @param authority - authority object
* @param request - CommonUsernamePasswordRequest provided by the developer
*/
private executeTokenRequest;
/**
* Generates a map for all the params to be sent to the service
* @param request - CommonUsernamePasswordRequest provided by the developer
*/
private createTokenRequestBody;
}
//# sourceMappingURL=UsernamePasswordClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"UsernamePasswordClient.d.ts","sourceRoot":"","sources":["../../src/client/UsernamePasswordClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,oBAAoB,EAEpB,UAAU,EAGV,mBAAmB,EACnB,6BAA6B,EAWhC,MAAM,yBAAyB,CAAC;AAEjC;;;;GAIG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;gBACtC,aAAa,EAAE,mBAAmB;IAI9C;;;;OAIG;IACG,YAAY,CACd,OAAO,EAAE,6BAA6B,GACvC,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IA8BvC;;;;OAIG;YACW,mBAAmB;IAmCjC;;;OAGG;YACW,sBAAsB;CAyEvC"}

View File

@@ -0,0 +1,103 @@
/*! @azure/msal-node v2.16.2 2024-11-19 */
'use strict';
import { BaseClient, TimeUtils, ResponseHandler, UrlString, CcsCredentialType, RequestParameterBuilder, GrantType, getClientAssertion, StringUtils } from '@azure/msal-common/node';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Oauth2.0 Password grant client
* Note: We are only supporting public clients for password grant and for purely testing purposes
* @public
*/
class UsernamePasswordClient extends BaseClient {
constructor(configuration) {
super(configuration);
}
/**
* API to acquire a token by passing the username and password to the service in exchage of credentials
* password_grant
* @param request - CommonUsernamePasswordRequest
*/
async acquireToken(request) {
this.logger.info("in acquireToken call in username-password client");
const reqTimestamp = TimeUtils.nowSeconds();
const response = await this.executeTokenRequest(this.authority, request);
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body);
const tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request);
return tokenResponse;
}
/**
* Executes POST request to token endpoint
* @param authority - authority object
* @param request - CommonUsernamePasswordRequest provided by the developer
*/
async executeTokenRequest(authority, request) {
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await this.createTokenRequestBody(request);
const headers = this.createTokenRequestHeaders({
credential: request.username,
type: CcsCredentialType.UPN,
});
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
}
/**
* Generates a map for all the params to be sent to the service
* @param request - CommonUsernamePasswordRequest provided by the developer
*/
async createTokenRequestBody(request) {
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addUsername(request.username);
parameterBuilder.addPassword(request.password);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addResponseTypeForTokenAndIdToken();
parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
const clientAssertion = this.config.clientCredentials.clientAssertion;
if (clientAssertion) {
parameterBuilder.addClientAssertion(await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (this.config.systemOptions.preventCorsPreflight &&
request.username) {
parameterBuilder.addCcsUpn(request.username);
}
return parameterBuilder.createQueryString();
}
}
export { UsernamePasswordClient };
//# sourceMappingURL=UsernamePasswordClient.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"UsernamePasswordClient.mjs","sources":["../../src/client/UsernamePasswordClient.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;AAAA;;;AAGG;AAsBH;;;;AAIG;AACG,MAAO,sBAAuB,SAA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C5D;AACE,YAAA,gBAAgB,CAAC,SAAS,CACtB,OAAO,CAAC,MAAM,EACd,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAkB,CAC7C,CAAC;AACL,SAAA;AAED,QAAA,IACI,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,oBAAoB;YAC9C,OAAO,CAAC,QAAQ,EAClB;AACE,YAAA,gBAAgB,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AAChD,SAAA;AAED,QAAA,OAAO,gBAAgB,CAAC,iBAAiB,EAAE,CAAC;KAC/C;AACJ;;;;"}

View File

@@ -0,0 +1,136 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { LoggerOptions, INetworkModule, ProtocolMode, ICachePlugin, AzureCloudOptions, ApplicationTelemetry, INativeBrokerPlugin, ClientAssertionCallback } from "@azure/msal-common/node";
import http from "http";
import https from "https";
import { ManagedIdentityId } from "./ManagedIdentityId.js";
/**
* - clientId - Client id of the application.
* - authority - Url of the authority. If no value is set, defaults to https://login.microsoftonline.com/common.
* - knownAuthorities - Needed for Azure B2C and ADFS. All authorities that will be used in the client application. Only the host of the authority should be passed in.
* - clientSecret - Secret string that the application uses when requesting a token. Only used in confidential client applications. Can be created in the Azure app registration portal.
* - clientAssertion - A ClientAssertion object containing an assertion string or a callback function that returns an assertion string that the application uses when requesting a token, as well as the assertion's type (urn:ietf:params:oauth:client-assertion-type:jwt-bearer). Only used in confidential client applications.
* - clientCertificate - Certificate that the application uses when requesting a token. Only used in confidential client applications. Requires hex encoded X.509 SHA-1 or SHA-256 thumbprint of the certificate, and the PEM encoded private key (string should contain -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- )
* - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.
* - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.
* @public
*/
export type NodeAuthOptions = {
clientId: string;
authority?: string;
clientSecret?: string;
clientAssertion?: string | ClientAssertionCallback;
clientCertificate?: {
/**
* @deprecated Use thumbprintSha2 property instead. Thumbprint needs to be computed with SHA-256 algorithm.
* SHA-1 is only needed for backwards compatibility with older versions of ADFS.
*/
thumbprint?: string;
thumbprintSha256?: string;
privateKey: string;
x5c?: string;
};
knownAuthorities?: Array<string>;
cloudDiscoveryMetadata?: string;
authorityMetadata?: string;
clientCapabilities?: Array<string>;
protocolMode?: ProtocolMode;
azureCloudOptions?: AzureCloudOptions;
skipAuthorityMetadataCache?: boolean;
};
/**
* Use this to configure the below cache configuration options:
*
* - cachePlugin - Plugin for reading and writing token cache to disk.
* @public
*/
export type CacheOptions = {
cachePlugin?: ICachePlugin;
/**
* @deprecated claims-based-caching functionality will be removed in the next version of MSALJS
*/
claimsBasedCachingEnabled?: boolean;
};
/**
* Use this to configure the below broker options:
* - nativeBrokerPlugin - Native broker implementation (should be imported from msal-node-extensions)
*
* Note: These options are only available for PublicClientApplications using the Authorization Code Flow
* @public
*/
export type BrokerOptions = {
nativeBrokerPlugin?: INativeBrokerPlugin;
};
/**
* Type for configuring logger and http client options
*
* - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger
* - networkClient - Http client used for all http get and post calls. Defaults to using MSAL's default http client.
* @public
*/
export type NodeSystemOptions = {
loggerOptions?: LoggerOptions;
networkClient?: INetworkModule;
proxyUrl?: string;
customAgentOptions?: http.AgentOptions | https.AgentOptions;
disableInternalRetries?: boolean;
};
/** @public */
export type NodeTelemetryOptions = {
application?: ApplicationTelemetry;
};
/**
* Use the configuration object to configure MSAL and initialize the client application object
*
* - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform
* - broker: this is where you configure broker options
* - cache: this is where you configure cache location
* - system: this is where you can configure the network client, logger
* - telemetry: this is where you can configure telemetry options
* @public
*/
export type Configuration = {
auth: NodeAuthOptions;
broker?: BrokerOptions;
cache?: CacheOptions;
system?: NodeSystemOptions;
telemetry?: NodeTelemetryOptions;
};
/** @public */
export type ManagedIdentityIdParams = {
userAssignedClientId?: string;
userAssignedResourceId?: string;
userAssignedObjectId?: string;
};
/** @public */
export type ManagedIdentityConfiguration = {
managedIdentityIdParams?: ManagedIdentityIdParams;
system?: NodeSystemOptions;
};
/** @internal */
export type NodeConfiguration = {
auth: Required<NodeAuthOptions>;
broker: BrokerOptions;
cache: CacheOptions;
system: Required<NodeSystemOptions>;
telemetry: Required<NodeTelemetryOptions>;
};
/**
* Sets the default options when not explicitly configured from app developer
*
* @param auth - Authentication options
* @param cache - Cache options
* @param system - System options
* @param telemetry - Telemetry options
*
* @returns Configuration
* @internal
*/
export declare function buildAppConfiguration({ auth, broker, cache, system, telemetry, }: Configuration): NodeConfiguration;
/** @internal */
export type ManagedIdentityNodeConfiguration = {
managedIdentityId: ManagedIdentityId;
system: Required<Pick<NodeSystemOptions, "loggerOptions" | "networkClient">>;
};
export declare function buildManagedIdentityConfiguration({ managedIdentityIdParams, system, }: ManagedIdentityConfiguration): ManagedIdentityNodeConfiguration;
//# sourceMappingURL=Configuration.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Configuration.d.ts","sourceRoot":"","sources":["../../src/config/Configuration.ts"],"names":[],"mappings":";;AAKA,OAAO,EACH,aAAa,EACb,cAAc,EAEd,YAAY,EACZ,YAAY,EAGZ,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,uBAAuB,EAC1B,MAAM,yBAAyB,CAAC;AAEjC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAU3D;;;;;;;;;;GAUG;AACH,MAAM,MAAM,eAAe,GAAG;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,GAAG,uBAAuB,CAAC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