@thinkingcat/auth-utils 1.0.4 → 1.0.6

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # @thinkingcat/auth-token-utils
1
+ # @thinkingcat/auth-utils
2
2
 
3
- ThinkingCat SSO 서비스를 위한 인증 토큰 유틸리티 패키지입니다. JWT 토큰 검증, NextAuth 세션 생성, 쿠키 설정 등의 기능을 제공합니다.
3
+ ThinkingCat SSO 서비스를 위한 인증 유틸리티 패키지입니다. JWT 토큰 검증, NextAuth 세션 생성, 쿠키 설정, 역할 기반 접근 제어, 미들웨어 헬퍼 등의 광범위한 인증 기능을 제공합니다.
4
4
 
5
5
  ## 📑 목차 (Table of Contents)
6
6
 
@@ -35,19 +35,19 @@ ThinkingCat SSO 서비스를 위한 인증 토큰 유틸리티 패키지입니
35
35
  ### npm 사용
36
36
 
37
37
  ```bash
38
- npm install @thinkingcat/auth-token-utils
38
+ npm install @thinkingcat/auth-utils
39
39
  ```
40
40
 
41
41
  ### yarn 사용
42
42
 
43
43
  ```bash
44
- yarn add @thinkingcat/auth-token-utils
44
+ yarn add @thinkingcat/auth-utils
45
45
  ```
46
46
 
47
47
  ### pnpm 사용
48
48
 
49
49
  ```bash
50
- pnpm add @thinkingcat/auth-token-utils
50
+ pnpm add @thinkingcat/auth-utils
51
51
  ```
52
52
 
53
53
  ## 📋 요구사항 (Requirements)
@@ -63,13 +63,13 @@ pnpm add @thinkingcat/auth-token-utils
63
63
  npm에 배포된 패키지를 사용할 때는 **별도의 설정이 필요하지 않습니다**. 바로 사용할 수 있습니다.
64
64
 
65
65
  ```bash
66
- npm install @thinkingcat/auth-token-utils
66
+ npm install @thinkingcat/auth-utils
67
67
  ```
68
68
 
69
69
  ```json
70
70
  {
71
71
  "dependencies": {
72
- "@thinkingcat/auth-token-utils": "^1.0.0"
72
+ "@thinkingcat/auth-utils": "^1.0.4"
73
73
  }
74
74
  }
75
75
  ```
@@ -87,7 +87,7 @@ npm install @thinkingcat/auth-token-utils
87
87
  ```typescript
88
88
  /** @type {import('next').NextConfig} */
89
89
  const nextConfig = {
90
- transpilePackages: ["@thinkingcat/auth-token-utils"],
90
+ transpilePackages: ["@thinkingcat/auth-utils"],
91
91
  // ... 기타 설정
92
92
  };
93
93
 
@@ -107,7 +107,7 @@ module.exports = nextConfig;
107
107
  ```json
108
108
  {
109
109
  "dependencies": {
110
- "@thinkingcat/auth-token-utils": "^1.0.0"
110
+ "@thinkingcat/auth-utils": "^1.0.4"
111
111
  }
112
112
  }
113
113
  ```
@@ -134,7 +134,7 @@ import {
134
134
  ServiceInfo,
135
135
  ResponseLike,
136
136
  JWTPayload,
137
- } from "@thinkingcat/auth-token-utils";
137
+ } from "@thinkingcat/auth-utils";
138
138
  ```
139
139
 
140
140
  ### 2. 환경 변수 설정
@@ -158,6 +158,12 @@ COOKIE_DOMAIN=.yourdomain.com # 선택사항
158
158
  5. **쿠키 설정**: 자체 토큰 및 NextAuth 토큰 쿠키 설정
159
159
  6. **리다이렉트 HTML**: 클라이언트 리다이렉트용 HTML 생성
160
160
  7. **완전한 인증 응답**: 모든 인증 단계를 한 번에 처리
