@infoteam/account-nest 0.6.1 → 0.7.0

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 GSA Infoteam
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GSA Infoteam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,122 +1,144 @@
1
- # @infoteam/account-nest
2
-
3
- NestJS 백엔드를 인포팀 계정(IdP)에 붙인다. 모듈이 [`@infoteam/account-server`](../server)의 IdP 클라이언트를 주입해 주고, 앱이 시작될 때 IdP 등록을
4
- 확인한다. 서비스 세션(로그인, 갱신, 로그아웃 endpoint와 guard)은 서비스가 [세션 프로토콜](../../README.md#세션-프로토콜)에 맞춰 직접 구현한다.
5
-
6
- ## 설치
7
-
8
- ```bash
9
- pnpm add @infoteam/account-nest zod
10
- ```
11
-
12
- ESM으로만 배포한다. CommonJS(`module: commonjs`)로 빌드하는 Nest 앱도 Node 20.19 이상이면 `require()`로 그대로 불러온다.
13
-
14
- jest는 ESM을 `require()` 하지 못하므로, SDK와 그 의존성(jose, oauth4webapi)만 변환하도록 설정한다.
15
-
16
- ```js
17
- // jest 설정
18
- transform: { '^.+\\.(t|j)s$': ['ts-jest', { tsconfig: { allowJs: true } }] },
19
- transformIgnorePatterns: ['/node_modules/(?!\\.pnpm|@infoteam|jose|oauth4webapi)'],
20
- ```
21
-
22
- ## 모듈 설정
23
-
24
- 타입을 정하는 정적인 값(scope)은 `defineAccount`에 두고, 환경마다 다른 값(client id, secret)은 `forRoot`나 `forRootAsync`에 둔다.
25
-
26
- ```ts
27
- // account.ts
28
- import { defineAccount } from '@infoteam/account-nest';
29
-
30
- export const { AccountModule, AccountService } = defineAccount({
31
- requiredScopes: ['name', 'email'], // client 에 필수로 등록한 scope
32
- });
33
- export type AccountService = InstanceType<typeof AccountService>;
34
- ```
35
-
36
- ```ts
37
- // app.module.ts
38
- AccountModule.forRootAsync({
39
- isGlobal: true,
40
- inject: [ConfigService],
41
- useFactory: (config: ConfigService) => ({
42
- issuer: 'production',
43
- clientId: config.getOrThrow('ACCOUNT_CLIENT_ID'),
44
- clientSecret: config.getOrThrow('ACCOUNT_CLIENT_SECRET'),
45
- }),
46
- }),
47
- ```
48
-
49
- - `export type AccountService` 줄은 반드시 함께 쓴다. 이 줄이 있어야 구조 분해로 꺼낸 클래스를 타입으로 쓸 수 있고, `@Inject` 없이 생성자 타입만으로 주입된다.
50
- - scope 없이 쓸 때는 `defineAccount` 대신 패키지가 내보내는 `AccountModule`, `AccountService`를 바로 써도 된다.
51
- - 앱이 시작될 때 IdP에 등록한 client 정보를 읽어 `requiredScopes`, `clientCredentialsScopes`, 인증 방식(`client_secret_post`)이 맞는지 확인한다.
52
- 맞지 않으면 앱이 시작되지 않는다. `verifyRegistration: 'warn'`이면 로그만 남긴다. IdP에 연결하지 못했을 때도 로그만 남긴다.
53
-
54
- ## 로그인 endpoint
55
-
56
- 프론트 SDK가 보낸 code를 `loginWithCode`에 넘기면 IdP와 교환하고 id_token의 `aud`와 `nonce`를 확인한 뒤 사용자를 돌려준다. 그 사용자로 서비스 세션을 만든다.
57
-
58
- ```ts
59
- @Post('auth/login')
60
- @HttpCode(200)
61
- async login(@Req() req: Request, @Body() body: LoginBody, @Res({ passthrough: true }) res: Response) {
62
- const origin = req.headers.origin;
63
- if (origin !== undefined && origin !== WEB_ORIGIN) throw new BadRequestException('untrusted origin');
64
-
65
- const { user } = await this.account
66
- .loginWithCode({
67
- code: body.code,
68
- codeVerifier: body.code_verifier,
69
- redirectUri: body.redirect_uri,
70
- nonce: body.nonce,
71
- iss: body.iss,
72
- })
73
- .catch(toHttpError); // 아래 에러 절 참고
74
- const local = await this.users.upsertByIdp(user); // user.email 은 string
75
- const { accessToken, refreshToken } = await this.sessions.issue(local.id);
76
-
77
- res.cookie('refresh_token', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict', path: '/auth' });
78
- return { access_token: accessToken };
79
- }
80
- ```
81
-
82
- 갱신, 로그아웃, 앱용 `transport: 'body'`, 거절과 ticket 규칙은 [세션 프로토콜](../../README.md#세션-프로토콜)에 있고, 메모리 저장소로 구현한 예시(ticket 흐름 제외)는
83
- [`examples/nest`](../../examples/nest)에 있다.
84
-
85
- ## scope와 필드 타입
86
-
87
- `requiredScopes`에 넣은 scope의 필드는 `loginWithCode`가 돌려주는 사용자에서 필수 타입이 된다. 예를 들어 `email`을 넣으면 `user.email`은 `string`이다.
88
- id_token에 그 필드가 빠져 있으면 SDK가 `missing_claims`로 실패하므로, `undefined`가 서비스 코드까지 전달되지 않는다. 다만 `profile`과 `picture`는 사용자가
89
- 비워 둘 수 있어서 필수 scope여도 `undefined`일 수 있다.
90
-
91
- `requiredScopes`에는 client에 **필수로** 등록한 scope만 넣는다. 사용자가 거부할 수 있는 선택 scope를 넣으면, 그 scope를 거부한 사용자는 로그인하지 못한다.
92
-
93
- scope 구성이 다른 설정이 여러 개 필요하면(예: 사용자 앱과 관리자 웹) `defineAccount`를 여러 번 호출한다. 호출할 때마다 주입 토큰이 따로 생긴다.
94
-
95
- ## 다른 사용자 조회
96
-
97
- ```ts
98
- constructor(private readonly account: AccountService) {}
99
-
100
- findUser(sub: string) {
101
- return this.account.getUserInfoBySub(sub); // clientSecret 과 clientCredentialsScopes 가 필요하다
102
- }
103
- ```
104
-
105
- 메서드 목록은 [`@infoteam/account-server` README](../server/README.md)에 있다.
106
-
107
- ## 에러
108
-
109
- SDK는 실패하면 `AccountError`를 던지므로 `code`로 HTTP 상태를 나눈다. 403은 [거절](../../README.md#세션-프로토콜) 전용이므로 다른 실패에 쓰지 않는다.
110
-
111
- | `code` | 상태 | 의미 |
112
- | ------------------------------------------------------------------------------ | ---- | -------------------------------------- |
113
- | `invalid_request` | 400 | 요청 형식이 틀렸다 |
114
- | `network_error`, `server_error`, `discovery_failed`, `temporarily_unavailable` | 502 | IdP에 연결하지 못했거나 IdP가 실패했다 |
115
- | `invalid_client`, `unauthorized_client`, `invalid_scope`, `missing_claims` | 500 | client 등록이나 서버 설정이 틀렸다 |
116
- | 그 밖의 code (`invalid_grant`, `invalid_id_token` 등) | 401 | 만료되거나 이미 쓴 code, 검증 실패 |
117
-
118
- [`examples/nest`의 `toHttpError`](../../examples/nest/src/auth.controller.ts)가 이 표를 구현한다.
119
-
120
- ## 테스트
121
-
122
- [`@infoteam/account-testing`](../testing)의 가짜 IdP로 진짜 IdP 없이 로그인 endpoint까지 e2e 테스트를 돌린다. 사용법은 [그 README](../testing/README.md)에 있다.
1
+ # @infoteam/account-nest
2
+
3
+ NestJS 백엔드를 인포팀 계정(IdP)에 붙인다. 모듈이 [`@infoteam/account-server`](../server)의 IdP 클라이언트를 주입해 주고, 앱이 시작될 때 IdP 등록을
4
+ 확인한다. 서비스 세션(로그인, 갱신, 로그아웃 endpoint와 guard)은 서비스가 [세션 프로토콜](../../README.md#세션-프로토콜)에 맞춰 직접 구현한다.
5
+
6
+ ## 설치
7
+
8
+ ```bash
9
+ pnpm add @infoteam/account-nest zod
10
+ ```
11
+
12
+ ESM으로만 배포한다. CommonJS(`module: commonjs`)로 빌드하는 Nest 앱도 Node 20.19 이상이면 `require()`로 그대로 불러온다.
13
+
14
+ jest는 ESM을 `require()` 하지 못하므로, SDK와 그 의존성(jose, oauth4webapi)만 변환하도록 설정한다.
15
+
16
+ ```js
17
+ // jest 설정
18
+ transform: { '^.+\\.(t|j)s$': ['ts-jest', { tsconfig: { allowJs: true } }] },
19
+ transformIgnorePatterns: ['/node_modules/(?!\\.pnpm|@infoteam|jose|oauth4webapi)'],
20
+ ```
21
+
22
+ ## 모듈 설정
23
+
24
+ 타입을 정하는 정적인 값(scope)은 `defineAccount`에 두고, 환경마다 다른 값(client id, secret)은 `forRoot`나 `forRootAsync`에 둔다.
25
+
26
+ ```ts
27
+ // account.ts
28
+ import { defineAccount } from '@infoteam/account-nest';
29
+
30
+ export const { AccountModule, AccountService } = defineAccount({
31
+ requiredScopes: ['name', 'email'], // client 에 필수로 등록한 scope
32
+ });
33
+ export type AccountService = InstanceType<typeof AccountService>;
34
+ ```
35
+
36
+ ```ts
37
+ // app.module.ts
38
+ AccountModule.forRootAsync({
39
+ isGlobal: true,
40
+ inject: [ConfigService],
41
+ useFactory: (config: ConfigService) => ({
42
+ issuer: 'production',
43
+ clientId: config.getOrThrow('ACCOUNT_CLIENT_ID'),
44
+ clientSecret: config.getOrThrow('ACCOUNT_CLIENT_SECRET'),
45
+ }),
46
+ }),
47
+ ```
48
+
49
+ - `export type AccountService` 줄은 반드시 함께 쓴다. 이 줄이 있어야 구조 분해로 꺼낸 클래스를 타입으로 쓸 수 있고, `@Inject` 없이 생성자 타입만으로 주입된다.
50
+ - scope 없이 쓸 때는 `defineAccount` 대신 패키지가 내보내는 `AccountModule`, `AccountService`를 바로 써도 된다.
51
+ - 앱이 시작될 때 IdP에 등록한 client 정보를 읽어 `requiredScopes`, `clientCredentialsScopes`, 인증 방식(`client_secret_post`)이 맞는지 확인한다.
52
+ 맞지 않으면 앱이 시작되지 않는다. `verifyRegistration: 'warn'`이면 로그만 남긴다. IdP에 연결하지 못했을 때도 로그만 남긴다.
53
+
54
+ ## 로그인 endpoint
55
+
56
+ 프론트 SDK가 보낸 code를 `loginWithCode`에 넘기면 IdP와 교환하고 id_token의 `aud`와 `nonce`를 확인한 뒤 사용자를 돌려준다. 그 사용자로 서비스 세션을 만든다.
57
+
58
+ ```ts
59
+ import { toHttpException } from '@infoteam/account-nest';
60
+ import { LoginCodeBody } from '@infoteam/account-nest/dto';
61
+
62
+ @Post('auth/login')
63
+ @HttpCode(200)
64
+ async login(@Req() req: Request, @Body() body: LoginCodeBody, @Res({ passthrough: true }) res: Response) {
65
+ const origin = req.headers.origin;
66
+ if (origin !== undefined && origin !== WEB_ORIGIN) throw new BadRequestException('untrusted origin');
67
+
68
+ const { user } = await this.account
69
+ .loginWithCode({
70
+ code: body.code,
71
+ codeVerifier: body.code_verifier,
72
+ redirectUri: body.redirect_uri,
73
+ nonce: body.nonce,
74
+ iss: body.iss,
75
+ })
76
+ .catch(toHttpException); // 아래 에러 절 참고
77
+ const local = await this.users.upsertByIdp(user); // user.email 은 string
78
+ const { accessToken, refreshToken } = await this.sessions.issue(local.id);
79
+
80
+ res.cookie('refresh_token', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict', path: '/auth' });
81
+ return { access_token: accessToken };
82
+ }
83
+ ```
84
+
85
+ ### login body
86
+
87
+ `@infoteam/account-nest/dto`는 login body를 class-validator와 Swagger 데코레이터가 붙은 클래스로 내보낸다. `class-validator`와 `@nestjs/swagger`가
88
+ 설치되어 있어야 하고, 이 경로를 import 하지 않으면 둘 다 필요 없다.
89
+
90
+ - `LoginCodeBody`: `{ code, code_verifier, redirect_uri, nonce, iss?, transport? }`. ticket 흐름이 없는 서비스가 쓴다.
91
+ - `LoginBody`: 위 필드에 `ticket?`을 더한다. code 필드는 ticket이 없을 때만 검사한다. 거절 뒤 ticket으로 다시 로그인하는 서비스가 쓴다.
92
+
93
+ ticket과 함께 받는 추가 입력은 상속해서 더한다.
94
+
95
+ ```ts
96
+ class SignupBody extends LoginBody {
97
+ @IsOptional()
98
+ @IsString()
99
+ nickname?: string;
100
+ }
101
+ ```
102
+
103
+ 거절 응답의 형식은 `SessionRejectedResponse` 타입과 `SESSION_REJECTED` 상수로, wire 형식의 zod 스키마는 `LoginCodeBodySchema`,
104
+ `LoginTicketBodySchema`, `SessionTokensResponseSchema`로 내보낸다.
105
+
106
+ 갱신, 로그아웃, 앱용 `transport: 'body'`, 거절과 ticket 규칙은 [세션 프로토콜](../../README.md#세션-프로토콜)에 있고, 메모리 저장소로 구현한 예시(ticket 흐름 제외)는
107
+ [`examples/nest`](../../examples/nest)에 있다.
108
+
109
+ ## scope와 필드 타입
110
+
111
+ `requiredScopes`에 넣은 scope의 필드는 `loginWithCode`가 돌려주는 사용자에서 필수 타입이 된다. 예를 들어 `email`을 넣으면 `user.email`은 `string`이다.
112
+ id_token에 그 필드가 빠져 있으면 SDK가 `missing_claims`로 실패하므로, `undefined`가 서비스 코드까지 전달되지 않는다. 다만 `profile`과 `picture`는 사용자가
113
+ 비워 둘 수 있어서 필수 scope여도 `undefined`일 수 있다.
114
+
115
+ `requiredScopes`에는 client에 **필수로** 등록한 scope만 넣는다. 사용자가 거부할 수 있는 선택 scope를 넣으면, 그 scope를 거부한 사용자는 로그인하지 못한다.
116
+
117
+ scope 구성이 다른 설정이 여러 개 필요하면(예: 사용자 앱과 관리자 웹) `defineAccount`를 여러 번 호출한다. 호출할 때마다 주입 토큰이 따로 생긴다.
118
+
119
+ ## 다른 사용자 조회
120
+
121
+ ```ts
122
+ constructor(private readonly account: AccountService) {}
123
+
124
+ findUser(sub: string) {
125
+ return this.account.getUserInfoBySub(sub); // clientSecret 과 clientCredentialsScopes 가 필요하다
126
+ }
127
+ ```
128
+
129
+ 메서드 목록은 [`@infoteam/account-server` README](../server/README.md)에 있다.
130
+
131
+ ## 에러
132
+
133
+ SDK는 실패하면 `AccountError`를 던진다. `toHttpException`이 `code`에 따라 아래 표의 HTTP 예외로 바꿔 던지고, `AccountError`가 아니면 그대로 던진다. 403은 [거절](../../README.md#세션-프로토콜) 전용이므로 쓰지 않는다.
134
+
135
+ | `code` | 상태 | 의미 |
136
+ | ------------------------------------------------------------------------------ | ---- | -------------------------------------- |
137
+ | `invalid_request` | 400 | 요청 형식이 틀렸다 |
138
+ | `network_error`, `server_error`, `discovery_failed`, `temporarily_unavailable` | 502 | IdP에 연결하지 못했거나 IdP가 실패했다 |
139
+ | `invalid_client`, `unauthorized_client`, `invalid_scope`, `missing_claims` | 500 | client 등록이나 서버 설정이 틀렸다 |
140
+ | 그 밖의 code (`invalid_grant`, `invalid_id_token` 등) | 401 | 만료되거나 이미 쓴 code, 검증 실패 |
141
+
142
+ ## 테스트
143
+
144
+ [`@infoteam/account-testing`](../testing)의 가짜 IdP로 진짜 IdP 없이 로그인 endpoint까지 e2e 테스트를 돌린다. 사용법은 [그 README](../testing/README.md)에 있다.
@@ -0,0 +1,9 @@
1
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorate.js
2
+ function __decorate(decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ }
8
+ //#endregion
9
+ export { __decorate as t };
package/dist/dto.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { SessionTransport } from "@infoteam/account-server";
2
+ //#region src/dto.d.ts
3
+ /** ticket 흐름이 없는 서비스의 `POST /auth/login` body다. 서비스 입력이 더 있으면 상속해서 필드를 더한다. */
4
+ export declare class LoginCodeBody {
5
+ code: string;
6
+ code_verifier: string;
7
+ redirect_uri: string;
8
+ nonce: string;
9
+ iss?: string;
10
+ transport?: SessionTransport;
11
+ }
12
+ /**
13
+ * 403 거절 뒤 ticket으로 다시 로그인하는 서비스의 body다. code 필드는 ticket이 없을 때만 검사한다.
14
+ * 동의 여부 같은 추가 입력은 상속해서 더한다.
15
+ */
16
+ export declare class LoginBody {
17
+ code: string;
18
+ code_verifier: string;
19
+ redirect_uri: string;
20
+ nonce: string;
21
+ iss?: string;
22
+ ticket?: string;
23
+ transport?: SessionTransport;
24
+ }
25
+ //#endregion
package/dist/dto.js ADDED
@@ -0,0 +1,102 @@
1
+ import { t as __decorate } from "./decorate-DXhg3-hW.js";
2
+ import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
3
+ import { IsIn, IsString, ValidateIf } from "class-validator";
4
+ //#region src/dto.ts
5
+ const TRANSPORTS = ["cookie", "body"];
6
+ /** `IsOptional`과 달리 null은 검사한다. ticket이 null이면 code 필드 검사를 건너뛰게 된다. */
7
+ const IfDefined = () => ValidateIf((_body, value) => value !== void 0);
8
+ /** ticket 흐름이 없는 서비스의 `POST /auth/login` body다. 서비스 입력이 더 있으면 상속해서 필드를 더한다. */
9
+ var LoginCodeBody = class {
10
+ code;
11
+ code_verifier;
12
+ redirect_uri;
13
+ nonce;
14
+ iss;
15
+ transport;
16
+ };
17
+ __decorate([ApiProperty({ type: String }), IsString()], LoginCodeBody.prototype, "code", void 0);
18
+ __decorate([ApiProperty({ type: String }), IsString()], LoginCodeBody.prototype, "code_verifier", void 0);
19
+ __decorate([ApiProperty({ type: String }), IsString()], LoginCodeBody.prototype, "redirect_uri", void 0);
20
+ __decorate([ApiProperty({ type: String }), IsString()], LoginCodeBody.prototype, "nonce", void 0);
21
+ __decorate([
22
+ ApiPropertyOptional({ type: String }),
23
+ IfDefined(),
24
+ IsString()
25
+ ], LoginCodeBody.prototype, "iss", void 0);
26
+ __decorate([
27
+ ApiPropertyOptional({
28
+ enum: TRANSPORTS,
29
+ description: "앱은 body, 웹은 cookie"
30
+ }),
31
+ IfDefined(),
32
+ IsIn(TRANSPORTS)
33
+ ], LoginCodeBody.prototype, "transport", void 0);
34
+ const withoutTicket = (body) => body.ticket === void 0;
35
+ /**
36
+ * 403 거절 뒤 ticket으로 다시 로그인하는 서비스의 body다. code 필드는 ticket이 없을 때만 검사한다.
37
+ * 동의 여부 같은 추가 입력은 상속해서 더한다.
38
+ */
39
+ var LoginBody = class {
40
+ code;
41
+ code_verifier;
42
+ redirect_uri;
43
+ nonce;
44
+ iss;
45
+ ticket;
46
+ transport;
47
+ };
48
+ __decorate([
49
+ ApiPropertyOptional({
50
+ type: String,
51
+ description: "ticket이 없으면 필수"
52
+ }),
53
+ ValidateIf(withoutTicket),
54
+ IsString()
55
+ ], LoginBody.prototype, "code", void 0);
56
+ __decorate([
57
+ ApiPropertyOptional({
58
+ type: String,
59
+ description: "ticket이 없으면 필수"
60
+ }),
61
+ ValidateIf(withoutTicket),
62
+ IsString()
63
+ ], LoginBody.prototype, "code_verifier", void 0);
64
+ __decorate([
65
+ ApiPropertyOptional({
66
+ type: String,
67
+ description: "ticket이 없으면 필수"
68
+ }),
69
+ ValidateIf(withoutTicket),
70
+ IsString()
71
+ ], LoginBody.prototype, "redirect_uri", void 0);
72
+ __decorate([
73
+ ApiPropertyOptional({
74
+ type: String,
75
+ description: "ticket이 없으면 필수"
76
+ }),
77
+ ValidateIf(withoutTicket),
78
+ IsString()
79
+ ], LoginBody.prototype, "nonce", void 0);
80
+ __decorate([
81
+ ApiPropertyOptional({ type: String }),
82
+ IfDefined(),
83
+ IsString()
84
+ ], LoginBody.prototype, "iss", void 0);
85
+ __decorate([
86
+ ApiPropertyOptional({
87
+ type: String,
88
+ description: "403 session_rejected 응답의 ticket"
89
+ }),
90
+ IfDefined(),
91
+ IsString()
92
+ ], LoginBody.prototype, "ticket", void 0);
93
+ __decorate([
94
+ ApiPropertyOptional({
95
+ enum: TRANSPORTS,
96
+ description: "앱은 body, 웹은 cookie"
97
+ }),
98
+ IfDefined(),
99
+ IsIn(TRANSPORTS)
100
+ ], LoginBody.prototype, "transport", void 0);
101
+ //#endregion
102
+ export { LoginBody, LoginCodeBody };
package/dist/index.d.ts CHANGED
@@ -30,6 +30,14 @@ interface DefinedAccount<RequiredScope extends ClientScope, LookupScope extends
30
30
  */
31
31
  export declare function defineAccount<const RequiredScopes extends readonly ClientScope[] = [], const LookupScopes extends readonly ClientScope[] = []>(scopes?: AccountScopes<RequiredScopes, LookupScopes>): DefinedAccount<RequiredScopes[number], LookupScopes[number]>;
32
32
  //#endregion
33
+ //#region src/http-exception.d.ts
34
+ /**
35
+ * `loginWithCode`의 `AccountError`를 HTTP 예외로 바꿔 던진다. `AccountError`가 아니면 그대로 던진다.
36
+ *
37
+ * 403은 세션 프로토콜의 거절 전용이라 쓰지 않는다. 프론트 SDK가 403을 약관 동의 같은 추가 입력 요청으로 처리한다.
38
+ */
39
+ export declare function toHttpException(error: unknown): never;
40
+ //#endregion
33
41
  //#region src/index.d.ts
34
42
  /** scope에 맞춘 필드 타입이 필요하면 {@link defineAccount}를 쓴다. */
35
43
  export declare const AccountModule: import("@nestjs/common").ConfigurableModuleCls<AccountModuleOptions, "forRoot", "create", AccountModuleExtras>, AccountService: abstract new () => import("@infoteam/account-server").AccountServer<never, never>;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { t as __decorate } from "./decorate-DXhg3-hW.js";
1
2
  import { AccountError } from "@infoteam/account-core";
2
- import { createAccountServer } from "@infoteam/account-server";
3
- import { ConfigurableModuleBuilder, Inject, Logger, Module } from "@nestjs/common";
3
+ import { AccountError as AccountError$1, createAccountServer } from "@infoteam/account-server";
4
+ import { BadGatewayException, BadRequestException, ConfigurableModuleBuilder, Inject, InternalServerErrorException, Logger, Module, UnauthorizedException } from "@nestjs/common";
4
5
  export * from "@infoteam/account-server";
5
6
  //#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorateParam.js
6
7
  function __decorateParam(paramIndex, decorator) {
@@ -9,14 +10,6 @@ function __decorateParam(paramIndex, decorator) {
9
10
  };
10
11
  }
11
12
  //#endregion
12
- //#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorate.js
13
- function __decorate(decorators, target, key, desc) {
14
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
16
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
17
- return c > 3 && r && Object.defineProperty(target, key, r), r;
18
- }
19
- //#endregion
20
13
  //#region src/define-account.ts
21
14
  /**
22
15
  * 생성자 인자의 타입이 클래스여야 `emitDecoratorMetadata`가 주입 토큰을 기록한다. 실제로 주입되는 값은
@@ -73,8 +66,34 @@ function defineAccount(scopes = {}) {
73
66
  };
74
67
  }
75
68
  //#endregion
69
+ //#region src/http-exception.ts
70
+ /**
71
+ * `loginWithCode`의 `AccountError`를 HTTP 예외로 바꿔 던진다. `AccountError`가 아니면 그대로 던진다.
72
+ *
73
+ * 403은 세션 프로토콜의 거절 전용이라 쓰지 않는다. 프론트 SDK가 403을 약관 동의 같은 추가 입력 요청으로 처리한다.
74
+ */
75
+ function toHttpException(error) {
76
+ if (!AccountError$1.is(error)) throw error;
77
+ const body = {
78
+ error: error.code,
79
+ error_description: error.description
80
+ };
81
+ switch (error.code) {
82
+ case "invalid_request": throw new BadRequestException(body);
83
+ case "network_error":
84
+ case "server_error":
85
+ case "discovery_failed":
86
+ case "temporarily_unavailable": throw new BadGatewayException(body);
87
+ case "invalid_client":
88
+ case "unauthorized_client":
89
+ case "invalid_scope":
90
+ case "missing_claims": throw new InternalServerErrorException(body);
91
+ default: throw new UnauthorizedException(body);
92
+ }
93
+ }
94
+ //#endregion
76
95
  //#region src/index.ts
77
96
  /** scope에 맞춘 필드 타입이 필요하면 {@link defineAccount}를 쓴다. */
78
97
  const { AccountModule, AccountService } = defineAccount();
79
98
  //#endregion
80
- export { AccountModule, AccountService, defineAccount };
99
+ export { AccountModule, AccountService, defineAccount, toHttpException };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infoteam/account-nest",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "NestJS module for the Infoteam account IdP",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,17 +18,20 @@
18
18
  "sideEffects": false,
19
19
  "exports": {
20
20
  ".": "./dist/index.js",
21
+ "./dto": "./dist/dto.js",
21
22
  "./package.json": "./package.json"
22
23
  },
23
24
  "devDependencies": {
24
25
  "@infoteam/account-contract": "^0.3.0",
25
- "@infoteam/account-testing": "^0.6.1",
26
+ "@infoteam/account-testing": "^0.7.0",
26
27
  "@nestjs/common": "^11.2.7",
27
28
  "@nestjs/core": "^11.2.7",
28
29
  "@nestjs/platform-express": "^11.2.7",
29
30
  "@nestjs/platform-fastify": "^11.2.7",
31
+ "@nestjs/swagger": "^11.4.8",
30
32
  "@nestjs/testing": "^11.2.7",
31
33
  "@types/node": "^24.0.0",
34
+ "class-validator": "^0.14.4",
32
35
  "reflect-metadata": "^0.2.2",
33
36
  "rxjs": "^7.8.2",
34
37
  "tsdown": "^0.23.0",
@@ -40,14 +43,31 @@
40
43
  "node": ">=20.19"
41
44
  },
42
45
  "dependencies": {
43
- "@infoteam/account-core": "^0.6.1",
44
- "@infoteam/account-server": "^0.6.1"
46
+ "@infoteam/account-core": "^0.7.0",
47
+ "@infoteam/account-server": "^0.7.0"
45
48
  },
46
49
  "peerDependencies": {
47
50
  "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
51
+ "@nestjs/swagger": "^7.0.0 || ^8.0.0 || ^11.0.0",
52
+ "class-validator": "^0.14.0 || ^0.15.0",
48
53
  "zod": "^4.0.0"
49
54
  },
50
55
  "types": "./dist/index.d.ts",
56
+ "typesVersions": {
57
+ "*": {
58
+ "dto": [
59
+ "./dist/dto.d.ts"
60
+ ]
61
+ }
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@nestjs/swagger": {
65
+ "optional": true
66
+ },
67
+ "class-validator": {
68
+ "optional": true
69
+ }
70
+ },
51
71
  "scripts": {
52
72
  "build": "tsdown",
53
73
  "typecheck": "tsc --noEmit",