diff --git a/nest-cli.json b/nest-cli.json index f9aa683..ec3a362 100644 --- a/nest-cli.json +++ b/nest-cli.json @@ -3,6 +3,16 @@ "collection": "@nestjs/schematics", "sourceRoot": "src", "compilerOptions": { - "deleteOutDir": true + "deleteOutDir": true, + "plugins": [ + { + "name": "@nestjs/swagger", + "options": { + "classValidatorShim": false, + "introspectComments": true, + "skipAutoHttpCode": true + } + } + ] } } diff --git a/package-lock.json b/package-lock.json index 36a2d2b..19e4507 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@nestjs/core": "^11.0.1", "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.2.1", + "jose": "^6.1.0", "mongoose": "^8.19.3", "nats": "^2.29.3", "reflect-metadata": "^0.2.2", @@ -502,7 +503,6 @@ "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.600.0.tgz", "integrity": "sha512-KQG97B7LvTtTiGmjlrG1LRAY8wUvCQzrmZVV5bjrJ/1oXAU7DITYwVbSJeX9NWg6hDuSk0VE3MFwIXS2SvfLIA==", "license": "Apache-2.0", - "peer": true, "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", @@ -1421,7 +1421,6 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -3353,7 +3352,6 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -3538,7 +3536,6 @@ "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.8.tgz", "integrity": "sha512-bbsOqwld/GdBfiRNc4nnjyWWENDEicq4SH+R5AuYatvf++vf1x5JIsHB1i1KtfZMD3eRte0D4K9WXuAYil6XAg==", "license": "MIT", - "peer": true, "dependencies": { "file-type": "21.0.0", "iterare": "1.2.1", @@ -3586,7 +3583,6 @@ "integrity": "sha512-7riWfmTmMhCJHZ5ZiaG+crj4t85IPCq/wLRuOUSigBYyFT2JZj0lVHtAdf4Davp9ouNI8GINBDt9h9b5Gz9nTw==", "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "@nuxt/opencollective": "0.4.1", "fast-safe-stringify": "2.1.1", @@ -3647,7 +3643,6 @@ "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.8.tgz", "integrity": "sha512-rL6pZH9BW7BnL5X2eWbJMtt86uloAKjFgyY5+L2UkizgfEp7rgAs0+Z1z0BcW2Pgu5+q8O7RKPNyHJ/9ZNz/ZQ==", "license": "MIT", - "peer": true, "dependencies": { "cors": "2.8.5", "express": "5.1.0", @@ -4755,7 +4750,6 @@ "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -4876,7 +4870,6 @@ "integrity": "sha512-xpr/lmLPQEj+TUnHmR+Ab91/glhJvsqcjB+yY0Ix9GO70H6Lb4FHH5GeqdOE5btAx7eIMwuHkp4H2MSkLcqWbA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -5037,7 +5030,6 @@ "integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/types": "8.46.3", @@ -5720,7 +5712,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5770,7 +5761,6 @@ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -6207,7 +6197,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -6415,7 +6404,6 @@ "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "readdirp": "^4.0.1" }, @@ -7127,7 +7115,6 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -7188,7 +7175,6 @@ "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", "dev": true, "license": "MIT", - "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -8510,7 +8496,6 @@ "integrity": "sha512-F26gjC0yWN8uAA5m5Ss8ZQf5nDHWGlN/xWZIh8S5SRbsEKBovwZhxGd6LJlbZYxBgCYOtreSUyb8hpXyGC5O4A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@jest/core": "30.2.0", "@jest/types": "30.2.0", @@ -9280,6 +9265,15 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jose": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.0.tgz", + "integrity": "sha512-TTQJyoEoKcC1lscpVDCSsVgYzUDg/0Bt3WE//WiTPK6uOCQC2KZS4MpugbMWt/zyjkopgZoXhZuCi00gLudfUA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -10461,7 +10455,6 @@ "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -10667,8 +10660,7 @@ "version": "0.2.2", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", - "license": "Apache-2.0", - "peer": true + "license": "Apache-2.0" }, "node_modules/require-directory": { "version": "2.1.1", @@ -10800,7 +10792,6 @@ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "license": "Apache-2.0", - "peer": true, "dependencies": { "tslib": "^2.1.0" } @@ -11508,7 +11499,6 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -11828,7 +11818,6 @@ "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", @@ -11981,7 +11970,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -12341,6 +12329,7 @@ "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "ajv": "^8.0.0" }, @@ -12359,6 +12348,7 @@ "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3" }, @@ -12372,6 +12362,7 @@ "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "dev": true, "license": "BSD-2-Clause", + "peer": true, "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" @@ -12386,6 +12377,7 @@ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "dev": true, "license": "BSD-2-Clause", + "peer": true, "engines": { "node": ">=4.0" } @@ -12395,7 +12387,8 @@ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/webpack/node_modules/mime-db": { "version": "1.52.0", @@ -12403,6 +12396,7 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 0.6" } @@ -12413,6 +12407,7 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -12426,6 +12421,7 @@ "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", diff --git a/package.json b/package.json index 40a4ca8..52d76da 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "@nestjs/core": "^11.0.1", "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.2.1", + "jose": "^6.1.0", "mongoose": "^8.19.3", "nats": "^2.29.3", "reflect-metadata": "^0.2.2", diff --git a/src/app.controller.ts b/src/app.controller.ts index cce879e..6cba703 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -1,12 +1,16 @@ -import { Controller, Get } from '@nestjs/common'; +import { Controller, Get, UseGuards } from '@nestjs/common'; import { AppService } from './app.service'; +import { JwtAuthGuard } from './modules/global/auth/jwt.guard'; +import { AllowPublicAccess } from './modules/global/auth/allow-public-access.decorator'; +@UseGuards(JwtAuthGuard) @Controller() export class AppController { constructor(private readonly appService: AppService) {} + @AllowPublicAccess() @Get() - getHello(): string { - return this.appService.getHello(); + isHealthy(): string { + return this.appService.isHealthy(); } } diff --git a/src/app.module.ts b/src/app.module.ts index 3514acb..09096f4 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -3,6 +3,7 @@ import { AppController } from './app.controller'; import { AppService } from './app.service'; import { GlobalModule } from './modules/global/global.module'; import { ConfigModule } from '@nestjs/config'; +import { AccountModule } from './modules/account/account.module'; @Module({ imports: [ @@ -10,7 +11,8 @@ import { ConfigModule } from '@nestjs/config'; isGlobal: true, envFilePath: process.env.NODE_ENV === 'prod' ? '.env.prod' : process.env.NODE_ENV === 'test' ? '.env.test' : '.env.dev', }), - GlobalModule], + GlobalModule, + AccountModule], controllers: [AppController], providers: [AppService], }) diff --git a/src/app.service.ts b/src/app.service.ts index 927d7cc..fd36230 100644 --- a/src/app.service.ts +++ b/src/app.service.ts @@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { - getHello(): string { - return 'Hello World!'; + // getHello(): string { + // return 'Hello World!'; + // } + isHealthy(): string { + return 'OK'; } } diff --git a/src/main.ts b/src/main.ts index 565236d..ee03f58 100644 --- a/src/main.ts +++ b/src/main.ts @@ -5,20 +5,24 @@ import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); + const apiVersion = 1; - const config = new DocumentBuilder() - .setTitle('Cats example') - .setDescription('The cats API description') - .setVersion('1.0') - .addTag('cats') - .build(); - const options: SwaggerCustomOptions = { - ui: false, // Swagger UI is disabled - raw: ['yaml'], // JSON API definition is still accessible (YAML is disabled) -} - const documentFactory = () => SwaggerModule.createDocument(app, config); - SwaggerModule.setup('api', app, documentFactory, options); + if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') { + const config = new DocumentBuilder() + .setTitle('Gemwiki API') + .setDescription('The Gemwiki API description') + .setVersion('1.0') + .addTag('gemwiki') + .build(); + const options: SwaggerCustomOptions = { + ui: false, + raw: ['yaml'], + } + const documentFactory = () => SwaggerModule.createDocument(app, config); + SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options); + } - await app.listen(process.env.PORT ?? 3000); + app.setGlobalPrefix(`v${apiVersion}`); + await app.listen(process.env.PORT ?? 3415); } bootstrap(); diff --git a/src/modules/account/account.controller.ts b/src/modules/account/account.controller.ts new file mode 100644 index 0000000..0194e99 --- /dev/null +++ b/src/modules/account/account.controller.ts @@ -0,0 +1,20 @@ +import { Controller, Get, UseGuards } from "@nestjs/common"; +import { AccountService } from "./account.service"; +import { JwtAuthGuard } from "../global/auth/jwt.guard"; + +@Controller('account') +export class AccountController { + constructor(private readonly accountService: AccountService) {} + + @Get('signin') + signIn(): string { + return this.accountService.signIn(); + } + + + @Get() + @UseGuards(JwtAuthGuard) + getAccountInfo(): string { + return this.accountService.getAccountInfo(); + } +} diff --git a/src/modules/account/account.module.ts b/src/modules/account/account.module.ts new file mode 100644 index 0000000..1332c53 --- /dev/null +++ b/src/modules/account/account.module.ts @@ -0,0 +1,9 @@ +import { Module } from "@nestjs/common"; +import { AccountController } from "./account.controller"; +import { AccountService } from "./account.service"; + +@Module({ + controllers: [AccountController], + providers: [AccountService], +}) +export class AccountModule {} \ No newline at end of file diff --git a/src/modules/account/account.service.ts b/src/modules/account/account.service.ts new file mode 100644 index 0000000..4401fd4 --- /dev/null +++ b/src/modules/account/account.service.ts @@ -0,0 +1,12 @@ +import { Injectable } from "@nestjs/common"; + +@Injectable() +export class AccountService { + signIn(): string { + return 'Sign In Successful'; + } + + getAccountInfo(): string { + return 'Account Information'; + } +} diff --git a/src/modules/global/auth/allow-public-access.decorator.ts b/src/modules/global/auth/allow-public-access.decorator.ts new file mode 100644 index 0000000..5c933ab --- /dev/null +++ b/src/modules/global/auth/allow-public-access.decorator.ts @@ -0,0 +1,4 @@ +// auth/public.decorator.ts +import { SetMetadata } from '@nestjs/common'; +export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = 'IS_PUBLIC_ACCESS_ALLOWED'; +export const AllowPublicAccess = () => SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true); diff --git a/src/modules/global/auth/jwt.guard.ts b/src/modules/global/auth/jwt.guard.ts new file mode 100644 index 0000000..e027e7e --- /dev/null +++ b/src/modules/global/auth/jwt.guard.ts @@ -0,0 +1,96 @@ +// src/auth/jwt.guard.ts +import { + CanActivate, + ExecutionContext, + Injectable, + UnauthorizedException, + ForbiddenException, +} from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import { IdentityProviderName, JwtService } from './jwt.service'; +import { decodeJwt } from 'jose'; +import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator'; + +@Injectable() +export class JwtAuthGuard implements CanActivate { + constructor( + private readonly reflector: Reflector, + private readonly jwtService: JwtService, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const isPublicAccessAllowed = this.reflector.getAllAndOverride(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [ + context.getHandler(), + context.getClass(), + ]); + if (isPublicAccessAllowed) return true; + + const request = context.switchToHttp().getRequest(); + const authz = request.headers?.authorization as string | undefined; + + if (!authz || !authz.startsWith('Bearer ')) { + throw new UnauthorizedException('Missing or invalid Authorization header'); + } + const token = authz.slice('Bearer '.length).trim(); + if (!token) { + throw new UnauthorizedException('Empty bearer token'); + } + + // let identityProvider = + // this.reflector.getAllAndOverride(IDP_KEY, [ + // context.getHandler(), + // context.getClass(), + // ]); + + // if (!identityProvider) { + + // } + let identityProvider: IdentityProviderName; + try { + const { iss } = decodeJwt(token) as { iss?: string }; + if (!iss) { + throw new UnauthorizedException('Token has no issuer (iss) claim'); + } + identityProvider = this.pickIdPFromIssuer(iss); + } catch (e) { + throw new UnauthorizedException( + e instanceof Error ? e.message : 'Unable to decode token', + ); + } + + try { + const verifyResult = await this.jwtService.verify(token, identityProvider); + request.user = verifyResult.payload; + request.tokenHeader = verifyResult.protectedHeader; + request.identityProvider = identityProvider; + + return true; + } catch (e) { + const msg = e instanceof Error ? e.message : 'JWT verification failed'; + // iss/aud 불일치는 보통 401, 접근권한 이슈는 403 (여기선 401로 통일) + throw new UnauthorizedException(msg); + } + } + + /** + * issuer(iss)로부터 IdP 추정 + * - Entra ID: https://login.microsoftonline.com//v2.0 + * - Cognito: https://cognito-idp..amazonaws.com/ + */ + private pickIdPFromIssuer(issuer: string): IdentityProviderName { + const lower = issuer.toLowerCase(); + + if (lower.includes('login.microsoftonline.com')) { + return 'MICROSOFT_ENTRAID'; + } + if (lower.includes('cognito-idp.') && lower.includes('.amazonaws.com')) { + return 'AMAZON_COGNITO'; + } + + // 필요하다면 여기서 jwtService 내부에 등록된 issuer들로 엄격 매칭하도록 변경 가능: + // const configuredIssuers = this.jwtService.getConfiguredIssuers?.(); + // ... + + throw new ForbiddenException(`Unknown issuer: ${issuer}`); + } +} diff --git a/src/modules/global/auth/jwt.service.ts b/src/modules/global/auth/jwt.service.ts new file mode 100644 index 0000000..2d90151 --- /dev/null +++ b/src/modules/global/auth/jwt.service.ts @@ -0,0 +1,137 @@ +// src/auth/azure-jwt.service.ts +import { Injectable, OnModuleInit } from '@nestjs/common'; +import { SecretService } from '../secret/secret.service'; +import { + createRemoteJWKSet, + jwtVerify, + JWTPayload, + JWTVerifyResult, +} from 'jose'; + +/** + * Microsoft Entra ID 를 IdP로 사용하는 OpenID Connect 인증 관련 모듈. + * OIDC 인증 흐름 -> https://learn.microsoft.com/ko-kr/entra/architecture/auth-oidc 문서 참조. + * 추후 IdP 확장 고려해 IdP 별로 해당 IdP 이름을 접두사에 붙인다. + */ +export type IdentityProviderName = 'MICROSOFT_ENTRAID' | 'AMAZON_COGNITO'; + +// export type IdentityProvider = { +// [x in IdentityProviderName]: EntraIDIdentityProviderMetadata +// }; + +// export type EntraIDIdentityProviderMetadata = { +// issuer: string; +// authorizationEndpoint: string; +// tokenEndpoint: string; +// userInfoEndpoint: string; +// jwksUri: string; +// } + +@Injectable() +export class JwtService implements OnModuleInit { + private jwtClaimAudience: string; + + private MICROSOFT_ENTRAID_tenantId: string; + private MICROSOFT_ENTRAID_allowedAlgs: string; + private MICROSOFT_ENTRAID_issuer: string; + private MICROSOFT_ENTRAID_jwksUri: string; + private MICROSOFT_ENTRAID_jwks: ReturnType; + + private readonly tokenSigningAlgValuesSupported = ['RS256']; + private readonly clockTolerance = + Number(process.env.JWT_CLOCK_TOLERANCE || 5); // seconds + + constructor( + private readonly secretService: SecretService + ) {} + + public async onModuleInit() { + await this.secretService.ready() + this.jwtClaimAudience = await this.secretService.get('JWT_CLAIM_AUDIENCE') + + this.MICROSOFT_ENTRAID_tenantId = await this.secretService.get('MICROSOFT_ENTRAID_TENANT_ID') + this.MICROSOFT_ENTRAID_allowedAlgs = await this.secretService.get('MICROSOFT_ENTRAID_ALLOWED_ALGS') + this.MICROSOFT_ENTRAID_issuer = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/v2.0`; + this.MICROSOFT_ENTRAID_jwksUri = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/discovery/v2.0/keys`; + this.MICROSOFT_ENTRAID_jwks = createRemoteJWKSet(new URL(this.MICROSOFT_ENTRAID_jwksUri), { + // cache: true, + cooldownDuration: 30_000, // 30s + timeoutDuration: 10_000, // 10s + }); + + } + + /** + * Authorization: Bearer 의 부분을 검증. + * - iss: v2.0 발급자 + * - aud: Application ID URI와 정확히 일치해야 함 + * - alg: RS256(기본) + */ + async verify( + token: string, + identityProvider: IdentityProviderName + ): Promise> { + if (!token) { + throw new Error('Empty token'); + } + + // IdP별 설정 매핑 + const providers = { + MICROSOFT_ENTRAID: { + jwks: this.MICROSOFT_ENTRAID_jwks, + issuer: this.MICROSOFT_ENTRAID_issuer, + audience: this.jwtClaimAudience, + extraValidate: (payload: JWTPayload) => { + // AAD v2 토큰 전용 추가 검증 + if (payload['ver'] && payload['ver'] !== '2.0') { + throw new Error(`Unsupported AAD token version: ${payload['ver']}`); + } + if (payload['tid'] && payload['tid'] !== this.MICROSOFT_ENTRAID_tenantId) { + throw new Error(`Unexpected tenant: ${payload['tid']}`); + } + }, + }, + AMAZON_COGNITO: { + // 아래 3개 필드는 onModuleInit에서 Entra와 동일하게 준비해야 함 + // this.AMAZON_COGNITO_jwks = createRemoteJWKSet(new URL(this.AMAZON_COGNITO_jwksUri), {...}) + jwks: this['AMAZON_COGNITO_jwks'], + issuer: this['AMAZON_COGNITO_issuer'], + audience: this['AMAZON_COGNITO_audience'], + extraValidate: (payload: JWTPayload) => { + // 필요하면 Cognito 전용 검증(예: token_use, cognito:username 등) 추가 + // if (payload['token_use'] && payload['token_use'] !== 'id' /* or 'access' */) { ... } + }, + }, + } as const; + + const provider = providers[identityProvider]; + if (!provider?.jwks || !provider?.issuer || !provider?.audience) { + throw new Error(`Identity provider not configured: ${identityProvider}`); + } + + // 허용 알고리즘: 환경변수(콤마 구분) -> 기본값(['RS256']) + const allowedAlgs = + (this.MICROSOFT_ENTRAID_allowedAlgs + ? this.MICROSOFT_ENTRAID_allowedAlgs.split(',').map(s => s.trim()).filter(Boolean) + : this.tokenSigningAlgValuesSupported) as string[]; + + const result = await jwtVerify(token, provider.jwks, { + issuer: provider.issuer, + audience: provider.audience, + algorithms: allowedAlgs, + clockTolerance: this.clockTolerance, + }); + + const { payload, protectedHeader } = result; + + // 공통: alg 확인 + if (!allowedAlgs.includes(protectedHeader.alg as string)) { + throw new Error(`Unexpected alg: ${protectedHeader.alg}`); + } + + // 프로바이더별 추가 검증 + provider.extraValidate?.(payload); + + return result; + } +} \ No newline at end of file diff --git a/src/modules/global/global.module.ts b/src/modules/global/global.module.ts index 5368900..9744f58 100644 --- a/src/modules/global/global.module.ts +++ b/src/modules/global/global.module.ts @@ -1,12 +1,13 @@ import { Module, Global } from '@nestjs/common'; import { SecretModule } from './secret/secret.module'; -import { DatabaseModule } from './database/database.module'; +// import { DatabaseModule } from './database/database.module'; import { NatsModule } from './nats/nats.module'; +import { JwtService } from './auth/jwt.service'; @Global() @Module({ imports: [SecretModule, NatsModule], - providers: [], - exports: [SecretModule, NatsModule], + providers: [JwtService], + exports: [SecretModule, NatsModule, JwtService], }) export class GlobalModule {} \ No newline at end of file