@chemmangat/msal-next 4.0.2 → 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/SECURITY.md CHANGED
@@ -1,152 +1,464 @@
1
1
  # Security Policy
2
2
 
3
- ## Supported Versions
3
+ ## Overview
4
4
 
5
- | Version | Supported |
6
- | ------- | ------------------ |
7
- | 2.0.x | :white_check_mark: |
8
- | < 2.0 | :x: |
5
+ @chemmangat/msal-next is built on Microsoft's official MSAL (Microsoft Authentication Library) and follows industry best practices for secure authentication in Next.js applications.
9
6
 
10
- ## Security Updates in v2.0.1
7
+ ---
11
8
 
12
- This release addresses several security vulnerabilities discovered in v2.0.0. We strongly recommend all users upgrade immediately.
9
+ ## 🔒 Security Architecture
13
10
 
14
- ### Fixed Vulnerabilities
11
+ ### Client-Side Authentication
15
12
 
16
- #### 1. Memory Leaks from Blob URLs (Medium Severity)
17
- **Affected:** `useUserProfile` hook
18
- **Fixed:** Added proper cleanup of blob URLs using `URL.revokeObjectURL()` in useEffect cleanup functions.
13
+ **All authentication happens in the browser:**
14
+ - Tokens are never sent to your Next.js server
15
+ - Authentication flow handled by Microsoft's MSAL library
16
+ - ✅ Direct communication between browser and Azure AD
17
+ - ✅ No server-side token storage or handling
19
18
 
20
- #### 2. Unbounded Cache Growth (Medium Severity)
21
- **Affected:** `useRoles` and `useUserProfile` hooks
22
- **Fixed:** Implemented LRU cache eviction with a maximum size limit of 100 entries to prevent memory exhaustion.
19
+ ```
20
+ User Browser ←→ Azure AD (Microsoft)
21
+
22
+ Your Next.js App (UI only)
23
+ ```
24
+
25
+ **Your Next.js server never sees:**
26
+ - Access tokens
27
+ - Refresh tokens
28
+ - ID tokens
29
+ - User credentials
30
+
31
+ ### Token Storage
23
32
 
24
- #### 3. Race Conditions in Token Acquisition (Medium Severity)
25
- **Affected:** `useMsalAuth` hook
26
- **Fixed:** Implemented request deduplication to prevent multiple concurrent popup windows and token requests.
33
+ **Secure token storage options:**
27
34
 
28
- #### 4. JSON Parsing Without Validation (High Severity)
29
- **Affected:** `getServerSession`, `createAuthMiddleware`
30
- **Fixed:** Added schema validation for all JSON parsing operations using the new `safeJsonParse` utility.
35
+ 1. **sessionStorage** (Default - Recommended)
36
+ - Tokens cleared when browser tab closes
37
+ - Most secure for public computers
38
+ - Isolated per tab
31
39
 
32
- #### 5. Information Disclosure in Error Messages (Medium Severity)
33
- **Affected:** All hooks and utilities
34
- **Fixed:** Implemented error sanitization to remove tokens, secrets, and sensitive information from error messages.
40
+ 2. **localStorage**
41
+ - Tokens persist across browser sessions
42
+ - Shared across tabs
43
+ - Use for "remember me" functionality
44
+
45
+ 3. **memoryStorage**
46
+ - Tokens only in memory
47
+ - Most secure (lost on page refresh)
48
+ - Use for maximum security
49
+
50
+ ```tsx
51
+ <MSALProvider
52
+ clientId="..."
53
+ cacheLocation="sessionStorage" // Recommended
54
+ >
55
+ ```
35
56
 
36
- #### 6. Missing Redirect URI Validation (Medium Severity)
37
- **Affected:** `createMsalConfig`
38
- **Fixed:** Added optional `allowedRedirectUris` configuration to validate redirect URIs and prevent open redirect vulnerabilities.
57
+ ---
39
58
 
40
- ### New Security Features
59
+ ## 🛡️ Security Features
41
60
 
42
- - **Input Validation Utilities**: New `validation.ts` module with functions for safe JSON parsing, scope validation, and redirect URI validation
43
- - **Error Sanitization**: Automatic removal of tokens and secrets from error messages
44
- - **Cache Management**: Proper cache size limits and cleanup on component unmount
45
- - **Request Deduplication**: Prevention of concurrent token acquisition requests
61
+ ### 1. Built on Microsoft MSAL
46
62
 
