@chemmangat/msal-next 4.0.1 → 4.1.0

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 CHANGED
@@ -2,6 +2,356 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [4.1.0] - 2026-03-07
6
+
7
+ ### 🎉 Major Release - Documentation Overhaul + Production Features
8
+
9
+ This release combines a complete documentation restructure with two highly-requested production features.
10
+
11
+ ### ✨ New Features
12
+
13
+ #### 1. Fixed 'use client' Directive in Built Files 🔧
14
+ Resolved the issue where importing MSALProvider in layout.tsx required adding 'use client' to the layout file.
15
+
16
+ **What Changed:**
17
+ - Added 'use client' directive to the top of all built dist files
18
+ - Updated tsup build configuration to preserve React directives
19
+ - Users can now import MSALProvider without needing to add 'use client' to their layout
20
+
21
+ **Before:**
22
+ ```tsx
23
+ // layout.tsx - Had to add 'use client' here
24
+ 'use client';
25
+
26
+ import { MSALProvider } from '@chemmangat/msal-next';
27
+ ```
28
+
29
+ **After:**
30
+ ```tsx
31
+ // layout.tsx - No 'use client' needed!
32
+ import { MSALProvider } from '@chemmangat/msal-next';
33
+ ```
34
+
35
+ #### 2. Automatic Silent Token Refresh ⭐
36
+ Prevents unexpected logouts by automatically refreshing tokens before they expire.
37
+
38
+ ```tsx
39
+ <MSALProvider
40
+ clientId="..."
41
+ autoRefreshToken={true} // Enable automatic refresh
42
+ refreshBeforeExpiry={300} // Refresh 5 min before expiry
43
+ >
44
+ {children}
45
+ </MSALProvider>
46
+ ```
47
+
48
+ **Benefits:**
49
+ - No more unexpected logouts during active sessions
50
+ - Tokens refresh silently in the background
51
+ - Configurable refresh timing
52
+ - Opt-in feature (disabled by default)
53
+ - Zero performance impact when disabled
54
+
55
+ #### 3. New useTokenRefresh Hook
56
+ Monitor token expiry and show warnings to users.
57
+
58
+ ```tsx
59
+ const { expiresIn, isExpiringSoon, refresh } = useTokenRefresh({
60
+ refreshBeforeExpiry: 300,
61
+ scopes: ['User.Read'],
62
+ });
63
+
64
+ if (isExpiringSoon) {
65
+ return <div>⚠️ Your session will expire soon</div>;
66
+ }
67
+ ```
68
+
69
+ **Use Cases:**
70
+ - Show session expiry warnings
71
+ - Manual token refresh
72
+ - Monitor token status
73
+ - Custom refresh logic
74
+
75
+ #### 4. Fixed "Interaction in Progress" Issue 🐛
76
+ Improved sign-in button state management to prevent the common "interaction already in progress" error.
77
+
78
+ **What was fixed:**
79
+ - Button now properly tracks MSAL interaction state
80
+ - Prevents multiple simultaneous login attempts
81
+ - Automatically resets state when user is authenticated
82
+ - Better cleanup on component unmount
83
+ - Safety timeout for edge cases
84
+
85
+ **Before:**
86
+ ```
87
+ User clicks "Sign In" → Redirects → Returns → Clicks again → "Interaction in progress" error
88
+ ```
89
+
90
+ **After:**
91
+ ```
92
+ User clicks "Sign In" → Redirects → Returns → Button automatically disabled/enabled correctly
93
+ ```
94
+
95
+ ### 📚 Documentation Overhaul
96
+
97
+ #### Restructured README.md
98
+ - **Setup-First Approach** - Quick Start guide now appears at the top
99
+ - **Complete Setup Guide for AI Assistants** - Step-by-step instructions from A to Z
100
+ - **Clear Project Structure** - Shows exactly where files should be placed
101
+ - **Common Patterns** - Ready-to-use code examples for typical scenarios
102
+ - **Troubleshooting Checklist** - Quick diagnostic steps
103
+ - **Configuration Reference** - Complete table of all options
104
+ - **FAQ Section** - Answers to common questions
105
+
106
+ #### Better for AI Assistants
107
+ When an AI assistant is asked to "implement MSAL authentication", the README now provides:
108
+ 1. Clear installation command
109
+ 2. Azure AD setup steps
110
+ 3. Environment variable configuration
111
+ 4. Exact file structure
112
+ 5. Complete code for each file
113
+ 6. Common patterns
114
+ 7. Troubleshooting steps
115
+
116
+ ### 🔧 Improvements
117
+
118
+ - **MicrosoftSignInButton**: Better state management, prevents duplicate clicks
119
+ - **MSALProvider**: New props for automatic token refresh
120
+ - **Type Safety**: New types exported for token refresh functionality
121
+ - **Error Handling**: Better handling of interaction state
122
+
123
+ ### 📦 New Exports
124
+
125
+ ```typescript
126
+ // Hook
127
+ export { useTokenRefresh } from '@chemmangat/msal-next';
128
+
129
+ // Types
130
+ export type { UseTokenRefreshOptions, UseTokenRefreshReturn } from '@chemmangat/msal-next';
131
+
132
+ // MSALProvider new props
133
+ interface MsalAuthConfig {
134
+ autoRefreshToken?: boolean;
135
+ refreshBeforeExpiry?: number;
136
+ }
137
+ ```
138
+
139
+ ### 📚 New Documentation
140
+
141
+ #### SECURITY.md
142
+ Comprehensive security documentation covering:
143
+ - Security architecture and token handling
144
+ - Best practices for production deployment
145
+ - Common security mistakes to avoid
146
+ - Compliance information (GDPR, SOC 2, HIPAA)
147
+ - Security checklist for deployment
148
+ - Monitoring and incident response
149
+
150
+ #### Updated README.md
151
+ - Top features table at the beginning
152
+ - Prominent security highlights
153
+ - Clear note about 'use client' not needed in layout.tsx
154
+ - Security policy links throughout
155
+ - Enhanced setup instructions
156
+
157
+ ### 🔄 Breaking Changes
158
+
159
+ **None!** This release is 100% backward compatible with v4.0.2.
160
+
161
+ ### 📝 Migration from v4.0.2
162
+
163
+ No code changes required! Simply update:
164
+
165
+ ```bash
166
+ npm install @chemmangat/msal-next@4.1.0
167
+ ```
168
+
169
+ **Optional: Enable automatic token refresh**
170
+
171
+ ```tsx
172
+ <MSALProvider
173
+ clientId="..."
174
+ autoRefreshToken={true} // NEW - prevents unexpected logouts
175
+ >
176
+ {children}
177
+ </MSALProvider>
178
+ ```
179
+
180
+ ### 🎯 Use Cases
181
+
182
+ **Automatic Token Refresh:**
183
+ - Long-running applications
184
+ - Apps where users stay logged in for hours
185
+ - Prevent interruptions during active work
186
+ - Background data synchronization
187
+
188
+ **Token Expiry Monitoring:**
189
+ - Show session timeout warnings
190
+ - Implement custom refresh logic
191
+ - Track authentication state
192
+ - User experience improvements
193
+
194
+ ### 📊 Impact
195
+
196
+ - **Reduced Support Tickets**: Automatic refresh prevents "why was I logged out?" questions
197
+ - **Better UX**: Users stay logged in during active sessions
198
+ - **Easier Setup**: AI assistants can now implement MSAL correctly first try
199
+ - **Faster Onboarding**: Developers can set up in 5 minutes with new README
200
+
201
+ ---
202
+
203
+ ## [4.0.2] - 2026-03-07
204
+
205
+ ### 🎉 Developer Experience Release - Better Types, Errors & Validation
206
+
207
+ This release focuses on making the package easier to use and debug with complete TypeScript types, actionable error messages, and automatic configuration validation.
208
+
209
+ ### ✨ New Features
210
+
211
+ #### Complete TypeScript Types
212
+ - **Extended UserProfile interface** with ALL Microsoft Graph /me endpoint fields
213
+ - Added: `department`, `preferredLanguage`, `employeeId`, `companyName`, `country`, `city`, `state`, `streetAddress`, `postalCode`, `usageLocation`, `manager`, `aboutMe`, `birthday`, `interests`, `skills`, `schools`, `pastProjects`, `responsibilities`, `mySite`, `faxNumber`, `accountEnabled`, `ageGroup`, `userType`, `employeeHireDate`, `employeeType`
214
+ - Full JSDoc comments for each field
215
+ - Generic type support: `useUserProfile<T extends UserProfile>()`
216
+ - Extensible for custom organization fields
217
+
218
+ #### Enhanced Error Handling
219
+ - **New MsalError class** that wraps MSAL errors with actionable messages
220
+ - **Automatic error detection** for common Azure AD errors:
221
+ - `AADSTS50011` (Redirect URI mismatch) → Step-by-step fix instructions
222
+ - `AADSTS65001` (Consent required) → How to grant admin consent
223
+ - `AADSTS700016` (Invalid client) → How to verify client ID
224
+ - `AADSTS90002` (Invalid tenant) → How to fix tenant configuration
225
+ - `user_cancelled` → Graceful handling (not a real error)
226
+ - `no_token_request_cache_error` → Explanation and fix
227
+ - `interaction_required` / `consent_required` → User-friendly messages
228
+ - **Colored console output** in development mode with emojis
229
+ - **Error helper methods**: `isUserCancellation()`, `requiresInteraction()`
230
+ - **Documentation links** included in error messages
231
+
232
+ #### Development Mode Configuration Validator
233
+ - **Automatic validation** of MSAL configuration in development mode
234
+ - **Detects common mistakes**:
235
+ - Placeholder values (e.g., "your-client-id-here")
236
+ - Missing environment variables
237
+ - Invalid GUID format for client/tenant IDs
238
+ - HTTP in production (should be HTTPS)
239
+ - Invalid scope formats
240
+ - **Helpful warnings** with fix instructions and emojis (⚠️, ✓, ✗)
241
+ - **Runs once on mount** and caches results for performance
242
+ - **Zero performance impact** in production (only runs in development)
243
+
244
+ ### 📚 Documentation
245
+
246
+ #### New TROUBLESHOOTING.md
247
+ - **Common Mistakes** section with before/after examples
248
+ - **Top 5 Errors** with detailed solutions:
249
+ 1. AADSTS50011 - Redirect URI mismatch
250
+ 2. AADSTS65001 - Admin consent required
251
+ 3. Missing environment variables
252
+ 4. AADSTS700016 - Invalid client
253
+ 5. AADSTS90002 - Invalid tenant
254
+ - **Configuration Issues** troubleshooting
255
+ - **Authentication Flow Issues** solutions
256
+ - **Development Tips** for debugging
257
+ - **Quick Reference** for Azure Portal tasks
258
+
259
+ #### Updated README.md
260
+ - **All code examples** now show `'use client'` FIRST
261
+ - **"What's New in v4.0.2"** section highlighting new features
262
+ - **Common Mistakes** section added
263
+ - **TypeScript examples** updated to show complete types
264
+ - **Error handling examples** with new MsalError class
265
+ - **Configuration validation** examples
266
+
267
+ ### 🔧 Improvements
268
+
269
+ - **Better error messages** throughout the package
270
+ - **Improved logging** in development mode
271
+ - **Type safety** for all user profile fields
272
+ - **Automatic validation** prevents common configuration mistakes
273
+ - **Clearer documentation** with more examples
274
+
275
+ ### 🐛 Bug Fixes
276
+
277
+ - Fixed missing TypeScript types for user profile fields
278
+ - Improved error handling in all authentication flows
279
+ - Better detection of user cancellation vs real errors
280
+
281
+ ### 📦 Exports
282
+
283
+ New exports added:
284
+ ```typescript
285
+ // Types
286
+ export type { UserProfile, UseUserProfileReturn } from '@chemmangat/msal-next';
287
+ export type { ValidationResult, ValidationWarning, ValidationError } from '@chemmangat/msal-next';
288
+
289
+ // Error handling
290
+ export { MsalError, wrapMsalError, createMissingEnvVarError } from '@chemmangat/msal-next';
291
+
292
+ // Configuration validation
293
+ export { validateConfig, displayValidationResults } from '@chemmangat/msal-next';
294
+ ```
295
+
296
+ ### 🔄 Breaking Changes
297
+
298
+ **None!** This release is 100% backward compatible with v4.0.1.
299
+
300
+ ### 📝 Migration from v4.0.1
301
+
302
+ No code changes required! Simply update:
303
+
304
+ ```bash
305
+ npm install @chemmangat/msal-next@4.0.2
306
+ ```
307
+
308
+ **Optional improvements you can make:**
309
+
310
+ 1. **Use complete types:**
311
+ ```typescript
312
+ const { profile } = useUserProfile();
313
+ // Now has access to: department, preferredLanguage, employeeId, etc.
314
+ console.log(profile?.department);
315
+ console.log(profile?.preferredLanguage);
316
+ ```
317
+
318
+ 2. **Better error handling:**
319
+ ```typescript
320
+ import { wrapMsalError } from '@chemmangat/msal-next';
321
+
322
+ try {
323
+ await loginRedirect();
324
+ } catch (error) {
325
+ const msalError = wrapMsalError(error);
326
+ if (msalError.isUserCancellation()) {
327
+ return; // User cancelled, ignore
328
+ }
329
+ console.error(msalError.toConsoleString()); // Actionable error message
330
+ }
331
+ ```
332
+
333
+ 3. **Manual validation (optional):**
334
+ ```typescript
335
+ import { validateConfig, displayValidationResults } from '@chemmangat/msal-next';
336
+
337
+ const result = validateConfig({
338
+ clientId: process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!,
339
+ tenantId: process.env.NEXT_PUBLIC_AZURE_AD_TENANT_ID,
340
+ });
341
+
342
+ displayValidationResults(result);
343
+ ```
344
+
345
+ ### 🎯 What's Next
346
+
347
+ v4.1.0 will focus on:
348
+ - Additional Graph API helpers
349
+ - More authentication examples
350
+ - Performance optimizations
351
+ - Enhanced testing coverage
352
+
353
+ ---
354
+
5
355
  ## [3.1.7] - 2026-03-05
6
356
 
7
357
  ### 🔄 Breaking Change - Redirect-Only Flow
@@ -121,7 +471,7 @@ await logoutRedirect();
121
471
  ### 🚨 CRITICAL BUG FIX
122
472
 
123
473
  #### Popup Authentication Fixed
124
- **This release fixes a critical bug introduced in v3.0.6 that broke popup authentication for 650+ users.**
474
+ **This release fixes a critical bug introduced in v3.0.6 that broke popup authentication for 2,200+ users.**
125
475
 
126
476
  **Problem:** In v3.0.6, we skipped `handleRedirectPromise()` in popup windows, which prevented MSAL from completing the authentication flow. This caused popups to not close and authentication to fail.
127
477