@thinkingcat/auth-utils 1.0.19 → 1.0.20

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/dist/index.d.ts CHANGED
@@ -468,6 +468,8 @@ export declare function handleJWTCallback(token: JWT, user?: {
468
468
  serviceId?: string;
469
469
  cookieName?: string;
470
470
  debug?: boolean;
471
+ ssoBaseURL?: string;
472
+ authServiceKey?: string;
471
473
  }): Promise<JWT>;
472
474
  /**
473
475
  * 쿠키에서 커스텀 토큰을 읽어서 NextAuth JWT로 변환하는 헬퍼 함수
package/dist/index.js CHANGED
@@ -871,13 +871,14 @@ function mapTokenToSession(session, token) {
871
871
  * @returns 업데이트된 JWT 토큰
872
872
  */
873
873
  async function handleJWTCallback(token, user, account, options) {
874
- const { secret, licenseKey, serviceId, cookieName, debug = false, } = options || {};
874
+ const { secret, licenseKey, serviceId, cookieName, debug = false, ssoBaseURL, authServiceKey, } = options || {};
875
875
  // 디버깅 로그
876
876
  if (debug) {
877
877
  debugLog('handleJWTCallback', 'Token received:', {
878
878
  hasId: !!token.id,
879
879
  hasEmail: !!token.email,
880
880
  hasRole: !!token.role,
881
+ hasExpires: !!token.accessTokenExpires,
881
882
  });
882
883
  }
883
884
  // 1. 초기 로그인 시 (providers를 통한 로그인)
@@ -885,9 +886,58 @@ async function handleJWTCallback(token, user, account, options) {
885
886
  debugLog('handleJWTCallback', 'Initial login, creating token from user data');
886
887
  return createInitialJWTToken(token, user, account);
887
888
  }
888
- // 2. 이미 토큰에 정보가 있으면 그대로 사용
889
+ // 2. 이미 토큰에 정보가 있는 경우 - 만료 체크 및 갱신
889
890
  if (token.id) {
890
- debugLog('handleJWTCallback', 'Token already has id, using existing token');
891
+ const now = Date.now();
892
+ const expires = token.accessTokenExpires;
893
+ // 2-1. 토큰이 만료되지 않았으면 그대로 사용
894
+ if (expires && expires > now) {
895
+ debugLog('handleJWTCallback', 'Token is still valid, using existing token');
896
+ return token;
897
+ }
898
+ // 2-2. 토큰이 만료되었으면 refresh token으로 갱신 시도
899
+ debugLog('handleJWTCallback', 'Token expired or no expiry, attempting refresh');
900
+ const refreshToken = token.refreshToken;
901
+ if (refreshToken && ssoBaseURL && authServiceKey) {
902
+ try {
903
+ debugLog('handleJWTCallback', 'Calling SSO refresh endpoint');
904
+ const response = await fetch(`${ssoBaseURL}/api/sso/refresh`, {
905
+ method: 'POST',
906
+ headers: {
907
+ 'Content-Type': 'application/json',
908
+ 'x-auth-service-key': authServiceKey,
909
+ },
910
+ body: JSON.stringify({ refreshToken }),
911
+ });
912
+ if (response.ok) {
913
+ const result = await response.json();
914
+ if (result.success && result.accessToken) {
915
+ debugLog('handleJWTCallback', 'Successfully refreshed token');
916
+ // 새 액세스 토큰 검증 및 페이로드 추출
917
+ if (secret) {
918
+ const tokenResult = await verifyToken(result.accessToken, secret);
919
+ if (tokenResult) {
920
+ const newJWT = createNextAuthJWT(tokenResult.payload, serviceId || '');
921
+ return {
922
+ ...newJWT,
923
+ refreshToken, // 기존 refresh token 유지
924
+ accessTokenExpires: Date.now() + (15 * 60 * 1000), // 15분
925
+ };
926
+ }
927
+ }
928
+ }
929
+ }
930
+ debugLog('handleJWTCallback', 'Failed to refresh token, SSO response not ok');
931
+ }
932
+ catch (error) {
933
+ console.error('[handleJWTCallback] Error refreshing token:', error);
934
+ }
935
+ }
936
+ else {
937
+ debugLog('handleJWTCallback', 'Missing refresh token or SSO config, cannot refresh');
938
+ }
939
+ // 갱신 실패 시 기존 토큰 반환 (만료되었지만)
940
+ debugLog('handleJWTCallback', 'Returning existing token (possibly expired)');
891
941
  return token;
892
942
  }
893
943
  // 3. 토큰에 id가 없는 경우 - 커스텀 토큰 쿠키에서 정보 읽기
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thinkingcat/auth-utils",
3
- "version": "1.0.19",
3
+ "version": "1.0.20",
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",