wcz-layout
Version:
52 lines (51 loc) • 2.02 kB
JavaScript
import { scopes } from "virtual:wcz-layout";
import { createServerOnlyFn } from "@tanstack/react-start";
//#region src/lib/auth/msalServer.ts
/**
* Singleton client for the service flows. Unlike the interactive refresh flow,
* caching here is safe and desirable: MSAL partitions on-behalf-of tokens by the
* incoming user assertion, and client-credentials tokens are app-level (no user).
*
* `entra` is imported dynamically so its `@azure/msal-node` dependency is never
* pulled into the client bundle by anything re-exporting these server functions.
*/
let ccaInstance = null;
const getCCA = async () => {
if (!ccaInstance) {
const { createConfidentialClient } = await import("./entra-DbC3aZkF.mjs");
ccaInstance = createConfidentialClient();
}
return ccaInstance;
};
/**
* On-Behalf-Of flow: Exchange user token for a token to call downstream API
* Use when: Server needs to call microservice on behalf of the logged-in user
*/
const getTokenOnBehalfOf = createServerOnlyFn(async (userToken, scopeKey) => {
const cca = await getCCA();
const scopes$1 = [...scopes[scopeKey]];
const result = await cca.acquireTokenOnBehalfOf({
oboAssertion: userToken,
scopes: scopes$1
});
if (!result) throw new Error("Failed to acquire OBO token");
return result.accessToken;
});
/**
* Client Credentials flow: Get app-only token (no user context)
* Use when: Background jobs, scheduled tasks, service-to-service calls
*/
const getAppToken = createServerOnlyFn(async (scopeKey) => {
const cca = await getCCA();
const defaultScopes = scopes[scopeKey].map((scope) => {
const lastSlash = scope.lastIndexOf("/");
return `${scope.substring(0, lastSlash)}/.default`;
});
const uniqueScopes = [...new Set(defaultScopes)];
const result = await cca.acquireTokenByClientCredential({ scopes: uniqueScopes });
if (!result) throw new Error("Failed to acquire app token");
return result.accessToken;
});
//#endregion
export { getTokenOnBehalfOf as n, getAppToken as t };
//# sourceMappingURL=msalServer-BHuM63vM.mjs.map