@thinkingcat/auth-utils 1.0.39 → 1.0.41

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.
Files changed (2) hide show
  1. package/dist/index.js +56 -31
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -448,44 +448,46 @@ async function createAuthResponse(accessToken, secret, options) {
448
448
  }
449
449
  // accessTokenExpires 추가 (15분)
450
450
  jwt.accessTokenExpires = Date.now() + (15 * 60 * 1000);
451
- debugLog('createAuthResponse', 'JWT created:', {
451
+ debugLog('createAuthResponse', 'JWT prepared (NextAuth will create session from custom tokens):', {
452
452
  hasId: !!jwt.id,
453
453
  hasEmail: !!jwt.email,
454
454
  hasRole: !!jwt.role,
455
455
  hasRefreshToken: !!jwt.refreshToken,
456
456
  });
457
- // 3. NextAuth 세션 쿠키 생성 (NextAuth encode() 우선 사용)
458
- const nextAuthToken = await encodeNextAuthToken(jwt, secret);
459
- debugLog('createAuthResponse', 'NextAuth session token encoded:', {
460
- tokenLength: nextAuthToken.length,
461
- });
462
- // 4. Response 생성 (HTTP 302 리다이렉트 사용)
457
+ // 3. Response 생성 (HTTP 302 리다이렉트 사용)
463
458
  const { NextResponse: NextResponseClass } = await getNextServer();
464
459
  // redirectPath가 있으면 302 리다이렉트, 없으면 200 OK
465
460
  const response = redirectPath
466
461
  ? NextResponseClass.redirect(new URL(redirectPath, req.url), { status: 302 })
467
462
  : NextResponseClass.json({ success: true, message: text || 'Authentication successful' }, { status: 200 });
468
- // 5. NextAuth 세션 쿠키 설정
469
- const nextAuthCookieName = isProduction
470
- ? '__Secure-next-auth.session-token'
471
- : 'next-auth.session-token';
472
- const cookieOptions = {
473
- httpOnly: true,
474
- secure: isProduction,
475
- sameSite: isProduction ? 'none' : 'lax',
476
- path: '/',
477
- maxAge: 30 * 24 * 60 * 60, // 30일
478
- };
479
- if (cookieDomain) {
480
- cookieOptions.domain = cookieDomain;
463
+ // 4. NextAuth 세션 쿠키 생성 (Edge Runtime에서도 작동하도록 encodeNextAuthToken 사용)
464
+ try {
465
+ const nextAuthToken = await encodeNextAuthToken(jwt, secret);
466
+ const nextAuthCookieName = isProduction
467
+ ? '__Secure-next-auth.session-token'
468
+ : 'next-auth.session-token';
469
+ const cookieOptions = {
470
+ httpOnly: true,
471
+ secure: isProduction,
472
+ sameSite: isProduction ? 'none' : 'lax',
473
+ path: '/',
474
+ maxAge: 30 * 24 * 60 * 60, // 30일
475
+ };
476
+ if (cookieDomain) {
477
+ cookieOptions.domain = cookieDomain;
478
+ }
479
+ response.cookies.set(nextAuthCookieName, nextAuthToken, cookieOptions);
480
+ debugLog('createAuthResponse', 'NextAuth session cookie set:', {
481
+ name: nextAuthCookieName,
482
+ valueLength: nextAuthToken.length,
483
+ hasRefreshToken: !!refreshToken,
484
+ });
481
485
  }
482
- response.cookies.set(nextAuthCookieName, nextAuthToken, cookieOptions);
483
- debugLog('createAuthResponse', 'NextAuth session cookie set:', {
484
- name: nextAuthCookieName,
485
- valueLength: nextAuthToken.length,
486
- ...cookieOptions,
487
- });
488
- // 6. 커스텀 토큰 쿠키 설정
486
+ catch (error) {
487
+ debugError('createAuthResponse', 'Failed to set NextAuth cookie:', error);
488
+ // NextAuth 쿠키 실패해도 커스텀 토큰으로는 작동 가능
489
+ }
490
+ // 5. 커스텀 토큰 쿠키 설정
489
491
  if (refreshToken) {
490
492
  setCustomTokens(response, accessToken, refreshToken, {
491
493
  cookiePrefix,
@@ -1556,12 +1558,35 @@ async function handleMiddleware(req, config, options) {
1556
1558
  const tokenRole = extractRoleFromPayload(payload, serviceId, defaultRole);
1557
1559
  debugLog('handleMiddleware', `Extracted role: ${tokenRole}`);
1558
1560
  // 3. Refresh token 가져오기 (서버 간 통신)
1559
- const userId = payload.sub || payload.userId || '';
1561
+ const userId = payload.id || payload.sub || payload.userId || '';
1560
1562
  const ssoBaseURL = options.ssoBaseURL;
1561
1563
  const authServiceKey = options.authServiceKey;
1562
- const refreshToken = authServiceKey
1563
- ? await getRefreshTokenFromSSO(userId, tokenParam, { ssoBaseURL, authServiceKey }) || ''
1564
- : '';
1564
+ debugLog('handleMiddleware', 'Getting refresh token from SSO:', {
1565
+ userId,
1566
+ hasSSO: !!ssoBaseURL,
1567
+ hasAuthKey: !!authServiceKey,
1568
+ });
1569
+ let refreshToken = '';
1570
+ if (authServiceKey && userId) {
1571
+ try {
1572
+ const refreshTokenResult = await getRefreshTokenFromSSO(userId, tokenParam, { ssoBaseURL, authServiceKey });
1573
+ refreshToken = refreshTokenResult || '';
1574
+ debugLog('handleMiddleware', 'Refresh token result:', {
1575
+ hasRefreshToken: !!refreshToken,
1576
+ length: refreshToken.length,
1577
+ });
1578
+ }
1579
+ catch (error) {
1580
+ debugError('handleMiddleware', 'Failed to get refresh token:', error);
1581
+ // refresh token이 없어도 access token으로는 로그인 가능
1582
+ }
1583
+ }
1584
+ else {
1585
+ debugLog('handleMiddleware', 'Skipping refresh token fetch:', {
1586
+ hasUserId: !!userId,
1587
+ hasAuthKey: !!authServiceKey,
1588
+ });
1589
+ }
1565
1590
  // 4. 자체 토큰 생성 및 쿠키 설정
1566
1591
  const redirectPath = config.rolePaths[tokenRole] || config.rolePaths[defaultRole] || '/admin';
1567
1592
  debugLog('handleMiddleware', `Creating auth response, redirect to: ${redirectPath}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thinkingcat/auth-utils",
3
- "version": "1.0.39",
3
+ "version": "1.0.41",
4
4
  "description": "Authentication utilities for ThinkingCat SSO services with conditional logging",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",