47
- ## Best Practices
63
+ - **Industry Standard**: Uses Microsoft's official authentication library
64
+ - **Regular Updates**: Microsoft maintains and updates MSAL
65
+ - **Security Patches**: Automatic security fixes from Microsoft
66
+ - **Compliance**: Meets enterprise security requirements
48
67
 
49
- ### DO NOT Store Tokens in Cookies
68
+ ### 2. Token Security
50
69
 
51
- The example code in `src/examples/api-route-session.ts` demonstrates cookie-based session management but includes a warning. **Do not use this pattern in production** as it exposes tokens to CSRF attacks.
70
+ **Access Tokens:**
71
+ - Short-lived (1 hour by default)
72
+ - Automatically refreshed
73
+ - Never exposed to server
74
+ - Stored securely in browser
52
75
 
53
- Instead:
54
- - Use MSAL's built-in sessionStorage/localStorage (client-side only)
55
- - Implement proper server-side session management with encrypted session IDs
56
- - Never store access tokens in cookies
76
+ **Refresh Tokens:**
77
+ - Managed by MSAL
78
+ - Encrypted by browser
79
+ - Automatic rotation
80
+ - Secure storage
57
81
 
58
- ### Use Redirect URI Validation
82
+ **ID Tokens:**
83
+ - Signed by Azure AD
84
+ - Verified by MSAL
85
+ - Contains user claims
86
+ - Tamper-proof
59
87
 
60
- ```typescript
61
- <MsalAuthProvider
62
- clientId={process.env.NEXT_PUBLIC_CLIENT_ID!}
88
+ ### 3. Redirect URI Validation
89
+
90
+ Prevent open redirect vulnerabilities:
91
+
92
+ ```tsx
93
+ <MSALProvider
94
+ clientId="..."
63
95
  allowedRedirectUris={[
64
96
  'https://myapp.com',
65
97
  'https://staging.myapp.com',
66
- 'http://localhost:3000'
98
+ 'http://localhost:3000' // Dev only
67
99
  ]}
68
100
  >
69
- {children}
70
- </MsalAuthProvider>
71
- ```
72
-
73
- ### Implement Security Headers
74
-
75
- Add comprehensive security headers in your `next.config.js`:
76
-
77
- ```javascript
78
- async headers() {
79
- return [
80
- {
81
- source: '/(.*)',
82
- headers: [
83
- {
84
- key: 'Content-Security-Policy',
85
- value: "default-src 'self'; script-src 'self'; connect-src 'self' https://login.microsoftonline.com https://graph.microsoft.com;"
86
- },
87
- {
88
- key: 'X-Frame-Options',
89
- value: 'DENY'
90
- },
91
- {
92
- key: 'X-Content-Type-Options',
93
- value: 'nosniff'
94
- },
95
- {
96
- key: 'Referrer-Policy',
97
- value: 'strict-origin-when-cross-origin'
98
- },
99
- {
100
- key: 'Permissions-Policy',
101
- value: 'camera=(), microphone=(), geolocation=()'
102
- }
103
- ]
104
- }
105
- ];
106
- }
107
101
  ```
108
102
 
109
- ### Validate Scopes
103
+ ### 4. Scope Validation
110
104
 
111
- Use the built-in scope validation:
105
+ Validate requested permissions:
112
106
 
113
- ```typescript
114
- import { validateScopes } from '@chemmangat/msal-next';
107
+ ```tsx
108
+ // Only request necessary scopes
109
+ scopes={['User.Read']} // ✅ Minimal permissions
115
110
 
116
- const scopes = ['User.Read', 'Mail.Read'];
117
- if (!validateScopes(scopes)) {
118
- throw new Error('Invalid scopes');
119
- }
111
+ // Avoid over-requesting
112
+ scopes={['User.Read', 'Mail.ReadWrite', 'Files.ReadWrite.All']} // ❌ Too broad
120
113
  ```
121
114
 
