@chemmangat/msal-next 3.1.7 → 3.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -1
- package/README.md +1 -1
- package/dist/index.d.mts +199 -19
- package/dist/index.d.ts +199 -19
- package/dist/index.js +2 -1620
- package/dist/index.mjs +2 -1566
- package/dist/server.js +1 -115
- package/dist/server.mjs +1 -87
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1,1566 +1,2 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
|
|
3
|
-
// src/components/MsalAuthProvider.tsx
|
|
4
|
-
import { MsalProvider } from "@azure/msal-react";
|
|
5
|
-
import { PublicClientApplication, EventType } from "@azure/msal-browser";
|
|
6
|
-
import { useEffect, useState, useRef } from "react";
|
|
7
|
-
|
|
8
|
-
// src/utils/createMsalConfig.ts
|
|
9
|
-
import { LogLevel } from "@azure/msal-browser";
|
|
10
|
-
|
|
11
|
-
// src/utils/validation.ts
|
|
12
|
-
function safeJsonParse(jsonString, validator) {
|
|
13
|
-
try {
|
|
14
|
-
const parsed = JSON.parse(jsonString);
|
|
15
|
-
if (validator(parsed)) {
|
|
16
|
-
return parsed;
|
|
17
|
-
}
|
|
18
|
-
console.warn("[Validation] JSON validation failed");
|
|
19
|
-
return null;
|
|
20
|
-
} catch (error) {
|
|
21
|
-
console.error("[Validation] JSON parse error:", error);
|
|
22
|
-
return null;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
function isValidAccountData(data) {
|
|
26
|
-
return typeof data === "object" && data !== null && typeof data.homeAccountId === "string" && data.homeAccountId.length > 0 && typeof data.username === "string" && data.username.length > 0 && (data.name === void 0 || typeof data.name === "string");
|
|
27
|
-
}
|
|
28
|
-
function sanitizeError(error) {
|
|
29
|
-
if (error instanceof Error) {
|
|
30
|
-
const message = error.message;
|
|
31
|
-
const sanitized = message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g, "[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi, "[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi, "Bearer [REDACTED]");
|
|
32
|
-
return sanitized;
|
|
33
|
-
}
|
|
34
|
-
return "An unexpected error occurred";
|
|
35
|
-
}
|
|
36
|
-
function isValidRedirectUri(uri, allowedOrigins) {
|
|
37
|
-
try {
|
|
38
|
-
const url = new URL(uri);
|
|
39
|
-
return allowedOrigins.some((allowed) => {
|
|
40
|
-
const allowedUrl = new URL(allowed);
|
|
41
|
-
return url.origin === allowedUrl.origin;
|
|
42
|
-
});
|
|
43
|
-
} catch {
|
|
44
|
-
return false;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
function isValidScope(scope) {
|
|
48
|
-
return /^[a-zA-Z0-9._-]+$/.test(scope);
|
|
49
|
-
}
|
|
50
|
-
function validateScopes(scopes) {
|
|
51
|
-
return Array.isArray(scopes) && scopes.every(isValidScope);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// src/utils/createMsalConfig.ts
|
|
55
|
-
function createMsalConfig(config) {
|
|
56
|
-
if (config.msalConfig) {
|
|
57
|
-
return config.msalConfig;
|
|
58
|
-
}
|
|
59
|
-
const {
|
|
60
|
-
clientId,
|
|
61
|
-
tenantId,
|
|
62
|
-
authorityType = "common",
|
|
63
|
-
redirectUri,
|
|
64
|
-
postLogoutRedirectUri,
|
|
65
|
-
cacheLocation = "sessionStorage",
|
|
66
|
-
storeAuthStateInCookie = false,
|
|
67
|
-
navigateToLoginRequestUrl = false,
|
|
68
|
-
enableLogging = false,
|
|
69
|
-
loggerCallback,
|
|
70
|
-
allowedRedirectUris
|
|
71
|
-
} = config;
|
|
72
|
-
if (!clientId) {
|
|
73
|
-
throw new Error("@chemmangat/msal-next: clientId is required");
|
|
74
|
-
}
|
|
75
|
-
const getAuthority = () => {
|
|
76
|
-
if (authorityType === "tenant") {
|
|
77
|
-
if (!tenantId) {
|
|
78
|
-
throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');
|
|
79
|
-
}
|
|
80
|
-
return `https://login.microsoftonline.com/${tenantId}`;
|
|
81
|
-
}
|
|
82
|
-
return `https://login.microsoftonline.com/${authorityType}`;
|
|
83
|
-
};
|
|
84
|
-
const defaultRedirectUri = typeof window !== "undefined" ? window.location.origin : "http://localhost:3000";
|
|
85
|
-
const finalRedirectUri = redirectUri || defaultRedirectUri;
|
|
86
|
-
if (allowedRedirectUris && allowedRedirectUris.length > 0) {
|
|
87
|
-
if (!isValidRedirectUri(finalRedirectUri, allowedRedirectUris)) {
|
|
88
|
-
throw new Error(
|
|
89
|
-
`@chemmangat/msal-next: redirectUri "${finalRedirectUri}" is not in the allowed list`
|
|
90
|
-
);
|
|
91
|
-
}
|
|
92
|
-
const finalPostLogoutUri = postLogoutRedirectUri || finalRedirectUri;
|
|
93
|
-
if (!isValidRedirectUri(finalPostLogoutUri, allowedRedirectUris)) {
|
|
94
|
-
throw new Error(
|
|
95
|
-
`@chemmangat/msal-next: postLogoutRedirectUri "${finalPostLogoutUri}" is not in the allowed list`
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
const msalConfig = {
|
|
100
|
-
auth: {
|
|
101
|
-
clientId,
|
|
102
|
-
authority: getAuthority(),
|
|
103
|
-
redirectUri: finalRedirectUri,
|
|
104
|
-
postLogoutRedirectUri: postLogoutRedirectUri || finalRedirectUri,
|
|
105
|
-
navigateToLoginRequestUrl
|
|
106
|
-
},
|
|
107
|
-
cache: {
|
|
108
|
-
cacheLocation,
|
|
109
|
-
storeAuthStateInCookie
|
|
110
|
-
},
|
|
111
|
-
system: {
|
|
112
|
-
loggerOptions: {
|
|
113
|
-
loggerCallback: loggerCallback || ((level, message, containsPii) => {
|
|
114
|
-
if (containsPii || !enableLogging) return;
|
|
115
|
-
switch (level) {
|
|
116
|
-
case LogLevel.Error:
|
|
117
|
-
console.error("[MSAL]", message);
|
|
118
|
-
break;
|
|
119
|
-
case LogLevel.Warning:
|
|
120
|
-
console.warn("[MSAL]", message);
|
|
121
|
-
break;
|
|
122
|
-
case LogLevel.Info:
|
|
123
|
-
console.info("[MSAL]", message);
|
|
124
|
-
break;
|
|
125
|
-
case LogLevel.Verbose:
|
|
126
|
-
console.debug("[MSAL]", message);
|
|
127
|
-
break;
|
|
128
|
-
}
|
|
129
|
-
}),
|
|
130
|
-
logLevel: enableLogging ? LogLevel.Verbose : LogLevel.Error
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
return msalConfig;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// src/components/MsalAuthProvider.tsx
|
|
138
|
-
import { Fragment, jsx } from "react/jsx-runtime";
|
|
139
|
-
var globalMsalInstance = null;
|
|
140
|
-
function getMsalInstance() {
|
|
141
|
-
return globalMsalInstance;
|
|
142
|
-
}
|
|
143
|
-
function MsalAuthProvider({ children, loadingComponent, onInitialized, ...config }) {
|
|
144
|
-
const [msalInstance, setMsalInstance] = useState(null);
|
|
145
|
-
const instanceRef = useRef(null);
|
|
146
|
-
useEffect(() => {
|
|
147
|
-
if (typeof window === "undefined") {
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
if (instanceRef.current) {
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
const initializeMsal = async () => {
|
|
154
|
-
try {
|
|
155
|
-
const msalConfig = createMsalConfig(config);
|
|
156
|
-
const instance = new PublicClientApplication(msalConfig);
|
|
157
|
-
await instance.initialize();
|
|
158
|
-
try {
|
|
159
|
-
const response = await instance.handleRedirectPromise();
|
|
160
|
-
if (response) {
|
|
161
|
-
if (config.enableLogging) {
|
|
162
|
-
console.log("[MSAL] Redirect authentication successful");
|
|
163
|
-
}
|
|
164
|
-
if (response.account) {
|
|
165
|
-
instance.setActiveAccount(response.account);
|
|
166
|
-
}
|
|
167
|
-
if (window.location.hash) {
|
|
168
|
-
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
} catch (redirectError) {
|
|
172
|
-
if (redirectError?.errorCode === "no_token_request_cache_error") {
|
|
173
|
-
if (config.enableLogging) {
|
|
174
|
-
console.log("[MSAL] No pending redirect found (this is normal)");
|
|
175
|
-
}
|
|
176
|
-
} else if (redirectError?.errorCode === "user_cancelled") {
|
|
177
|
-
if (config.enableLogging) {
|
|
178
|
-
console.log("[MSAL] User cancelled authentication");
|
|
179
|
-
}
|
|
180
|
-
} else {
|
|
181
|
-
console.error("[MSAL] Redirect handling error:", redirectError);
|
|
182
|
-
}
|
|
183
|
-
if (window.location.hash && (window.location.hash.includes("code=") || window.location.hash.includes("error="))) {
|
|
184
|
-
window.history.replaceState(null, "", window.location.pathname + window.location.search);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
const accounts = instance.getAllAccounts();
|
|
188
|
-
if (accounts.length > 0 && !instance.getActiveAccount()) {
|
|
189
|
-
instance.setActiveAccount(accounts[0]);
|
|
190
|
-
}
|
|
191
|
-
const enableLogging = config.enableLogging || false;
|
|
192
|
-
instance.addEventCallback((event) => {
|
|
193
|
-
if (event.eventType === EventType.LOGIN_SUCCESS) {
|
|
194
|
-
const payload = event.payload;
|
|
195
|
-
if (payload?.account) {
|
|
196
|
-
instance.setActiveAccount(payload.account);
|
|
197
|
-
}
|
|
198
|
-
if (enableLogging) {
|
|
199
|
-
console.log("[MSAL] Login successful:", payload.account?.username);
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
if (event.eventType === EventType.LOGIN_FAILURE) {
|
|
203
|
-
console.error("[MSAL] Login failed:", event.error);
|
|
204
|
-
}
|
|
205
|
-
if (event.eventType === EventType.LOGOUT_SUCCESS) {
|
|
206
|
-
instance.setActiveAccount(null);
|
|
207
|
-
if (enableLogging) {
|
|
208
|
-
console.log("[MSAL] Logout successful");
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
if (event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS) {
|
|
212
|
-
const payload = event.payload;
|
|
213
|
-
if (payload?.account && !instance.getActiveAccount()) {
|
|
214
|
-
instance.setActiveAccount(payload.account);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
if (event.eventType === EventType.ACQUIRE_TOKEN_FAILURE) {
|
|
218
|
-
if (enableLogging) {
|
|
219
|
-
console.error("[MSAL] Token acquisition failed:", event.error);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
});
|
|
223
|
-
instanceRef.current = instance;
|
|
224
|
-
globalMsalInstance = instance;
|
|
225
|
-
setMsalInstance(instance);
|
|
226
|
-
if (onInitialized) {
|
|
227
|
-
onInitialized(instance);
|
|
228
|
-
}
|
|
229
|
-
} catch (error) {
|
|
230
|
-
console.error("[MSAL] Initialization failed:", error);
|
|
231
|
-
throw error;
|
|
232
|
-
}
|
|
233
|
-
};
|
|
234
|
-
initializeMsal();
|
|
235
|
-
}, []);
|
|
236
|
-
if (typeof window === "undefined") {
|
|
237
|
-
return /* @__PURE__ */ jsx(Fragment, { children: loadingComponent || /* @__PURE__ */ jsx("div", { children: "Loading authentication..." }) });
|
|
238
|
-
}
|
|
239
|
-
if (!msalInstance) {
|
|
240
|
-
return /* @__PURE__ */ jsx(Fragment, { children: loadingComponent || /* @__PURE__ */ jsx("div", { children: "Loading authentication..." }) });
|
|
241
|
-
}
|
|
242
|
-
return /* @__PURE__ */ jsx(MsalProvider, { instance: msalInstance, children });
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// src/components/MSALProvider.tsx
|
|
246
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
247
|
-
function MSALProvider({ children, ...props }) {
|
|
248
|
-
return /* @__PURE__ */ jsx2(MsalAuthProvider, { ...props, children });
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// src/hooks/useMsalAuth.ts
|
|
252
|
-
import { useMsal, useAccount } from "@azure/msal-react";
|
|
253
|
-
import { InteractionStatus } from "@azure/msal-browser";
|
|
254
|
-
import { useCallback, useMemo } from "react";
|
|
255
|
-
var pendingTokenRequests = /* @__PURE__ */ new Map();
|
|
256
|
-
function useMsalAuth(defaultScopes = ["User.Read"]) {
|
|
257
|
-
const { instance, accounts, inProgress } = useMsal();
|
|
258
|
-
const account = useAccount(accounts[0] || null);
|
|
259
|
-
const isAuthenticated = useMemo(() => accounts.length > 0, [accounts]);
|
|
260
|
-
const loginRedirect = useCallback(
|
|
261
|
-
async (scopes = defaultScopes) => {
|
|
262
|
-
if (inProgress !== InteractionStatus.None) {
|
|
263
|
-
console.warn("[MSAL] Interaction already in progress");
|
|
264
|
-
return;
|
|
265
|
-
}
|
|
266
|
-
try {
|
|
267
|
-
const request = {
|
|
268
|
-
scopes,
|
|
269
|
-
prompt: "select_account"
|
|
270
|
-
};
|
|
271
|
-
await instance.loginRedirect(request);
|
|
272
|
-
} catch (error) {
|
|
273
|
-
if (error?.errorCode === "user_cancelled") {
|
|
274
|
-
console.log("[MSAL] User cancelled login");
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
console.error("[MSAL] Login redirect failed:", error);
|
|
278
|
-
throw error;
|
|
279
|
-
}
|
|
280
|
-
},
|
|
281
|
-
[instance, defaultScopes, inProgress]
|
|
282
|
-
);
|
|
283
|
-
const logoutRedirect = useCallback(async () => {
|
|
284
|
-
try {
|
|
285
|
-
await instance.logoutRedirect({
|
|
286
|
-
account: account || void 0
|
|
287
|
-
});
|
|
288
|
-
} catch (error) {
|
|
289
|
-
console.error("[MSAL] Logout redirect failed:", error);
|
|
290
|
-
throw error;
|
|
291
|
-
}
|
|
292
|
-
}, [instance, account]);
|
|
293
|
-
const acquireTokenSilent = useCallback(
|
|
294
|
-
async (scopes = defaultScopes) => {
|
|
295
|
-
if (!account) {
|
|
296
|
-
throw new Error("[MSAL] No active account. Please login first.");
|
|
297
|
-
}
|
|
298
|
-
try {
|
|
299
|
-
const request = {
|
|
300
|
-
scopes,
|
|
301
|
-
account,
|
|
302
|
-
forceRefresh: false
|
|
303
|
-
};
|
|
304
|
-
const response = await instance.acquireTokenSilent(request);
|
|
305
|
-
return response.accessToken;
|
|
306
|
-
} catch (error) {
|
|
307
|
-
console.error("[MSAL] Silent token acquisition failed:", error);
|
|
308
|
-
throw error;
|
|
309
|
-
}
|
|
310
|
-
},
|
|
311
|
-
[instance, account, defaultScopes]
|
|
312
|
-
);
|
|
313
|
-
const acquireTokenRedirect = useCallback(
|
|
314
|
-
async (scopes = defaultScopes) => {
|
|
315
|
-
if (!account) {
|
|
316
|
-
throw new Error("[MSAL] No active account. Please login first.");
|
|
317
|
-
}
|
|
318
|
-
try {
|
|
319
|
-
const request = {
|
|
320
|
-
scopes,
|
|
321
|
-
account
|
|
322
|
-
};
|
|
323
|
-
await instance.acquireTokenRedirect(request);
|
|
324
|
-
} catch (error) {
|
|
325
|
-
console.error("[MSAL] Token redirect acquisition failed:", error);
|
|
326
|
-
throw error;
|
|
327
|
-
}
|
|
328
|
-
},
|
|
329
|
-
[instance, account, defaultScopes]
|
|
330
|
-
);
|
|
331
|
-
const acquireToken = useCallback(
|
|
332
|
-
async (scopes = defaultScopes) => {
|
|
333
|
-
const requestKey = `${account?.homeAccountId || "anonymous"}-${scopes.sort().join(",")}`;
|
|
334
|
-
const pendingRequest = pendingTokenRequests.get(requestKey);
|
|
335
|
-
if (pendingRequest) {
|
|
336
|
-
return pendingRequest;
|
|
337
|
-
}
|
|
338
|
-
const tokenRequest = (async () => {
|
|
339
|
-
try {
|
|
340
|
-
return await acquireTokenSilent(scopes);
|
|
341
|
-
} catch (error) {
|
|
342
|
-
console.warn("[MSAL] Silent token acquisition failed, falling back to redirect");
|
|
343
|
-
await acquireTokenRedirect(scopes);
|
|
344
|
-
throw new Error("[MSAL] Redirecting for token acquisition");
|
|
345
|
-
} finally {
|
|
346
|
-
pendingTokenRequests.delete(requestKey);
|
|
347
|
-
}
|
|
348
|
-
})();
|
|
349
|
-
pendingTokenRequests.set(requestKey, tokenRequest);
|
|
350
|
-
return tokenRequest;
|
|
351
|
-
},
|
|
352
|
-
[acquireTokenSilent, acquireTokenRedirect, defaultScopes, account]
|
|
353
|
-
);
|
|
354
|
-
const clearSession = useCallback(async () => {
|
|
355
|
-
instance.setActiveAccount(null);
|
|
356
|
-
await instance.clearCache();
|
|
357
|
-
}, [instance]);
|
|
358
|
-
return {
|
|
359
|
-
account,
|
|
360
|
-
accounts,
|
|
361
|
-
isAuthenticated,
|
|
362
|
-
inProgress: inProgress !== InteractionStatus.None,
|
|
363
|
-
loginRedirect,
|
|
364
|
-
logoutRedirect,
|
|
365
|
-
acquireToken,
|
|
366
|
-
acquireTokenSilent,
|
|
367
|
-
acquireTokenRedirect,
|
|
368
|
-
clearSession
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// src/components/MicrosoftSignInButton.tsx
|
|
373
|
-
import { useState as useState2 } from "react";
|
|
374
|
-
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
|
|
375
|
-
function MicrosoftSignInButton({
|
|
376
|
-
text = "Sign in with Microsoft",
|
|
377
|
-
variant = "dark",
|
|
378
|
-
size = "medium",
|
|
379
|
-
scopes,
|
|
380
|
-
className = "",
|
|
381
|
-
style,
|
|
382
|
-
onSuccess,
|
|
383
|
-
onError
|
|
384
|
-
}) {
|
|
385
|
-
const { loginRedirect, inProgress } = useMsalAuth();
|
|
386
|
-
const [isLoading, setIsLoading] = useState2(false);
|
|
387
|
-
const handleClick = async () => {
|
|
388
|
-
setIsLoading(true);
|
|
389
|
-
try {
|
|
390
|
-
await loginRedirect(scopes);
|
|
391
|
-
onSuccess?.();
|
|
392
|
-
} catch (error) {
|
|
393
|
-
onError?.(error);
|
|
394
|
-
} finally {
|
|
395
|
-
setTimeout(() => setIsLoading(false), 500);
|
|
396
|
-
}
|
|
397
|
-
};
|
|
398
|
-
const sizeStyles = {
|
|
399
|
-
small: {
|
|
400
|
-
padding: "8px 16px",
|
|
401
|
-
fontSize: "14px",
|
|
402
|
-
height: "36px"
|
|
403
|
-
},
|
|
404
|
-
medium: {
|
|
405
|
-
padding: "10px 20px",
|
|
406
|
-
fontSize: "15px",
|
|
407
|
-
height: "41px"
|
|
408
|
-
},
|
|
409
|
-
large: {
|
|
410
|
-
padding: "12px 24px",
|
|
411
|
-
fontSize: "16px",
|
|
412
|
-
height: "48px"
|
|
413
|
-
}
|
|
414
|
-
};
|
|
415
|
-
const variantStyles = {
|
|
416
|
-
dark: {
|
|
417
|
-
backgroundColor: "#2F2F2F",
|
|
418
|
-
color: "#FFFFFF",
|
|
419
|
-
border: "1px solid #8C8C8C"
|
|
420
|
-
},
|
|
421
|
-
light: {
|
|
422
|
-
backgroundColor: "#FFFFFF",
|
|
423
|
-
color: "#5E5E5E",
|
|
424
|
-
border: "1px solid #8C8C8C"
|
|
425
|
-
}
|
|
426
|
-
};
|
|
427
|
-
const isDisabled = inProgress || isLoading;
|
|
428
|
-
const baseStyles = {
|
|
429
|
-
display: "inline-flex",
|
|
430
|
-
alignItems: "center",
|
|
431
|
-
justifyContent: "center",
|
|
432
|
-
gap: "12px",
|
|
433
|
-
fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
|
|
434
|
-
fontWeight: 600,
|
|
435
|
-
borderRadius: "2px",
|
|
436
|
-
cursor: isDisabled ? "not-allowed" : "pointer",
|
|
437
|
-
transition: "all 0.2s ease",
|
|
438
|
-
opacity: isDisabled ? 0.6 : 1,
|
|
439
|
-
...variantStyles[variant],
|
|
440
|
-
...sizeStyles[size],
|
|
441
|
-
...style
|
|
442
|
-
};
|
|
443
|
-
return /* @__PURE__ */ jsxs(
|
|
444
|
-
"button",
|
|
445
|
-
{
|
|
446
|
-
onClick: handleClick,
|
|
447
|
-
disabled: isDisabled,
|
|
448
|
-
className,
|
|
449
|
-
style: baseStyles,
|
|
450
|
-
"aria-label": text,
|
|
451
|
-
children: [
|
|
452
|
-
/* @__PURE__ */ jsx3(MicrosoftLogo, {}),
|
|
453
|
-
/* @__PURE__ */ jsx3("span", { children: text })
|
|
454
|
-
]
|
|
455
|
-
}
|
|
456
|
-
);
|
|
457
|
-
}
|
|
458
|
-
function MicrosoftLogo() {
|
|
459
|
-
return /* @__PURE__ */ jsxs("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
|
|
460
|
-
/* @__PURE__ */ jsx3("rect", { width: "10", height: "10", fill: "#F25022" }),
|
|
461
|
-
/* @__PURE__ */ jsx3("rect", { x: "11", width: "10", height: "10", fill: "#7FBA00" }),
|
|
462
|
-
/* @__PURE__ */ jsx3("rect", { y: "11", width: "10", height: "10", fill: "#00A4EF" }),
|
|
463
|
-
/* @__PURE__ */ jsx3("rect", { x: "11", y: "11", width: "10", height: "10", fill: "#FFB900" })
|
|
464
|
-
] });
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// src/components/SignOutButton.tsx
|
|
468
|
-
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
469
|
-
function SignOutButton({
|
|
470
|
-
text = "Sign out",
|
|
471
|
-
variant = "dark",
|
|
472
|
-
size = "medium",
|
|
473
|
-
className = "",
|
|
474
|
-
style,
|
|
475
|
-
onSuccess,
|
|
476
|
-
onError
|
|
477
|
-
}) {
|
|
478
|
-
const { logoutRedirect, inProgress } = useMsalAuth();
|
|
479
|
-
const handleClick = async () => {
|
|
480
|
-
try {
|
|
481
|
-
await logoutRedirect();
|
|
482
|
-
onSuccess?.();
|
|
483
|
-
} catch (error) {
|
|
484
|
-
onError?.(error);
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
const sizeStyles = {
|
|
488
|
-
small: {
|
|
489
|
-
padding: "8px 16px",
|
|
490
|
-
fontSize: "14px",
|
|
491
|
-
height: "36px"
|
|
492
|
-
},
|
|
493
|
-
medium: {
|
|
494
|
-
padding: "10px 20px",
|
|
495
|
-
fontSize: "15px",
|
|
496
|
-
height: "41px"
|
|
497
|
-
},
|
|
498
|
-
large: {
|
|
499
|
-
padding: "12px 24px",
|
|
500
|
-
fontSize: "16px",
|
|
501
|
-
height: "48px"
|
|
502
|
-
}
|
|
503
|
-
};
|
|
504
|
-
const variantStyles = {
|
|
505
|
-
dark: {
|
|
506
|
-
backgroundColor: "#2F2F2F",
|
|
507
|
-
color: "#FFFFFF",
|
|
508
|
-
border: "1px solid #8C8C8C"
|
|
509
|
-
},
|
|
510
|
-
light: {
|
|
511
|
-
backgroundColor: "#FFFFFF",
|
|
512
|
-
color: "#5E5E5E",
|
|
513
|
-
border: "1px solid #8C8C8C"
|
|
514
|
-
}
|
|
515
|
-
};
|
|
516
|
-
const baseStyles = {
|
|
517
|
-
display: "inline-flex",
|
|
518
|
-
alignItems: "center",
|
|
519
|
-
justifyContent: "center",
|
|
520
|
-
gap: "12px",
|
|
521
|
-
fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
|
|
522
|
-
fontWeight: 600,
|
|
523
|
-
borderRadius: "2px",
|
|
524
|
-
cursor: inProgress ? "not-allowed" : "pointer",
|
|
525
|
-
transition: "all 0.2s ease",
|
|
526
|
-
opacity: inProgress ? 0.6 : 1,
|
|
527
|
-
...variantStyles[variant],
|
|
528
|
-
...sizeStyles[size],
|
|
529
|
-
...style
|
|
530
|
-
};
|
|
531
|
-
return /* @__PURE__ */ jsxs2(
|
|
532
|
-
"button",
|
|
533
|
-
{
|
|
534
|
-
onClick: handleClick,
|
|
535
|
-
disabled: inProgress,
|
|
536
|
-
className,
|
|
537
|
-
style: baseStyles,
|
|
538
|
-
"aria-label": text,
|
|
539
|
-
children: [
|
|
540
|
-
/* @__PURE__ */ jsx4(MicrosoftLogo2, {}),
|
|
541
|
-
/* @__PURE__ */ jsx4("span", { children: text })
|
|
542
|
-
]
|
|
543
|
-
}
|
|
544
|
-
);
|
|
545
|
-
}
|
|
546
|
-
function MicrosoftLogo2() {
|
|
547
|
-
return /* @__PURE__ */ jsxs2("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
|
|
548
|
-
/* @__PURE__ */ jsx4("rect", { width: "10", height: "10", fill: "#F25022" }),
|
|
549
|
-
/* @__PURE__ */ jsx4("rect", { x: "11", width: "10", height: "10", fill: "#7FBA00" }),
|
|
550
|
-
/* @__PURE__ */ jsx4("rect", { y: "11", width: "10", height: "10", fill: "#00A4EF" }),
|
|
551
|
-
/* @__PURE__ */ jsx4("rect", { x: "11", y: "11", width: "10", height: "10", fill: "#FFB900" })
|
|
552
|
-
] });
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// src/components/UserAvatar.tsx
|
|
556
|
-
import { useEffect as useEffect3, useState as useState4 } from "react";
|
|
557
|
-
|
|
558
|
-
// src/hooks/useUserProfile.ts
|
|
559
|
-
import { useState as useState3, useEffect as useEffect2, useCallback as useCallback3 } from "react";
|
|
560
|
-
|
|
561
|
-
// src/hooks/useGraphApi.ts
|
|
562
|
-
import { useCallback as useCallback2 } from "react";
|
|
563
|
-
function useGraphApi() {
|
|
564
|
-
const { acquireToken } = useMsalAuth();
|
|
565
|
-
const request = useCallback2(
|
|
566
|
-
async (endpoint, options = {}) => {
|
|
567
|
-
const {
|
|
568
|
-
scopes = ["User.Read"],
|
|
569
|
-
version = "v1.0",
|
|
570
|
-
debug = false,
|
|
571
|
-
...fetchOptions
|
|
572
|
-
} = options;
|
|
573
|
-
try {
|
|
574
|
-
const token = await acquireToken(scopes);
|
|
575
|
-
const baseUrl = `https://graph.microsoft.com/${version}`;
|
|
576
|
-
const url = endpoint.startsWith("http") ? endpoint : `${baseUrl}${endpoint.startsWith("/") ? endpoint : `/${endpoint}`}`;
|
|
577
|
-
if (debug) {
|
|
578
|
-
console.log("[GraphAPI] Request:", { url, method: fetchOptions.method || "GET" });
|
|
579
|
-
}
|
|
580
|
-
const response = await fetch(url, {
|
|
581
|
-
...fetchOptions,
|
|
582
|
-
headers: {
|
|
583
|
-
"Authorization": `Bearer ${token}`,
|
|
584
|
-
"Content-Type": "application/json",
|
|
585
|
-
...fetchOptions.headers
|
|
586
|
-
}
|
|
587
|
-
});
|
|
588
|
-
if (!response.ok) {
|
|
589
|
-
const errorText = await response.text();
|
|
590
|
-
const errorMessage = `Graph API error (${response.status}): ${errorText}`;
|
|
591
|
-
throw new Error(errorMessage);
|
|
592
|
-
}
|
|
593
|
-
if (response.status === 204 || response.headers.get("content-length") === "0") {
|
|
594
|
-
return null;
|
|
595
|
-
}
|
|
596
|
-
const data = await response.json();
|
|
597
|
-
if (debug) {
|
|
598
|
-
console.log("[GraphAPI] Response:", data);
|
|
599
|
-
}
|
|
600
|
-
return data;
|
|
601
|
-
} catch (error) {
|
|
602
|
-
const sanitizedMessage = sanitizeError(error);
|
|
603
|
-
console.error("[GraphAPI] Request failed:", sanitizedMessage);
|
|
604
|
-
throw new Error(sanitizedMessage);
|
|
605
|
-
}
|
|
606
|
-
},
|
|
607
|
-
[acquireToken]
|
|
608
|
-
);
|
|
609
|
-
const get = useCallback2(
|
|
610
|
-
(endpoint, options = {}) => {
|
|
611
|
-
return request(endpoint, { ...options, method: "GET" });
|
|
612
|
-
},
|
|
613
|
-
[request]
|
|
614
|
-
);
|
|
615
|
-
const post = useCallback2(
|
|
616
|
-
(endpoint, body, options = {}) => {
|
|
617
|
-
return request(endpoint, {
|
|
618
|
-
...options,
|
|
619
|
-
method: "POST",
|
|
620
|
-
body: body ? JSON.stringify(body) : void 0
|
|
621
|
-
});
|
|
622
|
-
},
|
|
623
|
-
[request]
|
|
624
|
-
);
|
|
625
|
-
const put = useCallback2(
|
|
626
|
-
(endpoint, body, options = {}) => {
|
|
627
|
-
return request(endpoint, {
|
|
628
|
-
...options,
|
|
629
|
-
method: "PUT",
|
|
630
|
-
body: body ? JSON.stringify(body) : void 0
|
|
631
|
-
});
|
|
632
|
-
},
|
|
633
|
-
[request]
|
|
634
|
-
);
|
|
635
|
-
const patch = useCallback2(
|
|
636
|
-
(endpoint, body, options = {}) => {
|
|
637
|
-
return request(endpoint, {
|
|
638
|
-
...options,
|
|
639
|
-
method: "PATCH",
|
|
640
|
-
body: body ? JSON.stringify(body) : void 0
|
|
641
|
-
});
|
|
642
|
-
},
|
|
643
|
-
[request]
|
|
644
|
-
);
|
|
645
|
-
const deleteRequest = useCallback2(
|
|
646
|
-
(endpoint, options = {}) => {
|
|
647
|
-
return request(endpoint, { ...options, method: "DELETE" });
|
|
648
|
-
},
|
|
649
|
-
[request]
|
|
650
|
-
);
|
|
651
|
-
return {
|
|
652
|
-
get,
|
|
653
|
-
post,
|
|
654
|
-
put,
|
|
655
|
-
patch,
|
|
656
|
-
delete: deleteRequest,
|
|
657
|
-
request
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
// src/hooks/useUserProfile.ts
|
|
662
|
-
var profileCache = /* @__PURE__ */ new Map();
|
|
663
|
-
var CACHE_DURATION = 5 * 60 * 1e3;
|
|
664
|
-
var MAX_CACHE_SIZE = 100;
|
|
665
|
-
function enforceCacheLimit() {
|
|
666
|
-
if (profileCache.size > MAX_CACHE_SIZE) {
|
|
667
|
-
const entries = Array.from(profileCache.entries());
|
|
668
|
-
entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
|
|
669
|
-
const toRemove = entries.slice(0, profileCache.size - MAX_CACHE_SIZE);
|
|
670
|
-
toRemove.forEach(([key]) => {
|
|
671
|
-
const cached = profileCache.get(key);
|
|
672
|
-
if (cached?.data.photo) {
|
|
673
|
-
URL.revokeObjectURL(cached.data.photo);
|
|
674
|
-
}
|
|
675
|
-
profileCache.delete(key);
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
function useUserProfile() {
|
|
680
|
-
const { isAuthenticated, account } = useMsalAuth();
|
|
681
|
-
const graph = useGraphApi();
|
|
682
|
-
const [profile, setProfile] = useState3(null);
|
|
683
|
-
const [loading, setLoading] = useState3(false);
|
|
684
|
-
const [error, setError] = useState3(null);
|
|
685
|
-
const fetchProfile = useCallback3(async () => {
|
|
686
|
-
if (!isAuthenticated || !account) {
|
|
687
|
-
setProfile(null);
|
|
688
|
-
return;
|
|
689
|
-
}
|
|
690
|
-
const cacheKey = account.homeAccountId;
|
|
691
|
-
const cached = profileCache.get(cacheKey);
|
|
692
|
-
if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
|
|
693
|
-
setProfile(cached.data);
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
|
-
setLoading(true);
|
|
697
|
-
setError(null);
|
|
698
|
-
try {
|
|
699
|
-
const userData = await graph.get("/me", {
|
|
700
|
-
scopes: ["User.Read"]
|
|
701
|
-
});
|
|
702
|
-
let photoUrl;
|
|
703
|
-
try {
|
|
704
|
-
const photoBlob = await graph.get("/me/photo/$value", {
|
|
705
|
-
scopes: ["User.Read"],
|
|
706
|
-
headers: {
|
|
707
|
-
"Content-Type": "image/jpeg"
|
|
708
|
-
}
|
|
709
|
-
});
|
|
710
|
-
if (photoBlob) {
|
|
711
|
-
photoUrl = URL.createObjectURL(photoBlob);
|
|
712
|
-
}
|
|
713
|
-
} catch (photoError) {
|
|
714
|
-
console.debug("[UserProfile] Photo not available");
|
|
715
|
-
}
|
|
716
|
-
const profileData = {
|
|
717
|
-
id: userData.id,
|
|
718
|
-
displayName: userData.displayName,
|
|
719
|
-
givenName: userData.givenName,
|
|
720
|
-
surname: userData.surname,
|
|
721
|
-
userPrincipalName: userData.userPrincipalName,
|
|
722
|
-
mail: userData.mail,
|
|
723
|
-
jobTitle: userData.jobTitle,
|
|
724
|
-
officeLocation: userData.officeLocation,
|
|
725
|
-
mobilePhone: userData.mobilePhone,
|
|
726
|
-
businessPhones: userData.businessPhones,
|
|
727
|
-
photo: photoUrl
|
|
728
|
-
};
|
|
729
|
-
profileCache.set(cacheKey, {
|
|
730
|
-
data: profileData,
|
|
731
|
-
timestamp: Date.now()
|
|
732
|
-
});
|
|
733
|
-
enforceCacheLimit();
|
|
734
|
-
setProfile(profileData);
|
|
735
|
-
} catch (err) {
|
|
736
|
-
const error2 = err;
|
|
737
|
-
const sanitizedMessage = sanitizeError(error2);
|
|
738
|
-
const sanitizedError = new Error(sanitizedMessage);
|
|
739
|
-
setError(sanitizedError);
|
|
740
|
-
console.error("[UserProfile] Failed to fetch profile:", sanitizedMessage);
|
|
741
|
-
} finally {
|
|
742
|
-
setLoading(false);
|
|
743
|
-
}
|
|
744
|
-
}, [isAuthenticated, account, graph]);
|
|
745
|
-
const clearCache = useCallback3(() => {
|
|
746
|
-
if (account) {
|
|
747
|
-
const cached = profileCache.get(account.homeAccountId);
|
|
748
|
-
if (cached?.data.photo) {
|
|
749
|
-
URL.revokeObjectURL(cached.data.photo);
|
|
750
|
-
}
|
|
751
|
-
profileCache.delete(account.homeAccountId);
|
|
752
|
-
}
|
|
753
|
-
if (profile?.photo) {
|
|
754
|
-
URL.revokeObjectURL(profile.photo);
|
|
755
|
-
}
|
|
756
|
-
setProfile(null);
|
|
757
|
-
}, [account, profile]);
|
|
758
|
-
useEffect2(() => {
|
|
759
|
-
fetchProfile();
|
|
760
|
-
return () => {
|
|
761
|
-
if (profile?.photo) {
|
|
762
|
-
URL.revokeObjectURL(profile.photo);
|
|
763
|
-
}
|
|
764
|
-
};
|
|
765
|
-
}, [fetchProfile]);
|
|
766
|
-
useEffect2(() => {
|
|
767
|
-
return () => {
|
|
768
|
-
if (profile?.photo) {
|
|
769
|
-
URL.revokeObjectURL(profile.photo);
|
|
770
|
-
}
|
|
771
|
-
};
|
|
772
|
-
}, [profile?.photo]);
|
|
773
|
-
return {
|
|
774
|
-
profile,
|
|
775
|
-
loading,
|
|
776
|
-
error,
|
|
777
|
-
refetch: fetchProfile,
|
|
778
|
-
clearCache
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
// src/components/UserAvatar.tsx
|
|
783
|
-
import { jsx as jsx5 } from "react/jsx-runtime";
|
|
784
|
-
function UserAvatar({
|
|
785
|
-
size = 40,
|
|
786
|
-
className = "",
|
|
787
|
-
style,
|
|
788
|
-
showTooltip = true,
|
|
789
|
-
fallbackImage
|
|
790
|
-
}) {
|
|
791
|
-
const { profile, loading } = useUserProfile();
|
|
792
|
-
const [photoUrl, setPhotoUrl] = useState4(null);
|
|
793
|
-
const [photoError, setPhotoError] = useState4(false);
|
|
794
|
-
useEffect3(() => {
|
|
795
|
-
if (profile?.photo) {
|
|
796
|
-
setPhotoUrl(profile.photo);
|
|
797
|
-
}
|
|
798
|
-
}, [profile?.photo]);
|
|
799
|
-
const getInitials = () => {
|
|
800
|
-
if (!profile) return "?";
|
|
801
|
-
const { givenName, surname, displayName: displayName2 } = profile;
|
|
802
|
-
if (givenName && surname) {
|
|
803
|
-
return `${givenName[0]}${surname[0]}`.toUpperCase();
|
|
804
|
-
}
|
|
805
|
-
if (displayName2) {
|
|
806
|
-
const parts = displayName2.split(" ");
|
|
807
|
-
if (parts.length >= 2) {
|
|
808
|
-
return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase();
|
|
809
|
-
}
|
|
810
|
-
return displayName2.substring(0, 2).toUpperCase();
|
|
811
|
-
}
|
|
812
|
-
return "?";
|
|
813
|
-
};
|
|
814
|
-
const baseStyles = {
|
|
815
|
-
width: `${size}px`,
|
|
816
|
-
height: `${size}px`,
|
|
817
|
-
borderRadius: "50%",
|
|
818
|
-
display: "inline-flex",
|
|
819
|
-
alignItems: "center",
|
|
820
|
-
justifyContent: "center",
|
|
821
|
-
fontSize: `${size * 0.4}px`,
|
|
822
|
-
fontWeight: 600,
|
|
823
|
-
fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
|
|
824
|
-
backgroundColor: "#0078D4",
|
|
825
|
-
color: "#FFFFFF",
|
|
826
|
-
overflow: "hidden",
|
|
827
|
-
userSelect: "none",
|
|
828
|
-
...style
|
|
829
|
-
};
|
|
830
|
-
const displayName = profile?.displayName || "User";
|
|
831
|
-
if (loading) {
|
|
832
|
-
return /* @__PURE__ */ jsx5(
|
|
833
|
-
"div",
|
|
834
|
-
{
|
|
835
|
-
className,
|
|
836
|
-
style: { ...baseStyles, backgroundColor: "#E1E1E1" },
|
|
837
|
-
"aria-label": "Loading user avatar",
|
|
838
|
-
children: /* @__PURE__ */ jsx5("span", { style: { fontSize: `${size * 0.3}px` }, children: "..." })
|
|
839
|
-
}
|
|
840
|
-
);
|
|
841
|
-
}
|
|
842
|
-
if (photoUrl && !photoError) {
|
|
843
|
-
return /* @__PURE__ */ jsx5(
|
|
844
|
-
"div",
|
|
845
|
-
{
|
|
846
|
-
className,
|
|
847
|
-
style: baseStyles,
|
|
848
|
-
title: showTooltip ? displayName : void 0,
|
|
849
|
-
"aria-label": `${displayName} avatar`,
|
|
850
|
-
children: /* @__PURE__ */ jsx5(
|
|
851
|
-
"img",
|
|
852
|
-
{
|
|
853
|
-
src: photoUrl,
|
|
854
|
-
alt: displayName,
|
|
855
|
-
style: { width: "100%", height: "100%", objectFit: "cover" },
|
|
856
|
-
onError: () => {
|
|
857
|
-
setPhotoError(true);
|
|
858
|
-
if (fallbackImage) {
|
|
859
|
-
setPhotoUrl(fallbackImage);
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
)
|
|
864
|
-
}
|
|
865
|
-
);
|
|
866
|
-
}
|
|
867
|
-
return /* @__PURE__ */ jsx5(
|
|
868
|
-
"div",
|
|
869
|
-
{
|
|
870
|
-
className,
|
|
871
|
-
style: baseStyles,
|
|
872
|
-
title: showTooltip ? displayName : void 0,
|
|
873
|
-
"aria-label": `${displayName} avatar`,
|
|
874
|
-
children: getInitials()
|
|
875
|
-
}
|
|
876
|
-
);
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
// src/components/AuthStatus.tsx
|
|
880
|
-
import { Fragment as Fragment2, jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
881
|
-
function AuthStatus({
|
|
882
|
-
className = "",
|
|
883
|
-
style,
|
|
884
|
-
showDetails = false,
|
|
885
|
-
renderLoading,
|
|
886
|
-
renderAuthenticated,
|
|
887
|
-
renderUnauthenticated
|
|
888
|
-
}) {
|
|
889
|
-
const { isAuthenticated, inProgress, account } = useMsalAuth();
|
|
890
|
-
const baseStyles = {
|
|
891
|
-
display: "inline-flex",
|
|
892
|
-
alignItems: "center",
|
|
893
|
-
gap: "8px",
|
|
894
|
-
padding: "8px 12px",
|
|
895
|
-
borderRadius: "4px",
|
|
896
|
-
fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
|
|
897
|
-
fontSize: "14px",
|
|
898
|
-
fontWeight: 500,
|
|
899
|
-
...style
|
|
900
|
-
};
|
|
901
|
-
if (inProgress) {
|
|
902
|
-
if (renderLoading) {
|
|
903
|
-
return /* @__PURE__ */ jsx6(Fragment2, { children: renderLoading() });
|
|
904
|
-
}
|
|
905
|
-
return /* @__PURE__ */ jsxs3(
|
|
906
|
-
"div",
|
|
907
|
-
{
|
|
908
|
-
className,
|
|
909
|
-
style: { ...baseStyles, backgroundColor: "#FFF4CE", color: "#8A6D3B" },
|
|
910
|
-
role: "status",
|
|
911
|
-
"aria-live": "polite",
|
|
912
|
-
children: [
|
|
913
|
-
/* @__PURE__ */ jsx6(StatusIndicator, { color: "#FFA500" }),
|
|
914
|
-
/* @__PURE__ */ jsx6("span", { children: "Loading..." })
|
|
915
|
-
]
|
|
916
|
-
}
|
|
917
|
-
);
|
|
918
|
-
}
|
|
919
|
-
if (isAuthenticated) {
|
|
920
|
-
const username = account?.username || account?.name || "User";
|
|
921
|
-
if (renderAuthenticated) {
|
|
922
|
-
return /* @__PURE__ */ jsx6(Fragment2, { children: renderAuthenticated(username) });
|
|
923
|
-
}
|
|
924
|
-
return /* @__PURE__ */ jsxs3(
|
|
925
|
-
"div",
|
|
926
|
-
{
|
|
927
|
-
className,
|
|
928
|
-
style: { ...baseStyles, backgroundColor: "#D4EDDA", color: "#155724" },
|
|
929
|
-
role: "status",
|
|
930
|
-
"aria-live": "polite",
|
|
931
|
-
children: [
|
|
932
|
-
/* @__PURE__ */ jsx6(StatusIndicator, { color: "#28A745" }),
|
|
933
|
-
/* @__PURE__ */ jsx6("span", { children: showDetails ? `Authenticated as ${username}` : "Authenticated" })
|
|
934
|
-
]
|
|
935
|
-
}
|
|
936
|
-
);
|
|
937
|
-
}
|
|
938
|
-
if (renderUnauthenticated) {
|
|
939
|
-
return /* @__PURE__ */ jsx6(Fragment2, { children: renderUnauthenticated() });
|
|
940
|
-
}
|
|
941
|
-
return /* @__PURE__ */ jsxs3(
|
|
942
|
-
"div",
|
|
943
|
-
{
|
|
944
|
-
className,
|
|
945
|
-
style: { ...baseStyles, backgroundColor: "#F8D7DA", color: "#721C24" },
|
|
946
|
-
role: "status",
|
|
947
|
-
"aria-live": "polite",
|
|
948
|
-
children: [
|
|
949
|
-
/* @__PURE__ */ jsx6(StatusIndicator, { color: "#DC3545" }),
|
|
950
|
-
/* @__PURE__ */ jsx6("span", { children: "Not authenticated" })
|
|
951
|
-
]
|
|
952
|
-
}
|
|
953
|
-
);
|
|
954
|
-
}
|
|
955
|
-
function StatusIndicator({ color }) {
|
|
956
|
-
return /* @__PURE__ */ jsx6("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsx6("circle", { cx: "4", cy: "4", r: "4", fill: color }) });
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
// src/components/AuthGuard.tsx
|
|
960
|
-
import { useEffect as useEffect4 } from "react";
|
|
961
|
-
import { Fragment as Fragment3, jsx as jsx7 } from "react/jsx-runtime";
|
|
962
|
-
function AuthGuard({
|
|
963
|
-
children,
|
|
964
|
-
loadingComponent,
|
|
965
|
-
fallbackComponent,
|
|
966
|
-
scopes,
|
|
967
|
-
onAuthRequired
|
|
968
|
-
}) {
|
|
969
|
-
const { isAuthenticated, inProgress, loginRedirect } = useMsalAuth();
|
|
970
|
-
useEffect4(() => {
|
|
971
|
-
if (!isAuthenticated && !inProgress) {
|
|
972
|
-
onAuthRequired?.();
|
|
973
|
-
const login = async () => {
|
|
974
|
-
try {
|
|
975
|
-
await loginRedirect(scopes);
|
|
976
|
-
} catch (error) {
|
|
977
|
-
console.error("[AuthGuard] Authentication failed:", error);
|
|
978
|
-
}
|
|
979
|
-
};
|
|
980
|
-
login();
|
|
981
|
-
}
|
|
982
|
-
}, [isAuthenticated, inProgress, scopes, loginRedirect, onAuthRequired]);
|
|
983
|
-
if (inProgress) {
|
|
984
|
-
return /* @__PURE__ */ jsx7(Fragment3, { children: loadingComponent || /* @__PURE__ */ jsx7("div", { children: "Authenticating..." }) });
|
|
985
|
-
}
|
|
986
|
-
if (!isAuthenticated) {
|
|
987
|
-
return /* @__PURE__ */ jsx7(Fragment3, { children: fallbackComponent || /* @__PURE__ */ jsx7("div", { children: "Redirecting to login..." }) });
|
|
988
|
-
}
|
|
989
|
-
return /* @__PURE__ */ jsx7(Fragment3, { children });
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
// src/components/ErrorBoundary.tsx
|
|
993
|
-
import { Component } from "react";
|
|
994
|
-
import { jsx as jsx8, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
995
|
-
var ErrorBoundary = class extends Component {
|
|
996
|
-
constructor(props) {
|
|
997
|
-
super(props);
|
|
998
|
-
this.reset = () => {
|
|
999
|
-
this.setState({
|
|
1000
|
-
hasError: false,
|
|
1001
|
-
error: null
|
|
1002
|
-
});
|
|
1003
|
-
};
|
|
1004
|
-
this.state = {
|
|
1005
|
-
hasError: false,
|
|
1006
|
-
error: null
|
|
1007
|
-
};
|
|
1008
|
-
}
|
|
1009
|
-
static getDerivedStateFromError(error) {
|
|
1010
|
-
return {
|
|
1011
|
-
hasError: true,
|
|
1012
|
-
error
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
componentDidCatch(error, errorInfo) {
|
|
1016
|
-
const { onError, debug } = this.props;
|
|
1017
|
-
if (debug) {
|
|
1018
|
-
console.error("[ErrorBoundary] Caught error:", error);
|
|
1019
|
-
console.error("[ErrorBoundary] Error info:", errorInfo);
|
|
1020
|
-
}
|
|
1021
|
-
onError?.(error, errorInfo);
|
|
1022
|
-
}
|
|
1023
|
-
render() {
|
|
1024
|
-
const { hasError, error } = this.state;
|
|
1025
|
-
const { children, fallback } = this.props;
|
|
1026
|
-
if (hasError && error) {
|
|
1027
|
-
if (fallback) {
|
|
1028
|
-
return fallback(error, this.reset);
|
|
1029
|
-
}
|
|
1030
|
-
return /* @__PURE__ */ jsxs4(
|
|
1031
|
-
"div",
|
|
1032
|
-
{
|
|
1033
|
-
style: {
|
|
1034
|
-
padding: "20px",
|
|
1035
|
-
margin: "20px",
|
|
1036
|
-
border: "1px solid #DC3545",
|
|
1037
|
-
borderRadius: "4px",
|
|
1038
|
-
backgroundColor: "#F8D7DA",
|
|
1039
|
-
color: "#721C24",
|
|
1040
|
-
fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'
|
|
1041
|
-
},
|
|
1042
|
-
children: [
|
|
1043
|
-
/* @__PURE__ */ jsx8("h2", { style: { margin: "0 0 10px 0", fontSize: "18px" }, children: "Authentication Error" }),
|
|
1044
|
-
/* @__PURE__ */ jsx8("p", { style: { margin: "0 0 10px 0" }, children: error.message }),
|
|
1045
|
-
/* @__PURE__ */ jsx8(
|
|
1046
|
-
"button",
|
|
1047
|
-
{
|
|
1048
|
-
onClick: this.reset,
|
|
1049
|
-
style: {
|
|
1050
|
-
padding: "8px 16px",
|
|
1051
|
-
backgroundColor: "#DC3545",
|
|
1052
|
-
color: "#FFFFFF",
|
|
1053
|
-
border: "none",
|
|
1054
|
-
borderRadius: "4px",
|
|
1055
|
-
cursor: "pointer",
|
|
1056
|
-
fontSize: "14px",
|
|
1057
|
-
fontWeight: 600
|
|
1058
|
-
},
|
|
1059
|
-
children: "Try Again"
|
|
1060
|
-
}
|
|
1061
|
-
)
|
|
1062
|
-
]
|
|
1063
|
-
}
|
|
1064
|
-
);
|
|
1065
|
-
}
|
|
1066
|
-
return children;
|
|
1067
|
-
}
|
|
1068
|
-
};
|
|
1069
|
-
|
|
1070
|
-
// src/hooks/useRoles.ts
|
|
1071
|
-
import { useState as useState5, useEffect as useEffect5, useCallback as useCallback4 } from "react";
|
|
1072
|
-
var rolesCache = /* @__PURE__ */ new Map();
|
|
1073
|
-
var CACHE_DURATION2 = 5 * 60 * 1e3;
|
|
1074
|
-
var MAX_CACHE_SIZE2 = 100;
|
|
1075
|
-
function clearRolesCache(accountId) {
|
|
1076
|
-
if (accountId) {
|
|
1077
|
-
rolesCache.delete(accountId);
|
|
1078
|
-
} else {
|
|
1079
|
-
rolesCache.clear();
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
function enforceCacheLimit2() {
|
|
1083
|
-
if (rolesCache.size > MAX_CACHE_SIZE2) {
|
|
1084
|
-
const entries = Array.from(rolesCache.entries());
|
|
1085
|
-
entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
|
|
1086
|
-
const toRemove = entries.slice(0, rolesCache.size - MAX_CACHE_SIZE2);
|
|
1087
|
-
toRemove.forEach(([key]) => rolesCache.delete(key));
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
function useRoles() {
|
|
1091
|
-
const { isAuthenticated, account } = useMsalAuth();
|
|
1092
|
-
const graph = useGraphApi();
|
|
1093
|
-
const [roles, setRoles] = useState5([]);
|
|
1094
|
-
const [groups, setGroups] = useState5([]);
|
|
1095
|
-
const [loading, setLoading] = useState5(false);
|
|
1096
|
-
const [error, setError] = useState5(null);
|
|
1097
|
-
const fetchRolesAndGroups = useCallback4(async () => {
|
|
1098
|
-
if (!isAuthenticated || !account) {
|
|
1099
|
-
setRoles([]);
|
|
1100
|
-
setGroups([]);
|
|
1101
|
-
return;
|
|
1102
|
-
}
|
|
1103
|
-
const cacheKey = account.homeAccountId;
|
|
1104
|
-
const cached = rolesCache.get(cacheKey);
|
|
1105
|
-
if (cached && Date.now() - cached.timestamp < CACHE_DURATION2) {
|
|
1106
|
-
setRoles(cached.roles);
|
|
1107
|
-
setGroups(cached.groups);
|
|
1108
|
-
return;
|
|
1109
|
-
}
|
|
1110
|
-
setLoading(true);
|
|
1111
|
-
setError(null);
|
|
1112
|
-
try {
|
|
1113
|
-
const idTokenClaims = account.idTokenClaims;
|
|
1114
|
-
const tokenRoles = idTokenClaims?.roles || [];
|
|
1115
|
-
const groupsResponse = await graph.get("/me/memberOf", {
|
|
1116
|
-
scopes: ["User.Read", "Directory.Read.All"]
|
|
1117
|
-
});
|
|
1118
|
-
const userGroups = groupsResponse.value.map((group) => group.id);
|
|
1119
|
-
rolesCache.set(cacheKey, {
|
|
1120
|
-
roles: tokenRoles,
|
|
1121
|
-
groups: userGroups,
|
|
1122
|
-
timestamp: Date.now()
|
|
1123
|
-
});
|
|
1124
|
-
enforceCacheLimit2();
|
|
1125
|
-
setRoles(tokenRoles);
|
|
1126
|
-
setGroups(userGroups);
|
|
1127
|
-
} catch (err) {
|
|
1128
|
-
const error2 = err;
|
|
1129
|
-
const sanitizedMessage = sanitizeError(error2);
|
|
1130
|
-
const sanitizedError = new Error(sanitizedMessage);
|
|
1131
|
-
setError(sanitizedError);
|
|
1132
|
-
console.error("[Roles] Failed to fetch roles/groups:", sanitizedMessage);
|
|
1133
|
-
const idTokenClaims = account.idTokenClaims;
|
|
1134
|
-
const tokenRoles = idTokenClaims?.roles || [];
|
|
1135
|
-
setRoles(tokenRoles);
|
|
1136
|
-
} finally {
|
|
1137
|
-
setLoading(false);
|
|
1138
|
-
}
|
|
1139
|
-
}, [isAuthenticated, account, graph]);
|
|
1140
|
-
const hasRole = useCallback4(
|
|
1141
|
-
(role) => {
|
|
1142
|
-
return roles.includes(role);
|
|
1143
|
-
},
|
|
1144
|
-
[roles]
|
|
1145
|
-
);
|
|
1146
|
-
const hasGroup = useCallback4(
|
|
1147
|
-
(groupId) => {
|
|
1148
|
-
return groups.includes(groupId);
|
|
1149
|
-
},
|
|
1150
|
-
[groups]
|
|
1151
|
-
);
|
|
1152
|
-
const hasAnyRole = useCallback4(
|
|
1153
|
-
(checkRoles) => {
|
|
1154
|
-
return checkRoles.some((role) => roles.includes(role));
|
|
1155
|
-
},
|
|
1156
|
-
[roles]
|
|
1157
|
-
);
|
|
1158
|
-
const hasAllRoles = useCallback4(
|
|
1159
|
-
(checkRoles) => {
|
|
1160
|
-
return checkRoles.every((role) => roles.includes(role));
|
|
1161
|
-
},
|
|
1162
|
-
[roles]
|
|
1163
|
-
);
|
|
1164
|
-
useEffect5(() => {
|
|
1165
|
-
fetchRolesAndGroups();
|
|
1166
|
-
return () => {
|
|
1167
|
-
if (account) {
|
|
1168
|
-
clearRolesCache(account.homeAccountId);
|
|
1169
|
-
}
|
|
1170
|
-
};
|
|
1171
|
-
}, [fetchRolesAndGroups, account]);
|
|
1172
|
-
return {
|
|
1173
|
-
roles,
|
|
1174
|
-
groups,
|
|
1175
|
-
loading,
|
|
1176
|
-
error,
|
|
1177
|
-
hasRole,
|
|
1178
|
-
hasGroup,
|
|
1179
|
-
hasAnyRole,
|
|
1180
|
-
hasAllRoles,
|
|
1181
|
-
refetch: fetchRolesAndGroups
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
// src/utils/withAuth.tsx
|
|
1186
|
-
import { jsx as jsx9 } from "react/jsx-runtime";
|
|
1187
|
-
function withAuth(Component2, options = {}) {
|
|
1188
|
-
const { displayName, ...guardProps } = options;
|
|
1189
|
-
const WrappedComponent = (props) => {
|
|
1190
|
-
return /* @__PURE__ */ jsx9(AuthGuard, { ...guardProps, children: /* @__PURE__ */ jsx9(Component2, { ...props }) });
|
|
1191
|
-
};
|
|
1192
|
-
WrappedComponent.displayName = displayName || `withAuth(${Component2.displayName || Component2.name || "Component"})`;
|
|
1193
|
-
return WrappedComponent;
|
|
1194
|
-
}
|
|
1195
|
-
|
|
1196
|
-
// src/utils/tokenRetry.ts
|
|
1197
|
-
async function retryWithBackoff(fn, config = {}) {
|
|
1198
|
-
const {
|
|
1199
|
-
maxRetries = 3,
|
|
1200
|
-
initialDelay = 1e3,
|
|
1201
|
-
maxDelay = 1e4,
|
|
1202
|
-
backoffMultiplier = 2,
|
|
1203
|
-
debug = false
|
|
1204
|
-
} = config;
|
|
1205
|
-
let lastError;
|
|
1206
|
-
let delay = initialDelay;
|
|
1207
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1208
|
-
try {
|
|
1209
|
-
if (debug && attempt > 0) {
|
|
1210
|
-
console.log(`[TokenRetry] Attempt ${attempt + 1}/${maxRetries + 1}`);
|
|
1211
|
-
}
|
|
1212
|
-
return await fn();
|
|
1213
|
-
} catch (error) {
|
|
1214
|
-
lastError = error;
|
|
1215
|
-
if (attempt === maxRetries) {
|
|
1216
|
-
if (debug) {
|
|
1217
|
-
console.error("[TokenRetry] All retry attempts failed");
|
|
1218
|
-
}
|
|
1219
|
-
break;
|
|
1220
|
-
}
|
|
1221
|
-
if (!isRetryableError(error)) {
|
|
1222
|
-
if (debug) {
|
|
1223
|
-
console.log("[TokenRetry] Non-retryable error, aborting");
|
|
1224
|
-
}
|
|
1225
|
-
throw error;
|
|
1226
|
-
}
|
|
1227
|
-
if (debug) {
|
|
1228
|
-
console.warn(`[TokenRetry] Attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
|
|
1229
|
-
}
|
|
1230
|
-
await sleep(delay);
|
|
1231
|
-
delay = Math.min(delay * backoffMultiplier, maxDelay);
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
throw lastError;
|
|
1235
|
-
}
|
|
1236
|
-
function isRetryableError(error) {
|
|
1237
|
-
const message = error.message.toLowerCase();
|
|
1238
|
-
if (message.includes("network") || message.includes("timeout") || message.includes("fetch") || message.includes("connection")) {
|
|
1239
|
-
return true;
|
|
1240
|
-
}
|
|
1241
|
-
if (message.includes("500") || message.includes("502") || message.includes("503")) {
|
|
1242
|
-
return true;
|
|
1243
|
-
}
|
|
1244
|
-
if (message.includes("429") || message.includes("rate limit")) {
|
|
1245
|
-
return true;
|
|
1246
|
-
}
|
|
1247
|
-
if (message.includes("token") && message.includes("expired")) {
|
|
1248
|
-
return true;
|
|
1249
|
-
}
|
|
1250
|
-
return false;
|
|
1251
|
-
}
|
|
1252
|
-
function sleep(ms) {
|
|
1253
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1254
|
-
}
|
|
1255
|
-
function createRetryWrapper(fn, config = {}) {
|
|
1256
|
-
return (...args) => {
|
|
1257
|
-
return retryWithBackoff(() => fn(...args), config);
|
|
1258
|
-
};
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
// src/utils/debugLogger.ts
|
|
1262
|
-
var DebugLogger = class {
|
|
1263
|
-
constructor(config = {}) {
|
|
1264
|
-
this.logHistory = [];
|
|
1265
|
-
this.performanceTimings = /* @__PURE__ */ new Map();
|
|
1266
|
-
this.config = {
|
|
1267
|
-
enabled: config.enabled ?? false,
|
|
1268
|
-
prefix: config.prefix ?? "[MSAL-Next]",
|
|
1269
|
-
showTimestamp: config.showTimestamp ?? true,
|
|
1270
|
-
level: config.level ?? "info",
|
|
1271
|
-
enablePerformance: config.enablePerformance ?? false,
|
|
1272
|
-
enableNetworkLogs: config.enableNetworkLogs ?? false,
|
|
1273
|
-
maxHistorySize: config.maxHistorySize ?? 100
|
|
1274
|
-
};
|
|
1275
|
-
}
|
|
1276
|
-
shouldLog(level) {
|
|
1277
|
-
if (!this.config.enabled) return false;
|
|
1278
|
-
const levels = ["error", "warn", "info", "debug"];
|
|
1279
|
-
const currentLevelIndex = levels.indexOf(this.config.level);
|
|
1280
|
-
const messageLevelIndex = levels.indexOf(level);
|
|
1281
|
-
return messageLevelIndex <= currentLevelIndex;
|
|
1282
|
-
}
|
|
1283
|
-
formatMessage(level, message, data) {
|
|
1284
|
-
const timestamp = this.config.showTimestamp ? `[${(/* @__PURE__ */ new Date()).toISOString()}]` : "";
|
|
1285
|
-
const prefix = this.config.prefix;
|
|
1286
|
-
const levelStr = `[${level.toUpperCase()}]`;
|
|
1287
|
-
let formatted = `${timestamp} ${prefix} ${levelStr} ${message}`;
|
|
1288
|
-
if (data !== void 0) {
|
|
1289
|
-
formatted += "\n" + JSON.stringify(data, null, 2);
|
|
1290
|
-
}
|
|
1291
|
-
return formatted;
|
|
1292
|
-
}
|
|
1293
|
-
addToHistory(level, message, data) {
|
|
1294
|
-
if (this.logHistory.length >= this.config.maxHistorySize) {
|
|
1295
|
-
this.logHistory.shift();
|
|
1296
|
-
}
|
|
1297
|
-
this.logHistory.push({
|
|
1298
|
-
timestamp: Date.now(),
|
|
1299
|
-
level,
|
|
1300
|
-
message,
|
|
1301
|
-
data
|
|
1302
|
-
});
|
|
1303
|
-
}
|
|
1304
|
-
error(message, data) {
|
|
1305
|
-
if (this.shouldLog("error")) {
|
|
1306
|
-
console.error(this.formatMessage("error", message, data));
|
|
1307
|
-
this.addToHistory("error", message, data);
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
warn(message, data) {
|
|
1311
|
-
if (this.shouldLog("warn")) {
|
|
1312
|
-
console.warn(this.formatMessage("warn", message, data));
|
|
1313
|
-
this.addToHistory("warn", message, data);
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
info(message, data) {
|
|
1317
|
-
if (this.shouldLog("info")) {
|
|
1318
|
-
console.info(this.formatMessage("info", message, data));
|
|
1319
|
-
this.addToHistory("info", message, data);
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
debug(message, data) {
|
|
1323
|
-
if (this.shouldLog("debug")) {
|
|
1324
|
-
console.debug(this.formatMessage("debug", message, data));
|
|
1325
|
-
this.addToHistory("debug", message, data);
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
group(label) {
|
|
1329
|
-
if (this.config.enabled) {
|
|
1330
|
-
console.group(`${this.config.prefix} ${label}`);
|
|
1331
|
-
}
|
|
1332
|
-
}
|
|
1333
|
-
groupEnd() {
|
|
1334
|
-
if (this.config.enabled) {
|
|
1335
|
-
console.groupEnd();
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1338
|
-
/**
|
|
1339
|
-
* Start performance timing for an operation
|
|
1340
|
-
*/
|
|
1341
|
-
startTiming(operation) {
|
|
1342
|
-
if (this.config.enablePerformance) {
|
|
1343
|
-
this.performanceTimings.set(operation, {
|
|
1344
|
-
operation,
|
|
1345
|
-
startTime: performance.now()
|
|
1346
|
-
});
|
|
1347
|
-
this.debug(`\u23F1\uFE0F Started: ${operation}`);
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
/**
|
|
1351
|
-
* End performance timing for an operation
|
|
1352
|
-
*/
|
|
1353
|
-
endTiming(operation) {
|
|
1354
|
-
if (this.config.enablePerformance) {
|
|
1355
|
-
const timing = this.performanceTimings.get(operation);
|
|
1356
|
-
if (timing) {
|
|
1357
|
-
timing.endTime = performance.now();
|
|
1358
|
-
timing.duration = timing.endTime - timing.startTime;
|
|
1359
|
-
this.info(`\u23F1\uFE0F Completed: ${operation} (${timing.duration.toFixed(2)}ms)`);
|
|
1360
|
-
return timing.duration;
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
return void 0;
|
|
1364
|
-
}
|
|
1365
|
-
/**
|
|
1366
|
-
* Log network request
|
|
1367
|
-
*/
|
|
1368
|
-
logRequest(method, url, options) {
|
|
1369
|
-
if (this.config.enableNetworkLogs) {
|
|
1370
|
-
this.debug(`\u{1F310} ${method} ${url}`, options);
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
/**
|
|
1374
|
-
* Log network response
|
|
1375
|
-
*/
|
|
1376
|
-
logResponse(method, url, status, data) {
|
|
1377
|
-
if (this.config.enableNetworkLogs) {
|
|
1378
|
-
const statusEmoji = status >= 200 && status < 300 ? "\u2705" : "\u274C";
|
|
1379
|
-
this.debug(`${statusEmoji} ${method} ${url} - ${status}`, data);
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
/**
|
|
1383
|
-
* Get log history
|
|
1384
|
-
*/
|
|
1385
|
-
getHistory() {
|
|
1386
|
-
return [...this.logHistory];
|
|
1387
|
-
}
|
|
1388
|
-
/**
|
|
1389
|
-
* Get performance timings
|
|
1390
|
-
*/
|
|
1391
|
-
getPerformanceTimings() {
|
|
1392
|
-
return Array.from(this.performanceTimings.values());
|
|
1393
|
-
}
|
|
1394
|
-
/**
|
|
1395
|
-
* Clear log history
|
|
1396
|
-
*/
|
|
1397
|
-
clearHistory() {
|
|
1398
|
-
this.logHistory = [];
|
|
1399
|
-
}
|
|
1400
|
-
/**
|
|
1401
|
-
* Clear performance timings
|
|
1402
|
-
*/
|
|
1403
|
-
clearTimings() {
|
|
1404
|
-
this.performanceTimings.clear();
|
|
1405
|
-
}
|
|
1406
|
-
/**
|
|
1407
|
-
* Export logs as JSON
|
|
1408
|
-
*/
|
|
1409
|
-
exportLogs() {
|
|
1410
|
-
return JSON.stringify({
|
|
1411
|
-
config: this.config,
|
|
1412
|
-
history: this.logHistory,
|
|
1413
|
-
performanceTimings: Array.from(this.performanceTimings.values()),
|
|
1414
|
-
exportedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1415
|
-
}, null, 2);
|
|
1416
|
-
}
|
|
1417
|
-
/**
|
|
1418
|
-
* Download logs as a file
|
|
1419
|
-
*/
|
|
1420
|
-
downloadLogs(filename = "msal-next-debug-logs.json") {
|
|
1421
|
-
if (typeof window === "undefined") return;
|
|
1422
|
-
const logs = this.exportLogs();
|
|
1423
|
-
const blob = new Blob([logs], { type: "application/json" });
|
|
1424
|
-
const url = URL.createObjectURL(blob);
|
|
1425
|
-
const a = document.createElement("a");
|
|
1426
|
-
a.href = url;
|
|
1427
|
-
a.download = filename;
|
|
1428
|
-
a.click();
|
|
1429
|
-
URL.revokeObjectURL(url);
|
|
1430
|
-
}
|
|
1431
|
-
setEnabled(enabled) {
|
|
1432
|
-
this.config.enabled = enabled;
|
|
1433
|
-
}
|
|
1434
|
-
setLevel(level) {
|
|
1435
|
-
if (level) {
|
|
1436
|
-
this.config.level = level;
|
|
1437
|
-
}
|
|
1438
|
-
}
|
|
1439
|
-
};
|
|
1440
|
-
var globalLogger = null;
|
|
1441
|
-
function getDebugLogger(config) {
|
|
1442
|
-
if (!globalLogger) {
|
|
1443
|
-
globalLogger = new DebugLogger(config);
|
|
1444
|
-
} else if (config) {
|
|
1445
|
-
if (config.enabled !== void 0) {
|
|
1446
|
-
globalLogger.setEnabled(config.enabled);
|
|
1447
|
-
}
|
|
1448
|
-
if (config.level) {
|
|
1449
|
-
globalLogger.setLevel(config.level);
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
return globalLogger;
|
|
1453
|
-
}
|
|
1454
|
-
function createScopedLogger(scope, config) {
|
|
1455
|
-
return new DebugLogger({
|
|
1456
|
-
...config,
|
|
1457
|
-
prefix: `[MSAL-Next:${scope}]`
|
|
1458
|
-
});
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
// src/middleware/createAuthMiddleware.ts
|
|
1462
|
-
import { NextResponse } from "next/server";
|
|
1463
|
-
function createAuthMiddleware(config = {}) {
|
|
1464
|
-
const {
|
|
1465
|
-
protectedRoutes = [],
|
|
1466
|
-
publicOnlyRoutes = [],
|
|
1467
|
-
loginPath = "/login",
|
|
1468
|
-
redirectAfterLogin = "/",
|
|
1469
|
-
sessionCookie = "msal.account",
|
|
1470
|
-
isAuthenticated: customAuthCheck,
|
|
1471
|
-
debug = false
|
|
1472
|
-
} = config;
|
|
1473
|
-
return async function authMiddleware(request) {
|
|
1474
|
-
const { pathname } = request.nextUrl;
|
|
1475
|
-
if (debug) {
|
|
1476
|
-
console.log("[AuthMiddleware] Processing:", pathname);
|
|
1477
|
-
}
|
|
1478
|
-
let authenticated = false;
|
|
1479
|
-
if (customAuthCheck) {
|
|
1480
|
-
authenticated = await customAuthCheck(request);
|
|
1481
|
-
} else {
|
|
1482
|
-
const sessionData = request.cookies.get(sessionCookie);
|
|
1483
|
-
authenticated = !!sessionData?.value;
|
|
1484
|
-
}
|
|
1485
|
-
if (debug) {
|
|
1486
|
-
console.log("[AuthMiddleware] Authenticated:", authenticated);
|
|
1487
|
-
}
|
|
1488
|
-
const isProtectedRoute = protectedRoutes.some(
|
|
1489
|
-
(route) => pathname.startsWith(route)
|
|
1490
|
-
);
|
|
1491
|
-
const isPublicOnlyRoute = publicOnlyRoutes.some(
|
|
1492
|
-
(route) => pathname.startsWith(route)
|
|
1493
|
-
);
|
|
1494
|
-
if (isProtectedRoute && !authenticated) {
|
|
1495
|
-
if (debug) {
|
|
1496
|
-
console.log("[AuthMiddleware] Redirecting to login");
|
|
1497
|
-
}
|
|
1498
|
-
const url = request.nextUrl.clone();
|
|
1499
|
-
url.pathname = loginPath;
|
|
1500
|
-
url.searchParams.set("returnUrl", pathname);
|
|
1501
|
-
return NextResponse.redirect(url);
|
|
1502
|
-
}
|
|
1503
|
-
if (isPublicOnlyRoute && authenticated) {
|
|
1504
|
-
if (debug) {
|
|
1505
|
-
console.log("[AuthMiddleware] Redirecting to home");
|
|
1506
|
-
}
|
|
1507
|
-
const returnUrl = request.nextUrl.searchParams.get("returnUrl");
|
|
1508
|
-
const url = request.nextUrl.clone();
|
|
1509
|
-
url.pathname = returnUrl || redirectAfterLogin;
|
|
1510
|
-
url.searchParams.delete("returnUrl");
|
|
1511
|
-
return NextResponse.redirect(url);
|
|
1512
|
-
}
|
|
1513
|
-
const response = NextResponse.next();
|
|
1514
|
-
if (authenticated) {
|
|
1515
|
-
response.headers.set("x-msal-authenticated", "true");
|
|
1516
|
-
try {
|
|
1517
|
-
const sessionData = request.cookies.get(sessionCookie);
|
|
1518
|
-
if (sessionData?.value) {
|
|
1519
|
-
const account = safeJsonParse(sessionData.value, isValidAccountData);
|
|
1520
|
-
if (account?.username) {
|
|
1521
|
-
response.headers.set("x-msal-username", account.username);
|
|
1522
|
-
}
|
|
1523
|
-
}
|
|
1524
|
-
} catch (error) {
|
|
1525
|
-
if (debug) {
|
|
1526
|
-
console.warn("[AuthMiddleware] Failed to parse session data");
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
}
|
|
1530
|
-
return response;
|
|
1531
|
-
};
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
// src/client.ts
|
|
1535
|
-
import { useMsal as useMsal2, useIsAuthenticated, useAccount as useAccount2 } from "@azure/msal-react";
|
|
1536
|
-
export {
|
|
1537
|
-
AuthGuard,
|
|
1538
|
-
AuthStatus,
|
|
1539
|
-
ErrorBoundary,
|
|
1540
|
-
MSALProvider,
|
|
1541
|
-
MicrosoftSignInButton,
|
|
1542
|
-
MsalAuthProvider,
|
|
1543
|
-
SignOutButton,
|
|
1544
|
-
UserAvatar,
|
|
1545
|
-
createAuthMiddleware,
|
|
1546
|
-
createMsalConfig,
|
|
1547
|
-
createRetryWrapper,
|
|
1548
|
-
createScopedLogger,
|
|
1549
|
-
getDebugLogger,
|
|
1550
|
-
getMsalInstance,
|
|
1551
|
-
isValidAccountData,
|
|
1552
|
-
isValidRedirectUri,
|
|
1553
|
-
isValidScope,
|
|
1554
|
-
retryWithBackoff,
|
|
1555
|
-
safeJsonParse,
|
|
1556
|
-
sanitizeError,
|
|
1557
|
-
useAccount2 as useAccount,
|
|
1558
|
-
useGraphApi,
|
|
1559
|
-
useIsAuthenticated,
|
|
1560
|
-
useMsal2 as useMsal,
|
|
1561
|
-
useMsalAuth,
|
|
1562
|
-
useRoles,
|
|
1563
|
-
useUserProfile,
|
|
1564
|
-
validateScopes,
|
|
1565
|
-
withAuth
|
|
1566
|
-
};
|
|
1
|
+
import {MsalProvider,useMsal,useAccount}from'@azure/msal-react';export{useAccount,useIsAuthenticated,useMsal}from'@azure/msal-react';import {LogLevel,PublicClientApplication,EventType,InteractionStatus}from'@azure/msal-browser';import {useState,useRef,useEffect,useMemo,useCallback,Component}from'react';import {jsx,Fragment,jsxs}from'react/jsx-runtime';import {NextResponse}from'next/server';function q(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function _(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function v(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function G(r,e){try{let t=new URL(r);return e.some(o=>{let i=new URL(o);return t.origin===i.origin})}catch{return false}}function ne(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function Ae(r){return Array.isArray(r)&&r.every(ne)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:i,postLogoutRedirectUri:a,cacheLocation:p="sessionStorage",storeAuthStateInCookie:u=false,navigateToLoginRequestUrl:c=false,enableLogging:n=false,loggerCallback:h,allowedRedirectUris:g}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let l=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},s=typeof window<"u"?window.location.origin:"http://localhost:3000",m=i||s;if(g&&g.length>0){if(!G(m,g))throw new Error(`@chemmangat/msal-next: redirectUri "${m}" is not in the allowed list`);let d=a||m;if(!G(d,g))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${d}" is not in the allowed list`)}return {auth:{clientId:e,authority:l(),redirectUri:m,postLogoutRedirectUri:a||m,navigateToLoginRequestUrl:c},cache:{cacheLocation:p,storeAuthStateInCookie:u},system:{loggerOptions:{loggerCallback:h||((d,y,R)=>{if(!(R||!n))switch(d){case LogLevel.Error:console.error("[MSAL]",y);break;case LogLevel.Warning:console.warn("[MSAL]",y);break;case LogLevel.Info:console.info("[MSAL]",y);break;case LogLevel.Verbose:console.debug("[MSAL]",y);break}}),logLevel:n?LogLevel.Verbose:LogLevel.Error}}}}var se=null;function Pe(){return se}function V({children:r,loadingComponent:e,onInitialized:t,...o}){let[i,a]=useState(null),p=useRef(null);return useEffect(()=>{if(typeof window>"u"||p.current)return;(async()=>{try{let c=H(o),n=new PublicClientApplication(c);await n.initialize();try{let l=await n.handleRedirectPromise();l&&(o.enableLogging&&console.log("[MSAL] Redirect authentication successful"),l.account&&n.setActiveAccount(l.account),window.location.hash&&window.history.replaceState(null,"",window.location.pathname+window.location.search));}catch(l){l?.errorCode==="no_token_request_cache_error"?o.enableLogging&&console.log("[MSAL] No pending redirect found (this is normal)"):l?.errorCode==="user_cancelled"?o.enableLogging&&console.log("[MSAL] User cancelled authentication"):console.error("[MSAL] Redirect handling error:",l),window.location.hash&&(window.location.hash.includes("code=")||window.location.hash.includes("error="))&&window.history.replaceState(null,"",window.location.pathname+window.location.search);}let h=n.getAllAccounts();h.length>0&&!n.getActiveAccount()&&n.setActiveAccount(h[0]);let g=o.enableLogging||!1;n.addEventCallback(l=>{if(l.eventType===EventType.LOGIN_SUCCESS){let s=l.payload;s?.account&&n.setActiveAccount(s.account),g&&console.log("[MSAL] Login successful:",s.account?.username);}if(l.eventType===EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",l.error),l.eventType===EventType.LOGOUT_SUCCESS&&(n.setActiveAccount(null),g&&console.log("[MSAL] Logout successful")),l.eventType===EventType.ACQUIRE_TOKEN_SUCCESS){let s=l.payload;s?.account&&!n.getActiveAccount()&&n.setActiveAccount(s.account);}l.eventType===EventType.ACQUIRE_TOKEN_FAILURE&&g&&console.error("[MSAL] Token acquisition failed:",l.error);}),p.current=n,se=n,a(n),t&&t(n);}catch(c){throw console.error("[MSAL] Initialization failed:",c),c}})();},[]),typeof window>"u"?jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})}):i?jsx(MsalProvider,{instance:i,children:r}):jsx(Fragment,{children:e||jsx("div",{children:"Loading authentication..."})})}function Se({children:r,...e}){return jsx(V,{...e,children:r})}var W=new Map;function A(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=useMsal(),i=useAccount(t[0]||null),a=useMemo(()=>t.length>0,[t]),p=useCallback(async(l=r)=>{if(o!==InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let s={scopes:l,prompt:"select_account"};await e.loginRedirect(s);}catch(s){if(s?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login redirect failed:",s),s}},[e,r,o]),u=useCallback(async()=>{try{await e.logoutRedirect({account:i||void 0});}catch(l){throw console.error("[MSAL] Logout redirect failed:",l),l}},[e,i]),c=useCallback(async(l=r)=>{if(!i)throw new Error("[MSAL] No active account. Please login first.");try{let s={scopes:l,account:i,forceRefresh:!1};return (await e.acquireTokenSilent(s)).accessToken}catch(s){throw console.error("[MSAL] Silent token acquisition failed:",s),s}},[e,i,r]),n=useCallback(async(l=r)=>{if(!i)throw new Error("[MSAL] No active account. Please login first.");try{let s={scopes:l,account:i};await e.acquireTokenRedirect(s);}catch(s){throw console.error("[MSAL] Token redirect acquisition failed:",s),s}},[e,i,r]),h=useCallback(async(l=r)=>{let s=`${i?.homeAccountId||"anonymous"}-${l.sort().join(",")}`,m=W.get(s);if(m)return m;let f=(async()=>{try{return await c(l)}catch{throw console.warn("[MSAL] Silent token acquisition failed, falling back to redirect"),await n(l),new Error("[MSAL] Redirecting for token acquisition")}finally{W.delete(s);}})();return W.set(s,f),f},[c,n,r,i]),g=useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:i,accounts:t,isAuthenticated:a,inProgress:o!==InteractionStatus.None,loginRedirect:p,logoutRedirect:u,acquireToken:h,acquireTokenSilent:c,acquireTokenRedirect:n,clearSession:g}}function Ue({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",scopes:o,className:i="",style:a,onSuccess:p,onError:u}){let{loginRedirect:c,inProgress:n}=A(),[h,g]=useState(false),l=async()=>{g(true);try{await c(o),p?.();}catch(y){u?.(y);}finally{setTimeout(()=>g(false),500);}},s={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},m={dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}},f=n||h,d={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:f?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:f?.6:1,...m[e],...s[t],...a};return jsxs("button",{onClick:l,disabled:f,className:i,style:d,"aria-label":r,children:[jsx(ke,{}),jsx("span",{children:r})]})}function ke(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Fe({text:r="Sign out",variant:e="dark",size:t="medium",className:o="",style:i,onSuccess:a,onError:p}){let{logoutRedirect:u,inProgress:c}=A(),n=async()=>{try{await u(),a?.();}catch(s){p?.(s);}},h={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},l={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:c?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:c?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...h[t],...i};return jsxs("button",{onClick:n,disabled:c,className:o,style:l,"aria-label":r,children:[jsx(Ne,{}),jsx("span",{children:r})]})}function Ne(){return jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function k(){let{acquireToken:r}=A(),e=useCallback(async(u,c={})=>{let{scopes:n=["User.Read"],version:h="v1.0",debug:g=false,...l}=c;try{let s=await r(n),m=`https://graph.microsoft.com/${h}`,f=u.startsWith("http")?u:`${m}${u.startsWith("/")?u:`/${u}`}`;g&&console.log("[GraphAPI] Request:",{url:f,method:l.method||"GET"});let d=await fetch(f,{...l,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",...l.headers}});if(!d.ok){let R=await d.text(),L=`Graph API error (${d.status}): ${R}`;throw new Error(L)}if(d.status===204||d.headers.get("content-length")==="0")return null;let y=await d.json();return g&&console.log("[GraphAPI] Response:",y),y}catch(s){let m=v(s);throw console.error("[GraphAPI] Request failed:",m),new Error(m)}},[r]),t=useCallback((u,c={})=>e(u,{...c,method:"GET"}),[e]),o=useCallback((u,c,n={})=>e(u,{...n,method:"POST",body:c?JSON.stringify(c):void 0}),[e]),i=useCallback((u,c,n={})=>e(u,{...n,method:"PUT",body:c?JSON.stringify(c):void 0}),[e]),a=useCallback((u,c,n={})=>e(u,{...n,method:"PATCH",body:c?JSON.stringify(c):void 0}),[e]),p=useCallback((u,c={})=>e(u,{...c,method:"DELETE"}),[e]);return {get:t,post:o,put:i,patch:a,delete:p,request:e}}var x=new Map,Ie=300*1e3,pe=100;function Oe(){if(x.size>pe){let r=Array.from(x.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,x.size-pe).forEach(([t])=>{let o=x.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),x.delete(t);});}}function J(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,i]=useState(null),[a,p]=useState(false),[u,c]=useState(null),n=useCallback(async()=>{if(!r||!e){i(null);return}let g=e.homeAccountId,l=x.get(g);if(l&&Date.now()-l.timestamp<Ie){i(l.data);return}p(true),c(null);try{let s=await t.get("/me",{scopes:["User.Read"]}),m;try{let d=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});d&&(m=URL.createObjectURL(d));}catch{console.debug("[UserProfile] Photo not available");}let f={id:s.id,displayName:s.displayName,givenName:s.givenName,surname:s.surname,userPrincipalName:s.userPrincipalName,mail:s.mail,jobTitle:s.jobTitle,officeLocation:s.officeLocation,mobilePhone:s.mobilePhone,businessPhones:s.businessPhones,photo:m};x.set(g,{data:f,timestamp:Date.now()}),Oe(),i(f);}catch(s){let f=v(s),d=new Error(f);c(d),console.error("[UserProfile] Failed to fetch profile:",f);}finally{p(false);}},[r,e,t]),h=useCallback(()=>{if(e){let g=x.get(e.homeAccountId);g?.data.photo&&URL.revokeObjectURL(g.data.photo),x.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),i(null);},[e,o]);return useEffect(()=>(n(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[n]),useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:u,refetch:n,clearCache:h}}function Ge({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:i}){let{profile:a,loading:p}=J(),[u,c]=useState(null),[n,h]=useState(false);useEffect(()=>{a?.photo&&c(a.photo);},[a?.photo]);let g=()=>{if(!a)return "?";let{givenName:m,surname:f,displayName:d}=a;if(m&&f)return `${m[0]}${f[0]}`.toUpperCase();if(d){let y=d.split(" ");return y.length>=2?`${y[0][0]}${y[y.length-1][0]}`.toUpperCase():d.substring(0,2).toUpperCase()}return "?"},l={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},s=a?.displayName||"User";return p?jsx("div",{className:e,style:{...l,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):u&&!n?jsx("div",{className:e,style:l,title:o?s:void 0,"aria-label":`${s} avatar`,children:jsx("img",{src:u,alt:s,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{h(true),i&&c(i);}})}):jsx("div",{className:e,style:l,title:o?s:void 0,"aria-label":`${s} avatar`,children:g()})}function $e({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:i,renderUnauthenticated:a}){let{isAuthenticated:p,inProgress:u,account:c}=A(),n={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(u)return o?jsx(Fragment,{children:o()}):jsxs("div",{className:r,style:{...n,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsx(K,{color:"#FFA500"}),jsx("span",{children:"Loading..."})]});if(p){let h=c?.username||c?.name||"User";return i?jsx(Fragment,{children:i(h)}):jsxs("div",{className:r,style:{...n,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsx(K,{color:"#28A745"}),jsx("span",{children:t?`Authenticated as ${h}`:"Authenticated"})]})}return a?jsx(Fragment,{children:a()}):jsxs("div",{className:r,style:{...n,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsx(K,{color:"#DC3545"}),jsx("span",{children:"Not authenticated"})]})}function K({color:r}){return jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function Y({children:r,loadingComponent:e,fallbackComponent:t,scopes:o,onAuthRequired:i}){let{isAuthenticated:a,inProgress:p,loginRedirect:u}=A();return useEffect(()=>{!a&&!p&&(i?.(),(async()=>{try{await u(o);}catch(n){console.error("[AuthGuard] Authentication failed:",n);}})());},[a,p,o,u,i]),p?jsx(Fragment,{children:e||jsx("div",{children:"Authenticating..."})}):a?jsx(Fragment,{children:r}):jsx(Fragment,{children:t||jsx("div",{children:"Redirecting to login..."})})}var re=class extends Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:i,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),i?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:i,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):i}};var w=new Map,He=300*1e3,fe=100;function Ve(r){r?w.delete(r):w.clear();}function We(){if(w.size>fe){let r=Array.from(w.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,w.size-fe).forEach(([t])=>w.delete(t));}}function je(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,i]=useState([]),[a,p]=useState([]),[u,c]=useState(false),[n,h]=useState(null),g=useCallback(async()=>{if(!r||!e){i([]),p([]);return}let d=e.homeAccountId,y=w.get(d);if(y&&Date.now()-y.timestamp<He){i(y.roles),p(y.groups);return}c(true),h(null);try{let L=e.idTokenClaims?.roles||[],D=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(oe=>oe.id);w.set(d,{roles:L,groups:D,timestamp:Date.now()}),We(),i(L),p(D);}catch(R){let B=v(R),D=new Error(B);h(D),console.error("[Roles] Failed to fetch roles/groups:",B);let ye=e.idTokenClaims?.roles||[];i(ye);}finally{c(false);}},[r,e,t]),l=useCallback(d=>o.includes(d),[o]),s=useCallback(d=>a.includes(d),[a]),m=useCallback(d=>d.some(y=>o.includes(y)),[o]),f=useCallback(d=>d.every(y=>o.includes(y)),[o]);return useEffect(()=>(g(),()=>{e&&Ve(e.homeAccountId);}),[g,e]),{roles:o,groups:a,loading:u,error:n,hasRole:l,hasGroup:s,hasAnyRole:m,hasAllRoles:f,refetch:g}}function Je(r,e={}){let{displayName:t,...o}=e,i=a=>jsx(Y,{...o,children:jsx(r,{...a})});return i.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,i}async function me(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:i=1e4,backoffMultiplier:a=2,debug:p=false}=e,u,c=o;for(let n=0;n<=t;n++)try{return p&&n>0&&console.log(`[TokenRetry] Attempt ${n+1}/${t+1}`),await r()}catch(h){if(u=h,n===t){p&&console.error("[TokenRetry] All retry attempts failed");break}if(!Ke(h))throw p&&console.log("[TokenRetry] Non-retryable error, aborting"),h;p&&console.warn(`[TokenRetry] Attempt ${n+1} failed, retrying in ${c}ms...`),await Ze(c),c=Math.min(c*a,i);}throw u}function Ke(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Ze(r){return new Promise(e=>setTimeout(e,r))}function Qe(r,e={}){return (...t)=>me(()=>r(...t),e)}var z=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let i=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,p=`[${e.toUpperCase()}]`,u=`${i} ${a} ${p} ${t}`;return o!==void 0&&(u+=`
|
|
2
|
+
`+JSON.stringify(o,null,2)),u}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,i){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,i);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=e,a.click(),URL.revokeObjectURL(i);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},O=null;function Xe(r){return O?r&&(r.enabled!==void 0&&O.setEnabled(r.enabled),r.level&&O.setLevel(r.level)):O=new z(r),O}function Ye(r,e){return new z({...e,prefix:`[MSAL-Next:${r}]`})}function er(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:i="/",sessionCookie:a="msal.account",isAuthenticated:p,debug:u=false}=r;return async function(n){let{pathname:h}=n.nextUrl;u&&console.log("[AuthMiddleware] Processing:",h);let g=false;p?g=await p(n):g=!!n.cookies.get(a)?.value,u&&console.log("[AuthMiddleware] Authenticated:",g);let l=e.some(f=>h.startsWith(f)),s=t.some(f=>h.startsWith(f));if(l&&!g){u&&console.log("[AuthMiddleware] Redirecting to login");let f=n.nextUrl.clone();return f.pathname=o,f.searchParams.set("returnUrl",h),NextResponse.redirect(f)}if(s&&g){u&&console.log("[AuthMiddleware] Redirecting to home");let f=n.nextUrl.searchParams.get("returnUrl"),d=n.nextUrl.clone();return d.pathname=f||i,d.searchParams.delete("returnUrl"),NextResponse.redirect(d)}let m=NextResponse.next();if(g){m.headers.set("x-msal-authenticated","true");try{let f=n.cookies.get(a);if(f?.value){let d=q(f.value,_);d?.username&&m.headers.set("x-msal-username",d.username);}}catch{u&&console.warn("[AuthMiddleware] Failed to parse session data");}}return m}}export{Y as AuthGuard,$e as AuthStatus,re as ErrorBoundary,Se as MSALProvider,Ue as MicrosoftSignInButton,V as MsalAuthProvider,Fe as SignOutButton,Ge as UserAvatar,er as createAuthMiddleware,H as createMsalConfig,Qe as createRetryWrapper,Ye as createScopedLogger,Xe as getDebugLogger,Pe as getMsalInstance,_ as isValidAccountData,G as isValidRedirectUri,ne as isValidScope,me as retryWithBackoff,q as safeJsonParse,v as sanitizeError,k as useGraphApi,A as useMsalAuth,je as useRoles,J as useUserProfile,Ae as validateScopes,Je as withAuth};
|