161
+ 8. **미들웨어 헬퍼**: 에러 리다이렉트, 쿠키 삭제, SSO 로그인 리다이렉트 등
162
+ 9. **역할 기반 접근 제어**: 경로별 역할 검증 및 접근 제어
163
+ 10. **구독 검증**: 서비스 구독 상태 확인
164
+ 11. **토큰 유효성 검사**: 토큰 만료 및 유효성 확인
165
+ 12. **경로 체크**: 공개 경로, API 경로, 보호된 경로 확인
166
+ 13. **통합 인증 체크**: NextAuth와 자체 토큰을 모두 확인하는 통합 함수
161
167
 
162
168
  ## 🔧 API 레퍼런스
163
169
 
@@ -412,7 +418,7 @@ import {
412
418
  setCustomTokens,
413
419
  createRedirectHTML,
414
420
  JWTPayload,
415
- } from "@thinkingcat/auth-token-utils";
421
+ } from "@thinkingcat/auth-utils";
416
422
 
417
423
  export async function GET(req: NextRequest) {
418
424
  // URL 파라미터에서 토큰 가져오기 (초기 로그인 시)
@@ -458,7 +464,7 @@ export async function GET(req: NextRequest) {
458
464
 
459
465
  ```typescript
460
466
  import { NextRequest, NextResponse } from "next/server";
461
- import { verifyToken, JWTPayload } from "@thinkingcat/auth-token-utils";
467
+ import { verifyToken, JWTPayload } from "@thinkingcat/auth-utils";
462
468
 
463
469
  export async function GET(req: NextRequest) {
464
470
  const secret = process.env.NEXTAUTH_SECRET!;
@@ -530,7 +536,7 @@ import {
530
536
  createNextAuthJWT,
531
537
  encodeNextAuthToken,
532
538
  setNextAuthToken,
533
- } from "@thinkingcat/auth-token-utils";
539
+ } from "@thinkingcat/auth-utils";
534
540
 
535
541
  export async function GET(req: NextRequest) {
536
542
  const tokenParam = req.nextUrl.searchParams.get("token");
@@ -574,7 +580,7 @@ import {
574
580
  setCustomTokens,
575
581
  setNextAuthToken,
576
582
  createRedirectHTML,
577
- } from "@thinkingcat/auth-token-utils";
583
+ } from "@thinkingcat/auth-utils";
578
584
 
579
585
  export async function GET(req: NextRequest) {
580
586
  const tokenParam = req.nextUrl.searchParams.get("token");
@@ -642,7 +648,7 @@ import {
642
648
  setNextAuthToken,
643
649
  createNextAuthJWT,
644
650
  encodeNextAuthToken,
645
- } from "@thinkingcat/auth-token-utils";
651
+ } from "@thinkingcat/auth-utils";
646
652
 
647
653
  export async function middleware(req: NextRequest) {
648
654
  const secret = process.env.NEXTAUTH_SECRET!;
@@ -857,7 +863,7 @@ import type {
857
863
  SSORefreshTokenResponse,
858
864
  SSOGetRefreshTokenResponse,
859
865
  SSORegisterResponse,
860
- } from "@thinkingcat/auth-token-utils";
866
+ } from "@thinkingcat/auth-utils";
861
867
 
862
868
  // SSO API 호출 시 타입 사용
863
869
  const response = await fetch("/api/sso/refresh", {
@@ -896,13 +902,13 @@ interface ResponseLike {
896
902
 
897
903
  ## 🐛 문제 해결 (Troubleshooting)
898
904
 
899
- ### 문제 1: "Cannot find module '@thinkingcat/auth-token-utils'"
905
+ ### 문제 1: "Cannot find module '@thinkingcat/auth-utils'"
900
906
 
901
907
  **해결 방법:**
902
908
 
903
909
  ```bash
904
910
  # 패키지 재설치
905
- npm install @thinkingcat/auth-token-utils
911
+ npm install @thinkingcat/auth-utils
906
912
 
907
913
  # 또는 node_modules 삭제 후 재설치
908
914
  rm -rf node_modules package-lock.json
@@ -932,8 +938,8 @@ npm install
932
938
 
933
939
  ## 📦 패키지 정보
934
940
 
935
- - **패키지명**: `@thinkingcat/auth-token-utils`
936
- - **버전**: `1.0.0`
941
+ - **패키지명**: `@thinkingcat/auth-utils`
942
+ - **버전**: `1.0.4`
937
943
  - **라이선스**: MIT
938
944
  - **저장소**: npm registry
939
945
 
package/dist/index.d.ts CHANGED
@@ -291,6 +291,29 @@ export interface RoleAccessConfig {
291
291
  allowedRoles?: string[];
292
292
  };
293
293
  }
294
+ /**
295
+ * 미들웨어 설정 인터페이스
296
+ */
297
+ export interface MiddlewareConfig {
298
+ /** 공개 접근 가능한 경로 배열 */
299
+ publicPaths?: string[];
300
+ /** 구독이 필요한 경로 배열 */
301
+ subscriptionRequiredPaths?: string[];
302
+ /** 구독 상태 확인을 제외할 API 경로 배열 */
303
+ subscriptionExemptApiPaths?: string[];
304
+ /** 인증 관련 API 경로 배열 */
305
+ authApiPaths?: string[];
306
+ /** 역할별 대시보드 경로 객체 */
307
+ rolePaths?: Record<string, string>;
308
+ /** 역할 기반 접근 제어 설정 */
309
+ roleAccessConfig?: RoleAccessConfig;
310
+ /** 서비스 ID */
311
+ serviceId?: string;
312
+ /** 시스템 관리자 역할명 (기본값: 'SYSTEM_ADMIN') */
313
+ systemAdminRole?: string;
314
+ /** 에러 페이지 경로 (기본값: '/error') */
315
+ errorPath?: string;
316
+ }
294
317
  export declare function checkRoleAccess(pathname: string, role: string, roleConfig: RoleAccessConfig): {
295
318
  allowed: boolean;
296
319
  message?: string;
@@ -382,3 +405,31 @@ export declare function checkAuthentication(req: NextRequest, secret: string, op
382
405
  response?: NextResponse;
383
406
  error?: string;
384
407
  }>;
408
+ /**
409
+ * NextAuth 토큰과 자체 토큰을 모두 확인하는 미들웨어용 함수
410
+ * NextAuth 토큰이 있으면 바로 통과, 없으면 자체 토큰을 확인
411
+ * @param req NextRequest 객체
412
+ * @param nextAuthToken NextAuth JWT 토큰 (null 가능)
413
+ * @param secret JWT 서명에 사용할 secret key
414
+ * @param options 옵션
415
+ * @returns 인증 결과
416
+ */
417
+ export declare function verifyAndRefreshTokenWithNextAuth(req: NextRequest, nextAuthToken: JWT | null, secret: string, options?: {
418
+ cookiePrefix?: string;
419
+ isProduction?: boolean;
420
+ cookieDomain?: string;
421
+ text?: string;
422
+ ssoBaseURL?: string;
423
+ authServiceKey?: string;
424
+ }): Promise<{
425
+ isValid: boolean;
426
+ response?: NextResponse;
427
+ error?: string;
428
+ payload?: JWTPayload;
429
+ }>;
430
+ /**
431
+ * 기본 미들웨어 설정을 생성하는 함수
432
+ * @param config 커스텀 설정 (선택사항)
433
+ * @returns 미들웨어 설정 객체
434
+ */
435
+ export declare function createMiddlewareConfig(config?: Partial<MiddlewareConfig>): Required<Omit<MiddlewareConfig, 'serviceId'>> & Pick<MiddlewareConfig, 'serviceId'>;
package/dist/index.js CHANGED
@@ -27,6 +27,8 @@ exports.isPublicPath = isPublicPath;
27
27
  exports.isApiPath = isApiPath;
28
28
  exports.isProtectedApiPath = isProtectedApiPath;
29
29
  exports.checkAuthentication = checkAuthentication;
30
+ exports.verifyAndRefreshTokenWithNextAuth = verifyAndRefreshTokenWithNextAuth;
31
+ exports.createMiddlewareConfig = createMiddlewareConfig;
30
32
  const jwt_1 = require("next-auth/jwt");
31
33
  const jose_1 = require("jose");
32
34
  const server_1 = require("next/server");
@@ -707,3 +709,86 @@ async function checkAuthentication(req, secret, options) {
707
709
  error: authCheck.error || 'NO_TOKEN',
708
710
  };
709
711
  }
712
+ /**
713
+ * NextAuth 토큰과 자체 토큰을 모두 확인하는 미들웨어용 함수
714
+ * NextAuth 토큰이 있으면 바로 통과, 없으면 자체 토큰을 확인
715
+ * @param req NextRequest 객체
716
+ * @param nextAuthToken NextAuth JWT 토큰 (null 가능)
717
+ * @param secret JWT 서명에 사용할 secret key
718
+ * @param options 옵션
719
+ * @returns 인증 결과
720
+ */
721
+ async function verifyAndRefreshTokenWithNextAuth(req, nextAuthToken, secret, options) {
722
+ // 1. NextAuth 토큰이 있고 유효하면 통과
723
+ if (nextAuthToken && isValidToken(nextAuthToken)) {
724
+ return { isValid: true };
725
+ }
726
+ // 2. 자체 토큰 확인 및 리프레시
727
+ const authCheck = await verifyAndRefreshToken(req, secret, options);
728
+ return authCheck;
729
+ }
730
+ /**
731
+ * 기본 미들웨어 설정을 생성하는 함수
732
+ * @param config 커스텀 설정 (선택사항)
733
+ * @returns 미들웨어 설정 객체
734
+ */
735
+ function createMiddlewareConfig(config) {
736
+ const defaultConfig = {
737
+ publicPaths: [
738
+ '/robots.txt',
739
+ '/sitemap.xml',
740
+ '/ads.txt',
741
+ '/images',
742
+ '/login',
743
+ '/register',
744
+ '/forgot-password',
745
+ '/reset-password',
746
+ '/about',
747
+ '/pricing',
748
+ '/support',
749
+ '/terms',
750
+ '/privacy',
751
+ '/refund',
752
+ '/error',
753
+ ],
754
+ subscriptionRequiredPaths: [
755
+ '/admin',
756
+ '/teacher',
757
+ '/student',
758
+ '/personal',
759
+ ],
760
+ subscriptionExemptApiPaths: [
761
+ '/api/auth',
762
+ '/api/sso',
763
+ '/api/admin/subscription',
764
+ '/api/admin/payment-methods',
765
+ ],
766
+ authApiPaths: [
767
+ '/api/auth/send-verification',
768
+ '/api/auth/verify-code',
769
+ '/api/auth/verify-user',
770
+ '/api/auth/select-academy',
771
+ ],
772
+ rolePaths: {
773
+ SYSTEM_ADMIN: '/system',
774
+ ADMIN: '/admin',
775
+ TEACHER: '/teacher',
776
+ STUDENT: '/student',
777
+ },
778
+ roleAccessConfig: {},
779
+ systemAdminRole: 'SYSTEM_ADMIN',
780
+ errorPath: '/error',
781
+ serviceId: config?.serviceId,
782
+ };
783
+ // 커스텀 설정으로 병합
784
+ return {
785
+ ...defaultConfig,
786
+ ...config,
787
+ publicPaths: config?.publicPaths || defaultConfig.publicPaths,
788
+ subscriptionRequiredPaths: config?.subscriptionRequiredPaths || defaultConfig.subscriptionRequiredPaths,
789
+ subscriptionExemptApiPaths: config?.subscriptionExemptApiPaths || defaultConfig.subscriptionExemptApiPaths,
790
+ authApiPaths: config?.authApiPaths || defaultConfig.authApiPaths,
791
+ rolePaths: config?.rolePaths || defaultConfig.rolePaths,
792
+ roleAccessConfig: config?.roleAccessConfig || defaultConfig.roleAccessConfig,
793
+ };
794
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thinkingcat/auth-utils",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Authentication utilities for ThinkingCat SSO services",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",