122
- ### Use HTTPS in Development
115
+ ### 5. Error Sanitization
116
+
117
+ Automatic removal of sensitive data from error messages:
118
+
119
+ ```tsx
120
+ // Tokens and secrets automatically redacted
121
+ console.error(error); // "[TOKEN_REDACTED]" instead of actual token
122
+ ```
123
123
 
124
- Always test with HTTPS locally to catch security issues early:
124
+ ### 6. Configuration Validation
125
+
126
+ Development-mode validation catches security issues:
127
+
128
+ ```tsx
129
+ // Warns about:
130
+ // - HTTP in production (should be HTTPS)
131
+ // - Placeholder values
132
+ // - Invalid configurations
133
+ ```
134
+
135
+ ---
136
+
137
+ ## 🔐 Best Practices
138
+
139
+ ### 1. Environment Variables
140
+
141
+ **Always use environment variables for sensitive data:**
125
142
 
126
143
  ```bash
127
- # Use mkcert or similar tools
128
- mkcert localhost
144
+ # .env.local
145
+ NEXT_PUBLIC_AZURE_AD_CLIENT_ID=your-client-id
146
+ NEXT_PUBLIC_AZURE_AD_TENANT_ID=your-tenant-id
147
+ ```
148
+
149
+ **Never hardcode:**
150
+ ```tsx
151
+ // ❌ BAD - Hardcoded
152
+ <MSALProvider clientId="12345678-1234-1234-1234-123456789012">
153
+
154
+ // ✅ GOOD - Environment variable
155
+ <MSALProvider clientId={process.env.NEXT_PUBLIC_AZURE_AD_CLIENT_ID!}>
156
+ ```
157
+
158
+ ### 2. HTTPS in Production
159
+
160
+ **Always use HTTPS in production:**
161
+
162
+ ```tsx
163
+ // ✅ GOOD
164
+ redirectUri: "https://myapp.com"
165
+
166
+ // ❌ BAD - HTTP in production
167
+ redirectUri: "http://myapp.com"
168
+ ```
169
+
170
+ **HTTP is only acceptable for localhost:**
171
+ ```tsx
172
+ redirectUri: "http://localhost:3000" // ✅ OK for development
173
+ ```
174
+
175
+ ### 3. Minimal Scopes
176
+
177
+ **Request only necessary permissions:**
178
+
179
+ ```tsx
180
+ // ✅ GOOD - Minimal scopes
181
+ scopes={['User.Read']}
182
+
183
+ // ❌ BAD - Excessive scopes
184
+ scopes={['User.Read', 'Mail.ReadWrite', 'Files.ReadWrite.All', 'Directory.ReadWrite.All']}
129
185
  ```
130
186
 
