@infoteam/account-server 0.8.0 → 0.10.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/README.md +32 -19
- package/dist/index.d.ts +6 -2
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# @infoteam/account-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@infoteam/account-server)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
서비스 백엔드용 인포팀 계정(IdP) 클라이언트입니다. 특정 프레임워크에 의존하지 않고 `fetch`만 씁니다. NestJS라면 [`@infoteam/account-nest`](https://github.com/gsainfoteam/account-sdk/tree/main/packages/nest)를 씁니다.
|
|
6
|
+
|
|
7
|
+
> **이 패키지는 IdP로 사용자를 확인하는 데까지만 맡습니다.** [서비스 세션](https://github.com/gsainfoteam/account-sdk#서비스-세션)(토큰 발급, 갱신, 로그아웃)은 서비스가 [세션 프로토콜](https://github.com/gsainfoteam/account-sdk#세션-프로토콜)에 맞춰 직접 구현합니다.
|
|
7
8
|
|
|
8
9
|
## 설치
|
|
9
10
|
|
|
@@ -11,6 +12,8 @@
|
|
|
11
12
|
pnpm add @infoteam/account-server zod
|
|
12
13
|
```
|
|
13
14
|
|
|
15
|
+
ESM으로만 배포하고 Node 20.19 이상이 필요합니다. jest를 쓰면 [`account-nest`의 jest 설정](https://github.com/gsainfoteam/account-sdk/tree/main/packages/nest#jest-설정)을 똑같이 적용합니다.
|
|
16
|
+
|
|
14
17
|
## 사용
|
|
15
18
|
|
|
16
19
|
```ts
|
|
@@ -22,30 +25,40 @@ const account = createAccountServer({
|
|
|
22
25
|
clientSecret: process.env.ACCOUNT_CLIENT_SECRET,
|
|
23
26
|
requiredScopes: ['name', 'email'], // client 에 필수로 등록한 scope
|
|
24
27
|
clientCredentialsScopes: ['name'], // getUserInfoBySub 를 쓸 때만. client 에 등록한 scope 여야 한다
|
|
28
|
+
// fetch: 생략하면 전역 fetch 를 쓴다
|
|
25
29
|
});
|
|
26
30
|
|
|
27
31
|
// 프론트가 callback 에서 받은 값을 그대로 넘긴다
|
|
28
|
-
const { user } = await account.loginWithCode({ code, codeVerifier, redirectUri, nonce });
|
|
32
|
+
const { user } = await account.loginWithCode({ code, codeVerifier, redirectUri, nonce, iss });
|
|
29
33
|
user.name; // string
|
|
30
34
|
user.studentId; // string | undefined
|
|
31
35
|
```
|
|
32
36
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
옵션이 비어 있거나 틀리면 `createAccountServer`가 바로 `invalid_request`를 던집니다. `iss`는 callback이 준 값이고 생략할 수 있습니다. 값을 주면 discovery 문서의 issuer와 비교해서, 다르면 `issuer_mismatch`로 실패합니다.
|
|
38
|
+
|
|
39
|
+
`loginWithCode`는 code를 confidential client로서 교환하고, 응답에 담긴 id_token으로 사용자를 만듭니다. 그래서 프론트는 `openid`를 요청해야 합니다. 웹과 Flutter SDK는 항상 요청합니다.
|
|
40
|
+
|
|
41
|
+
### scope와 필드 타입
|
|
42
|
+
|
|
43
|
+
- `requiredScopes`의 필드는 `loginWithCode` 결과에서 필수 타입이 됩니다. id_token에 필드가 빠져 있으면 `missing_claims`로 실패합니다. `profile`과 `picture`는 사용자가 비워 둘 수 있어서 예외입니다.
|
|
44
|
+
- `getUserInfoBySub` 결과에서는 `clientCredentialsScopes` 중 `requiredScopes`에도 있는 필드만 필수 타입입니다. 선택 scope는 사용자가 거절했을 수 있어서, 그 필드는 `undefined`일 수 있습니다. 필수 타입인 필드가 응답에 없으면 `missing_claims`로 실패합니다.
|
|
45
|
+
- 두 결과의 타입은 `LoggedInUser<typeof account>`와 `LookedUpUser<typeof account>`로 꺼냅니다. scope를 `UserInfo<'name' | 'email'>`처럼 다시 적지 않아도 됩니다.
|
|
46
|
+
|
|
47
|
+
> **`requiredScopes`에는 client에 필수로 등록한 scope만 넣습니다.** 선택 scope를 넣으면 그 scope를 거부한 사용자는 로그인하지 못합니다.
|
|
48
|
+
|
|
49
|
+
### 로그인 조건
|
|
50
|
+
|
|
51
|
+
`loginWithCode(params, { maxAge: 300, amr: ['hwk'] })`처럼 로그인 조건을 요구할 수 있습니다. IdP에 로그인한 지 5분이 넘었거나 패스키로 로그인하지 않았으면 `insufficient_authentication`으로 실패합니다. `amr`은 나열한 값 중 하나만 있으면 통과합니다. id_token에 `auth_time`이 없는 오래된 세션은 `maxAge`를 주면 항상 실패합니다. account에 2FA가 생기면 같은 방식으로 확인합니다.
|
|
40
52
|
|
|
41
53
|
## 메서드
|
|
42
54
|
|
|
43
|
-
| 메서드
|
|
44
|
-
|
|
|
45
|
-
| `loginWithCode(params)`
|
|
46
|
-
| `getUserInfoBySub(sub)`
|
|
47
|
-
| `verifyIdToken(idToken)`
|
|
48
|
-
| `revoke({ token, tokenTypeHint })`
|
|
49
|
-
| `verifyRegistration()`
|
|
55
|
+
| 메서드 | 기능 | secret |
|
|
56
|
+
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
|
|
57
|
+
| `loginWithCode(params)` | code를 교환하고 id_token으로 사용자를 만듭니다 | 필요 |
|
|
58
|
+
| `getUserInfoBySub(sub)` | client credentials 토큰으로 사용자 조회. 이 client에 동의하지 않았거나 없는 사용자면 `null`. 토큰은 캐시합니다. `clientCredentialsScopes`가 없으면 `invalid_request` | 필요 |
|
|
59
|
+
| `verifyIdToken(idToken, { nonce? })` | 앱이 보낸 id_token의 서명, `iss`, `aud`(`clientId`) 검증 | 필요 없음 |
|
|
60
|
+
| `revoke({ token, tokenTypeHint })` | 토큰 폐기 | 필요 없음 |
|
|
61
|
+
| `verifyRegistration()` | IdP 등록 정보와 대조. `requiredScopes`는 필수 scope로, `clientCredentialsScopes`는 필수나 선택 scope로 등록됐는지 보고, secret이 있으면 인증 방식도 봅니다 | 필요 없음 |
|
|
62
|
+
| `metadata()` | IdP의 discovery 문서 | 필요 없음 |
|
|
50
63
|
|
|
51
|
-
실패하면 `AccountError`를 던지므로 `code`로 경우를
|
|
64
|
+
실패하면 `AccountError`를 던지므로 `code`로 경우를 나눕니다.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AccountError, AccountErrorCode, AccountMetadata, AccountMetadata as AccountMetadata$1, ClientScope, ClientScope as ClientScope$1, ENVIRONMENTS, Environment, ExchangeCodeParams, ExchangeCodeParams as ExchangeCodeParams$1, IdTokenClaims, IdTokenClaims as IdTokenClaims$1, IssuerInput, IssuerInput as IssuerInput$1, LoginCodeBodySchema, LoginRequestBody, LoginTicketBodySchema, RevokeParams, RevokeParams as RevokeParams$1, SESSION_REJECTED, Scope, SessionRejectedResponse, SessionTokensResponse, SessionTokensResponseSchema, SessionTransport, TokenResponse, TokenResponse as TokenResponse$1, UserInfo, UserInfo as UserInfo$1 } from "@infoteam/account-core";
|
|
1
|
+
import { AccountError, AccountErrorCode, AccountMetadata, AccountMetadata as AccountMetadata$1, ClientScope, ClientScope as ClientScope$1, ENVIRONMENTS, Environment, ExchangeCodeParams, ExchangeCodeParams as ExchangeCodeParams$1, INVALID_TICKET, IdTokenClaims, IdTokenClaims as IdTokenClaims$1, IssuerInput, IssuerInput as IssuerInput$1, LoginCodeBodySchema, LoginRequestBody, LoginTicketBodySchema, RevokeParams, RevokeParams as RevokeParams$1, SESSION_REJECTED, Scope, SessionRejectedResponse, SessionTokensResponse, SessionTokensResponseSchema, SessionTransport, TokenResponse, TokenResponse as TokenResponse$1, UserInfo, UserInfo as UserInfo$1 } from "@infoteam/account-core";
|
|
2
2
|
import * as z from "zod/mini";
|
|
3
3
|
//#region src/options.d.ts
|
|
4
4
|
/** 값은 보통 환경 변수에서 오므로, 첫 요청이 아니라 서버가 시작될 때 검증한다. */
|
|
@@ -83,7 +83,11 @@ interface AccountServer<RequiredScope extends ClientScope$1 = never, LookupScope
|
|
|
83
83
|
*/
|
|
84
84
|
verifyRegistration(): Promise<void>;
|
|
85
85
|
}
|
|
86
|
+
/** `loginWithCode`가 돌려주는 사용자다. `A`에는 `AccountServer`나 nest의 `AccountService`를 넣는다. */
|
|
87
|
+
type LoggedInUser<A extends Pick<AccountServer, 'loginWithCode'>> = Awaited<ReturnType<A['loginWithCode']>>['user'];
|
|
88
|
+
/** `getUserInfoBySub`가 찾은 사용자다(`null` 제외). `clientCredentialsScopes`와 `requiredScopes`에 모두 있는 scope의 필드만 필수다. */
|
|
89
|
+
type LookedUpUser<A extends Pick<AccountServer, 'getUserInfoBySub'>> = NonNullable<Awaited<ReturnType<A['getUserInfoBySub']>>>;
|
|
86
90
|
/** @throws {@link AccountError} 옵션이 없거나 비어 있으면 `invalid_request`. */
|
|
87
91
|
export declare function createAccountServer<const RequiredScopes extends readonly ClientScope$1[] = [], const LookupScopes extends readonly ClientScope$1[] = []>(input: AccountServerOptions<RequiredScopes, LookupScopes>): AccountServer<RequiredScopes[number], LookupScopes[number]>;
|
|
88
92
|
//#endregion
|
|
89
|
-
export { AccountError, type AccountErrorCode, type AccountMetadata, type AccountServer, type AccountServerOptions, type AuthenticationRequirement, type ClientScope, ENVIRONMENTS, type Environment, type ExchangeCodeParams, type IdTokenClaims, type IssuerInput, LoginCodeBodySchema, type LoginRequestBody, LoginTicketBodySchema, type LoginWithCodeParams, type RevokeParams, SESSION_REJECTED, type Scope, type SessionRejectedResponse, type SessionTokensResponse, SessionTokensResponseSchema, type SessionTransport, type TokenResponse, type UserInfo };
|
|
93
|
+
export { AccountError, type AccountErrorCode, type AccountMetadata, type AccountServer, type AccountServerOptions, type AuthenticationRequirement, type ClientScope, ENVIRONMENTS, type Environment, type ExchangeCodeParams, INVALID_TICKET, type IdTokenClaims, type IssuerInput, type LoggedInUser, LoginCodeBodySchema, type LoginRequestBody, LoginTicketBodySchema, type LoginWithCodeParams, type LookedUpUser, type RevokeParams, SESSION_REJECTED, type Scope, type SessionRejectedResponse, type SessionTokensResponse, SessionTokensResponseSchema, type SessionTransport, type TokenResponse, type UserInfo };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AccountError, AccountError as AccountError$1, CLIENT_TOKEN_REFRESH_MARGIN_MS, ClientScopeSchema, ENVIRONMENTS, LoginCodeBodySchema, LoginTicketBodySchema, SESSION_REJECTED, SessionTokensResponseSchema, discover, exchangeCode, fetchClientRegistration, fetchUserInfo, requestClientCredentials, revokeToken, userInfoFromIdToken, verifyIdToken } from "@infoteam/account-core";
|
|
1
|
+
import { AccountError, AccountError as AccountError$1, CLIENT_TOKEN_REFRESH_MARGIN_MS, ClientScopeSchema, ENVIRONMENTS, INVALID_TICKET, LoginCodeBodySchema, LoginTicketBodySchema, SESSION_REJECTED, SessionTokensResponseSchema, discover, exchangeCode, fetchClientRegistration, fetchUserInfo, requestClientCredentials, revokeToken, userInfoFromIdToken, verifyIdToken } from "@infoteam/account-core";
|
|
2
2
|
import * as z from "zod/mini";
|
|
3
3
|
import { Mutex, isFunction, isString } from "es-toolkit";
|
|
4
4
|
//#region src/client-token-cache.ts
|
|
@@ -124,4 +124,4 @@ function checkAuthentication(claims, { maxAge, amr }) {
|
|
|
124
124
|
if (amr && !amr.some((method) => claims.amr?.includes(method))) throw new AccountError$1("insufficient_authentication", { description: `the IdP login used ${claims.amr?.join(" ") || "an unknown method"}, not ${amr.join(" or ")}` });
|
|
125
125
|
}
|
|
126
126
|
//#endregion
|
|
127
|
-
export { AccountError, AccountServerOptionsSchema, ENVIRONMENTS, LoginCodeBodySchema, LoginTicketBodySchema, SESSION_REJECTED, SessionTokensResponseSchema, createAccountServer };
|
|
127
|
+
export { AccountError, AccountServerOptionsSchema, ENVIRONMENTS, INVALID_TICKET, LoginCodeBodySchema, LoginTicketBodySchema, SESSION_REJECTED, SessionTokensResponseSchema, createAccountServer };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@infoteam/account-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Backend client for the Infoteam account IdP: code exchange with id_token login and user lookup with client credentials",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"node": ">=20.19"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@infoteam/account-core": "^0.
|
|
34
|
+
"@infoteam/account-core": "^0.10.0",
|
|
35
35
|
"es-toolkit": "^1.52.0"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|