@infoteam/account-nest 0.0.0-stage → 0.6.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 +21 -0
- package/README.md +122 -3
- package/dist/index.d.ts +38 -0
- package/dist/index.js +80 -0
- package/package.json +54 -3
package/LICENSE
ADDED
|
@@ -0,0 +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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,122 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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)에 있다.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { AccountServer, AccountServerOptions, ClientScope } from "@infoteam/account-server";
|
|
2
|
+
import { ConfigurableModuleAsyncOptions, ConfigurableModuleCls } from "@nestjs/common";
|
|
3
|
+
export * from "@infoteam/account-server";
|
|
4
|
+
//#region src/define-account.d.ts
|
|
5
|
+
interface AccountScopes<RequiredScopes extends readonly ClientScope[], LookupScopes extends readonly ClientScope[]> {
|
|
6
|
+
requiredScopes?: RequiredScopes;
|
|
7
|
+
clientCredentialsScopes?: LookupScopes;
|
|
8
|
+
}
|
|
9
|
+
type AccountModuleOptions = Omit<AccountServerOptions, 'requiredScopes' | 'clientCredentialsScopes'> & {
|
|
10
|
+
/**
|
|
11
|
+
* 기본값인 `error`는 등록이 맞지 않으면 앱이 시작되지 않게 하고, `warn`은 로그만 남긴다. IdP에 연결하지 못하면
|
|
12
|
+
* 어느 쪽이든 로그만 남긴다.
|
|
13
|
+
*/
|
|
14
|
+
verifyRegistration?: 'error' | 'warn' | 'off';
|
|
15
|
+
};
|
|
16
|
+
interface AccountModuleExtras {
|
|
17
|
+
isGlobal: boolean;
|
|
18
|
+
}
|
|
19
|
+
type AccountModuleAsyncOptions<Options = AccountModuleOptions> = ConfigurableModuleAsyncOptions<Options> & Partial<AccountModuleExtras>;
|
|
20
|
+
interface DefinedAccount<RequiredScope extends ClientScope, LookupScope extends ClientScope> {
|
|
21
|
+
AccountModule: ConfigurableModuleCls<AccountModuleOptions, 'forRoot', 'create', AccountModuleExtras>;
|
|
22
|
+
AccountService: abstract new () => AccountServer<RequiredScope, LookupScope>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 호출할 때마다 주입 토큰이 새로 생기므로 설정이 다른 계정 여러 개가 한 앱에 함께 있을 수 있다.
|
|
26
|
+
*
|
|
27
|
+
* 꺼낸 `AccountService` 옆에 `export type AccountService = InstanceType<typeof AccountService>`를 빼면 안 된다.
|
|
28
|
+
* 구조 분해로 꺼낸 클래스 값은 TS에서 타입 이름이 되지 않는다. 같은 이름의 값과 타입이 함께 있어야
|
|
29
|
+
* `emitDecoratorMetadata`가 생성자 인자에 클래스 값을 기록해서, `@Inject` 없이도 주입된다.
|
|
30
|
+
*/
|
|
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
|
+
//#endregion
|
|
33
|
+
//#region src/index.d.ts
|
|
34
|
+
/** scope에 맞춘 필드 타입이 필요하면 {@link defineAccount}를 쓴다. */
|
|
35
|
+
export declare const AccountModule: import("@nestjs/common").ConfigurableModuleCls<AccountModuleOptions, "forRoot", "create", AccountModuleExtras>, AccountService: abstract new () => import("@infoteam/account-server").AccountServer<never, never>;
|
|
36
|
+
export type AccountService = InstanceType<typeof AccountService>;
|
|
37
|
+
//#endregion
|
|
38
|
+
export type { AccountModuleAsyncOptions, AccountModuleExtras, AccountModuleOptions, AccountScopes, DefinedAccount };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { AccountError } from "@infoteam/account-core";
|
|
2
|
+
import { createAccountServer } from "@infoteam/account-server";
|
|
3
|
+
import { ConfigurableModuleBuilder, Inject, Logger, Module } from "@nestjs/common";
|
|
4
|
+
export * from "@infoteam/account-server";
|
|
5
|
+
//#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorateParam.js
|
|
6
|
+
function __decorateParam(paramIndex, decorator) {
|
|
7
|
+
return function(target, key) {
|
|
8
|
+
decorator(target, key, paramIndex);
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
//#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
|
+
//#region src/define-account.ts
|
|
21
|
+
/**
|
|
22
|
+
* 생성자 인자의 타입이 클래스여야 `emitDecoratorMetadata`가 주입 토큰을 기록한다. 실제로 주입되는 값은
|
|
23
|
+
* `createAccountServer`가 만든 객체이고, `implements`가 그 모양과 이 클래스를 묶어 둔다.
|
|
24
|
+
*/
|
|
25
|
+
var AccountServerToken = class {};
|
|
26
|
+
function defineAccount(scopes = {}) {
|
|
27
|
+
const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder().setClassMethodName("forRoot").setExtras({ isGlobal: false }, (module, extras) => ({
|
|
28
|
+
...module,
|
|
29
|
+
global: extras.isGlobal
|
|
30
|
+
})).build();
|
|
31
|
+
const RUNTIME = Symbol("gsainfoteam-account:runtime");
|
|
32
|
+
class AccountService extends AccountServerToken {}
|
|
33
|
+
const createRuntime = ({ verifyRegistration = "error", ...options }) => ({
|
|
34
|
+
service: createAccountServer({
|
|
35
|
+
...options,
|
|
36
|
+
...scopes
|
|
37
|
+
}),
|
|
38
|
+
verifyRegistration
|
|
39
|
+
});
|
|
40
|
+
let AccountModule = class AccountModule extends ConfigurableModuleClass {
|
|
41
|
+
runtime;
|
|
42
|
+
constructor(runtime) {
|
|
43
|
+
super();
|
|
44
|
+
this.runtime = runtime;
|
|
45
|
+
}
|
|
46
|
+
async onApplicationBootstrap() {
|
|
47
|
+
const { service, verifyRegistration } = this.runtime;
|
|
48
|
+
if (verifyRegistration === "off") return;
|
|
49
|
+
try {
|
|
50
|
+
await service.verifyRegistration();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const mismatch = AccountError.is(error, "invalid_client");
|
|
53
|
+
if (mismatch && verifyRegistration === "error") throw error;
|
|
54
|
+
new Logger("AccountModule").warn(mismatch ? `IdP registration does not match: ${error.description}` : `could not check the IdP registration: ${String(error)}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
AccountModule = __decorate([Module({
|
|
59
|
+
providers: [{
|
|
60
|
+
provide: RUNTIME,
|
|
61
|
+
inject: [MODULE_OPTIONS_TOKEN],
|
|
62
|
+
useFactory: createRuntime
|
|
63
|
+
}, {
|
|
64
|
+
provide: AccountService,
|
|
65
|
+
inject: [RUNTIME],
|
|
66
|
+
useFactory: (runtime) => runtime.service
|
|
67
|
+
}],
|
|
68
|
+
exports: [AccountService]
|
|
69
|
+
}), __decorateParam(0, Inject(RUNTIME))], AccountModule);
|
|
70
|
+
return {
|
|
71
|
+
AccountModule,
|
|
72
|
+
AccountService
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/index.ts
|
|
77
|
+
/** scope에 맞춘 필드 타입이 필요하면 {@link defineAccount}를 쓴다. */
|
|
78
|
+
const { AccountModule, AccountService } = defineAccount();
|
|
79
|
+
//#endregion
|
|
80
|
+
export { AccountModule, AccountService, defineAccount };
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@infoteam/account-nest",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "NestJS module for the Infoteam account IdP",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/gsainfoteam/account-sdk.git",
|
|
10
|
+
"directory": "packages/nest"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./dist/index.js",
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@infoteam/account-contract": "^0.3.0",
|
|
25
|
+
"@infoteam/account-testing": "^0.6.0",
|
|
26
|
+
"@nestjs/common": "^11.2.7",
|
|
27
|
+
"@nestjs/core": "^11.2.7",
|
|
28
|
+
"@nestjs/platform-express": "^11.2.7",
|
|
29
|
+
"@nestjs/platform-fastify": "^11.2.7",
|
|
30
|
+
"@nestjs/testing": "^11.2.7",
|
|
31
|
+
"@types/node": "^24.0.0",
|
|
32
|
+
"reflect-metadata": "^0.2.2",
|
|
33
|
+
"rxjs": "^7.8.2",
|
|
34
|
+
"tsdown": "^0.23.0",
|
|
35
|
+
"typescript": "~6.0.3",
|
|
36
|
+
"vitest": "^5.0.3",
|
|
37
|
+
"zod": "^4.6.5"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=20.19"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@infoteam/account-core": "^0.6.0",
|
|
44
|
+
"@infoteam/account-server": "^0.6.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
|
|
48
|
+
"zod": "^4.0.0"
|
|
49
|
+
},
|
|
50
|
+
"types": "./dist/index.d.ts",
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsdown",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"lint": "eslint .",
|
|
55
|
+
"test": "vitest run"
|
|
56
|
+
}
|
|
6
57
|
}
|