131
- ## Reporting a Vulnerability
187
+ ### 4. Token Refresh
188
+
189
+ **Use automatic token refresh to prevent token exposure:**
190
+
191
+ ```tsx
192
+ <MSALProvider
193
+ clientId="..."
194
+ autoRefreshToken={true} // Reduces token exposure window
195
+ refreshBeforeExpiry={300}
196
+ >
197
+ ```
198
+
199
+ ### 5. Secure Cookie Settings
200
+
201
+ **When using server-side sessions:**
202
+
203
+ ```tsx
204
+ // Set secure cookie options
205
+ const session = await getServerSession();
206
+
207
+ // Cookies should be:
208
+ // - HttpOnly: true
209
+ // - Secure: true (in production)
210
+ // - SameSite: 'lax' or 'strict'
211
+ ```
212
+
213
+ ### 6. Content Security Policy
214
+
215
+ **Add CSP headers to your Next.js app:**
216
+
217
+ ```tsx
218
+ // next.config.js
219
+ const securityHeaders = [
220
+ {
221
+ key: 'Content-Security-Policy',
222
+ value: `
223
+ default-src 'self';
224
+ script-src 'self' 'unsafe-eval' 'unsafe-inline';
225
+ connect-src 'self' https://login.microsoftonline.com https://graph.microsoft.com;
226
+ img-src 'self' data: https:;
227
+ style-src 'self' 'unsafe-inline';
228
+ `.replace(/\s{2,}/g, ' ').trim()
229
+ }
230
+ ];
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 🚨 Common Security Mistakes
236
+
237
+ ### ❌ Mistake 1: Storing Tokens in Cookies
238
+
239
+ ```tsx
240
+ // ❌ BAD - Don't store tokens in cookies
241
+ document.cookie = `token=${accessToken}`;
242
+
243
+ // ✅ GOOD - Let MSAL handle storage
244
+ const token = await acquireToken(['User.Read']);
245
+ ```
246
+
247
+ ### ❌ Mistake 2: Sending Tokens to Your Server
248
+
249
+ ```tsx
250
+ // ❌ BAD - Don't send tokens to your server
251
+ fetch('/api/user', {
252
+ headers: { 'Authorization': `Bearer ${token}` }
253
+ });
254
+
255
+ // ✅ GOOD - Use tokens only for Microsoft Graph
256
+ fetch('https://graph.microsoft.com/v1.0/me', {
257
+ headers: { 'Authorization': `Bearer ${token}` }
258
+ });
259
+ ```
260
+
261
+ ### ❌ Mistake 3: Logging Tokens
262
+
263
+ ```tsx
264
+ // ❌ BAD - Don't log tokens
265
+ console.log('Token:', token);
266
+
267
+ // ✅ GOOD - Log without sensitive data
268
+ console.log('Token acquired successfully');
269
+ ```
270
+
271
+ ### ❌ Mistake 4: Exposing Client Secret
272
+
273
+ ```tsx
274
+ // ❌ BAD - Client secret in frontend
275
+ const clientSecret = "your-secret"; // NEVER DO THIS
276
+
277
+ // ✅ GOOD - No client secret needed
278
+ // SPAs don't use client secrets
279
+ ```
280
+
281
+ ### ❌ Mistake 5: Using localStorage in Public Computers
282
+
283
+ ```tsx
284
+ // ❌ BAD - localStorage on public computers
285
+ cacheLocation: "localStorage"
286
+
287
+ // ✅ GOOD - sessionStorage for public computers
288
+ cacheLocation: "sessionStorage"
289
+ ```
290
+
291
+ ---
292
+
293
+ ## 🔍 Security Checklist
294
+
295
+ Before deploying to production:
296
+
297
+ - [ ] Using HTTPS (not HTTP)
298
+ - [ ] Environment variables for sensitive data
299
+ - [ ] Minimal scopes requested
300
+ - [ ] Redirect URIs validated
301
+ - [ ] sessionStorage for token cache (or localStorage with caution)
302
+ - [ ] Content Security Policy configured
303
+ - [ ] Error logging doesn't expose tokens
304
+ - [ ] No client secrets in frontend code
305
+ - [ ] Regular dependency updates
306
+ - [ ] Security headers configured
307
+
308
+ ---
309
+
310
+ ## 🛠️ Security Monitoring
311
+
312
+ ### 1. Enable Logging in Development
313
+
314
+ ```tsx
315
+ <MSALProvider
316
+ clientId="..."
317
+ enableLogging={true} // Only in development
318
+ >
319
+ ```
320
+
321
+ ### 2. Monitor Authentication Events
322
+
323
+ ```tsx
324
+ <MSALProvider
325
+ clientId="..."
326
+ onInitialized={(instance) => {
327
+ // Log authentication events
328
+ instance.addEventCallback((event) => {
329
+ if (event.eventType === 'LOGIN_FAILURE') {
330
+ // Send to monitoring service
331
+ logSecurityEvent('login_failure', event);
332
+ }
333
+ });
334
+ }}
335
+ >
336
+ ```
337
+
338
+ ### 3. Track Token Acquisition
339
+
340
+ ```tsx
341
+ const { acquireToken } = useMsalAuth();
342
+
343
+ try {
344
+ const token = await acquireToken(['User.Read']);
345
+ // Log successful acquisition
346
+ } catch (error) {
347
+ // Log and monitor failures
348
+ logSecurityEvent('token_acquisition_failed', error);
349
+ }
350
+ ```
351
+
352
+ ---
353
+
354
+ ## 📊 Compliance
355
+
356
+ ### GDPR Compliance
357
+
358
+ - ✅ No user data stored on your servers
359
+ - ✅ Authentication handled by Microsoft (GDPR compliant)
360
+ - ✅ User can revoke access anytime
361
+ - ✅ Clear data handling policies
362
+
363
+ ### SOC 2 Compliance
364
+
365
+ - ✅ Uses Microsoft's SOC 2 compliant infrastructure
366
+ - ✅ Secure token storage
367
+ - ✅ Audit logging available
368
+ - ✅ Access controls via Azure AD
369
+
370
+ ### HIPAA Compliance
371
+
372
+ - ✅ No PHI stored in frontend
373
+ - ✅ Secure authentication
374
+ - ✅ Microsoft Azure is HIPAA compliant
375
+ - ✅ Proper access controls
376
+
377
+ ---
378
+
379
+ ## 🐛 Reporting Security Issues
380
+
381
+ **If you discover a security vulnerability:**
382
+
383
+ 1. **DO NOT** open a public GitHub issue
384
+ 2. Email: [your-security-email@example.com]
385
+ 3. Include:
386
+ - Description of the vulnerability
387
+ - Steps to reproduce
388
+ - Potential impact
389
+ - Suggested fix (if any)
390
+
391
+ **We will:**
392
+ - Acknowledge within 48 hours
393
+ - Provide a fix within 7 days for critical issues
394
+ - Credit you in the security advisory (if desired)
395
+
396
+ ---
397
+
398
+ ## 📚 Security Resources
399
+
400
+ ### Microsoft Documentation
401
+ - [MSAL.js Security](https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-js-security)
402
+ - [Azure AD Security Best Practices](https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/security-operations-introduction)
403
+ - [OAuth 2.0 Security](https://oauth.net/2/security-best-practices/)
404
+
405
+ ### OWASP Guidelines
406
+ - [Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
407
+ - [Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
408
+
409
+ ### Package Security
410
+ - [npm Security Advisories](https://www.npmjs.com/advisories)
411
+ - [Snyk Vulnerability Database](https://snyk.io/vuln/)
412
+
413
+ ---
414
+
415
+ ## 🔄 Security Updates
416
+
417
+ **We regularly:**
418
+ - Update MSAL dependencies
419
+ - Monitor security advisories
420
+ - Apply security patches
421
+ - Review code for vulnerabilities
422
+ - Update documentation
423
+
424
+ **You should:**
425
+ - Keep @chemmangat/msal-next updated
426
+ - Monitor security advisories
427
+ - Review Azure AD audit logs
428
+ - Update dependencies regularly
429
+ - Follow security best practices
430
+
431
+ ---
432
+
433
+ ## ✅ Security Guarantees
434
+
435
+ **What we guarantee:**
436
+ - ✅ No tokens sent to your server
437
+ - ✅ Secure token storage
438
+ - ✅ Regular security updates
439
+ - ✅ Industry-standard practices
440
+ - ✅ Microsoft MSAL compliance
441
+
442
+ **What you must ensure:**
443
+ - ✅ HTTPS in production
444
+ - ✅ Secure environment variables
445
+ - ✅ Regular updates
446
+ - ✅ Proper Azure AD configuration
447
+ - ✅ Security monitoring
448
+
449
+ ---
132
450
 
133
- If you discover a security vulnerability, please email security@chemmangat.com with:
451
+ ## 📞 Support
134
452
 
135
- 1. Description of the vulnerability
136
- 2. Steps to reproduce
137
- 3. Potential impact
138
- 4. Suggested fix (if any)
453
+ For security questions:
454
+ - 📧 Email: [security@example.com]
455
+ - 💬 [GitHub Discussions](https://github.com/chemmangat/msal-next/discussions)
456
+ - 📖 [Documentation](./README.md)
139
457
 
140
- We will respond within 48 hours and provide a timeline for a fix.
458
+ **For urgent security issues, email directly.**
141
459
 
142
- ## Security Checklist
460
+ ---
143
461
 
144
- - [ ] Updated to v2.0.1 or later
145
- - [ ] Not storing tokens in cookies
146
- - [ ] Security headers configured in next.config.js
147
- - [ ] Redirect URI validation enabled
148
- - [ ] Using HTTPS in production
149
- - [ ] Regular dependency audits (`npm audit`)
150
- - [ ] Environment variables properly secured
151
- - [ ] CSRF protection on state-changing endpoints
152
- - [ ] Rate limiting on authentication endpoints
462
+ **Last Updated:** March 7, 2026
463
+ **Version:** 4.1.0
464
+ **License:** MIT