@infoteam/account-server 0.8.0 → 0.9.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 CHANGED
@@ -1,9 +1,10 @@
1
1
  # @infoteam/account-server
2
2
 
3
- 서비스 백엔드용 인포팀 계정(IdP) 클라이언트. 특정 프레임워크에 의존하지 않고 `fetch`만 쓴다. NestJS라면 [`@infoteam/account-nest`](../nest)를 쓴다.
3
+ [![npm](https://img.shields.io/npm/v/%40infoteam%2Faccount-server?color=CB3837)](https://www.npmjs.com/package/@infoteam/account-server)
4
4
 
5
- 이 패키지는 IdP로 사용자를 확인하는 데까지만 맡는다. [서비스 세션](../../README.md#서비스-세션)(토큰 발급, 갱신, 로그아웃)은 서비스가
6
- [세션 프로토콜](../../README.md#세션-프로토콜)에 맞춰 직접 구현한다.
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
- - `loginWithCode`는 code를 confidential client로서 교환하고, 응답에 담긴 id_token으로 사용자를 만든다. 그래서 프론트는 `openid`를 요청해야 한다(웹과 Flutter SDK는 항상 요청한다).
34
- - `requiredScopes`의 필드는 `loginWithCode` 결과에서 필수 타입이 된다. id_token에 필드가 빠져 있으면 `missing_claims`로 실패한다. `profile`과 `picture`는
35
- 사용자가 비워 둘 수 있어서 예외다.
36
- - `getUserInfoBySub` 결과에서는 `clientCredentialsScopes` 중 `requiredScopes`에도 있는 필드만 필수 타입이다. 선택 scope는 사용자가 거절했을 수 있어서, 그 필드는 `undefined`일 수 있다.
37
- - `requiredScopes`에는 client에 **필수로** 등록한 scope만 넣는다. 선택 scope를 넣으면 그 scope를 거부한 사용자는 로그인하지 못한다.
38
- - `loginWithCode(params, { maxAge: 300, amr: ['hwk'] })`처럼 로그인 조건을 요구할 수 있다. IdP에 로그인한 지 5분이 넘었거나 패스키로 로그인하지 않았으면
39
- `insufficient_authentication`으로 실패한다. account에 2FA가 생기면 같은 자리에서 확인한다.
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
- | 메서드 | 기능 | secret |
44
- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------ | --------- |
45
- | `loginWithCode(params)` | code를 교환하고 id_token으로 사용자를 만든다 | 필요 |
46
- | `getUserInfoBySub(sub)` | client credentials 토큰으로 사용자 조회. 이 client에 동의하지 않았거나 없는 사용자면 `null`. 토큰은 캐시한다 | 필요 |
47
- | `verifyIdToken(idToken)` | 앱이 보낸 id_token 검증 | 필요 없음 |
48
- | `revoke({ token, tokenTypeHint })` | 토큰 폐기 | 필요 없음 |
49
- | `verifyRegistration()` | IdP 등록 정보와 `requiredScopes`, 인증 방식 대조 | 필요 없음 |
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
@@ -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, 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infoteam/account-server",
3
- "version": "0.8.0",
3
+ "version": "0.9.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.8.0",
34
+ "@infoteam/account-core": "^0.9.0",
35
35
  "es-toolkit": "^1.52.0"
36
36
  },
37
37
  "peerDependencies": {