Refactor createPca function to dynamically import msal-node-extensions and improve cache plugin fallback handling

This commit is contained in:
2026-02-07 13:30:24 +01:00
parent 752c6c797c
commit 0748210744

View File

@@ -4,12 +4,7 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { PublicClientApplication } from "@azure/msal-node"; import { PublicClientApplication } from "@azure/msal-node";
import { import os from "node:os";
DataProtectionScope,
Environment,
PersistenceCachePlugin,
PersistenceCreator,
} from "@azure/msal-node-extensions";
function fileCachePlugin(cachePath) { function fileCachePlugin(cachePath) {
return { return {
@@ -28,13 +23,23 @@ function fileCachePlugin(cachePath) {
} }
async function createPca({ tenantId, clientId }) { async function createPca({ tenantId, clientId }) {
const cacheRoot = Environment.isWindowsPlatform() const isWindows = process.platform === "win32";
? path.join(Environment.getUserRootDirectory(), "sk-az-tools") const userRoot = isWindows
: path.join(Environment.getUserRootDirectory(), ".config", "sk-az-tools"); ? process.env.LOCALAPPDATA || os.homedir()
: os.homedir();
const cacheRoot = isWindows
? path.join(userRoot, "sk-az-tools")
: path.join(userRoot, ".config", "sk-az-tools");
const cachePath = path.join(cacheRoot, `${clientId}-msal.cache`); const cachePath = path.join(cacheRoot, `${clientId}-msal.cache`);
let cachePlugin; let cachePlugin;
try { try {
const {
DataProtectionScope,
PersistenceCachePlugin,
PersistenceCreator,
} = await import("@azure/msal-node-extensions");
const persistence = await PersistenceCreator.createPersistence({ const persistence = await PersistenceCreator.createPersistence({
cachePath, cachePath,
dataProtectionScope: DataProtectionScope.CurrentUser, dataProtectionScope: DataProtectionScope.CurrentUser,
@@ -44,7 +49,7 @@ async function createPca({ tenantId, clientId }) {
}); });
cachePlugin = new PersistenceCachePlugin(persistence); cachePlugin = new PersistenceCachePlugin(persistence);
} catch (err) { } catch (err) {
// Fallback for Linux environments where libsecret integration is unavailable. // Fallback when msal-node-extensions/keytar/libsecret are unavailable.
cachePlugin = fileCachePlugin(cachePath); cachePlugin = fileCachePlugin(cachePath);
} }