@thinkingcat/auth-utils 1.0.40 → 1.0.42

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 +70 -7
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -460,9 +460,33 @@ async function createAuthResponse(accessToken, secret, options) {
460
460
  const response = redirectPath
461
461
  ? NextResponseClass.redirect(new URL(redirectPath, req.url), { status: 302 })
462
462
  : NextResponseClass.json({ success: true, message: text || 'Authentication successful' }, { status: 200 });
463
- // 4. 처음 로그인 시에는 NextAuth 쿠키를 생성하지 않음
464
- // Edge Runtime에서 생성한 NextAuth 쿠키는 Node.js Runtime에서 디코드 실패
465
- // 대신 커스텀 토큰만 설정하고, handleJWTCallback이 이를 읽어서 세션 생성
463
+ // 4. NextAuth 세션 쿠키 생성 (Edge Runtime에서도 작동하도록 encodeNextAuthToken 사용)
464
+ const nextAuthCookieName = isProduction
465
+ ? '__Secure-next-auth.session-token'
466
+ : 'next-auth.session-token';
467
+ try {
468
+ const nextAuthToken = await encodeNextAuthToken(jwt, secret);
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
+ });
485
+ }
486
+ catch (error) {
487
+ debugError('createAuthResponse', 'Failed to set NextAuth cookie:', error);
488
+ // NextAuth 쿠키 실패해도 커스텀 토큰으로는 작동 가능
489
+ }
466
490
  // 5. 커스텀 토큰 쿠키 설정
467
491
  if (refreshToken) {
468
492
  setCustomTokens(response, accessToken, refreshToken, {
@@ -479,6 +503,11 @@ async function createAuthResponse(accessToken, secret, options) {
479
503
  });
480
504
  }
481
505
  debugLog('createAuthResponse', 'Custom tokens set successfully');
506
+ console.log('[createAuthResponse] All cookies set:', {
507
+ nextAuthCookie: nextAuthCookieName,
508
+ accessTokenCookie: `${cookiePrefix}_access_token`,
509
+ refreshTokenCookie: refreshToken ? `${cookiePrefix}_refresh_token` : 'none',
510
+ });
482
511
  return response;
483
512
  }
484
513
  // ============================================================================
@@ -1534,15 +1563,45 @@ async function handleMiddleware(req, config, options) {
1534
1563
  const tokenRole = extractRoleFromPayload(payload, serviceId, defaultRole);
1535
1564
  debugLog('handleMiddleware', `Extracted role: ${tokenRole}`);
1536
1565
  // 3. Refresh token 가져오기 (서버 간 통신)
1537
- const userId = payload.sub || payload.userId || '';
1566
+ const userId = payload.id || payload.sub || payload.userId || '';
1538
1567
  const ssoBaseURL = options.ssoBaseURL;
1539
1568
  const authServiceKey = options.authServiceKey;
1540
- const refreshToken = authServiceKey
1541
- ? await getRefreshTokenFromSSO(userId, tokenParam, { ssoBaseURL, authServiceKey }) || ''
1542
- : '';
1569
+ debugLog('handleMiddleware', 'Getting refresh token from SSO:', {
1570
+ userId,
1571
+ hasSSO: !!ssoBaseURL,
1572
+ hasAuthKey: !!authServiceKey,
1573
+ });
1574
+ let refreshToken = '';
1575
+ if (authServiceKey && userId) {
1576
+ try {
1577
+ const refreshTokenResult = await getRefreshTokenFromSSO(userId, tokenParam, { ssoBaseURL, authServiceKey });
1578
+ refreshToken = refreshTokenResult || '';
1579
+ debugLog('handleMiddleware', 'Refresh token result:', {
1580
+ hasRefreshToken: !!refreshToken,
1581
+ length: refreshToken.length,
1582
+ });
1583
+ }
1584
+ catch (error) {
1585
+ debugError('handleMiddleware', 'Failed to get refresh token:', error);
1586
+ // refresh token이 없어도 access token으로는 로그인 가능
1587
+ }
1588
+ }
1589
+ else {
1590
+ debugLog('handleMiddleware', 'Skipping refresh token fetch:', {
1591
+ hasUserId: !!userId,
1592
+ hasAuthKey: !!authServiceKey,
1593
+ });
1594
+ }
1543
1595
  // 4. 자체 토큰 생성 및 쿠키 설정
1544
1596
  const redirectPath = config.rolePaths[tokenRole] || config.rolePaths[defaultRole] || '/admin';
1545
1597
  debugLog('handleMiddleware', `Creating auth response, redirect to: ${redirectPath}`);
1598
+ console.log('[handleMiddleware] Creating auth response:', {
1599
+ redirectPath,
1600
+ hasRefreshToken: !!refreshToken,
1601
+ cookiePrefix,
1602
+ isProduction,
1603
+ cookieDomain,
1604
+ });
1546
1605
  const response = await createAuthResponse(tokenParam, secret, {
1547
1606
  req,
1548
1607
  refreshToken: refreshToken || undefined,
@@ -1554,6 +1613,10 @@ async function handleMiddleware(req, config, options) {
1554
1613
  serviceId,
1555
1614
  licenseKey: options.licenseKey,
1556
1615
  });
1616
+ console.log('[handleMiddleware] Auth response created, cookies set:', {
1617
+ hasResponse: !!response,
1618
+ cookieNames: ['renton_access_token', 'renton_refresh_token', isProduction ? '__Secure-next-auth.session-token' : 'next-auth.session-token'],
1619
+ });
1557
1620
  return response;
1558
1621
  }
1559
1622
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thinkingcat/auth-utils",
3
- "version": "1.0.40",
3
+ "version": "1.0.42",
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",