@infoteam/account-server 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 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,51 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @infoteam/account-server
2
+
3
+ 서비스 백엔드용 인포팀 계정(IdP) 클라이언트. 특정 프레임워크에 의존하지 않고 `fetch`만 쓴다. NestJS라면 [`@infoteam/account-nest`](../nest)를 쓴다.
4
+
5
+ 이 패키지는 IdP로 사용자를 확인하는 데까지만 맡는다. [서비스 세션](../../README.md#서비스-세션)(토큰 발급, 갱신, 로그아웃)은 서비스가
6
+ [세션 프로토콜](../../README.md#세션-프로토콜)에 맞춰 직접 구현한다.
7
+
8
+ ## 설치
9
+
10
+ ```bash
11
+ pnpm add @infoteam/account-server zod
12
+ ```
13
+
14
+ ## 사용
15
+
16
+ ```ts
17
+ import { createAccountServer } from '@infoteam/account-server';
18
+
19
+ const account = createAccountServer({
20
+ issuer: 'production',
21
+ clientId: process.env.ACCOUNT_CLIENT_ID!,
22
+ clientSecret: process.env.ACCOUNT_CLIENT_SECRET,
23
+ requiredScopes: ['name', 'email'], // client 에 필수로 등록한 scope
24
+ clientCredentialsScopes: ['name'], // getUserInfoBySub 를 쓸 때만. client 에 등록한 scope 여야 한다
25
+ });
26
+
27
+ // 프론트가 callback 에서 받은 값을 그대로 넘긴다
28
+ const { user } = await account.loginWithCode({ code, codeVerifier, redirectUri, nonce });
29
+ user.name; // string
30
+ user.studentId; // string | undefined
31
+ ```
32
+
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가 생기면 같은 자리에서 확인한다.
40
+
41
+ ## 메서드
42
+
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`, 인증 방식 대조 | 필요 없음 |
50
+
51
+ 실패하면 `AccountError`를 던지므로 `code`로 경우를 나눈다.
@@ -0,0 +1,89 @@
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, RevokeParams, RevokeParams as RevokeParams$1, Scope, TokenResponse, TokenResponse as TokenResponse$1, UserInfo, UserInfo as UserInfo$1 } from "@infoteam/account-core";
2
+ import * as z from "zod/mini";
3
+ //#region src/options.d.ts
4
+ /** 값은 보통 환경 변수에서 오므로, 첫 요청이 아니라 서버가 시작될 때 검증한다. */
5
+ export declare const AccountServerOptionsSchema: z.ZodMiniObject<{
6
+ issuer: z.ZodMiniCustom<IssuerInput$1, IssuerInput$1>;
7
+ clientId: z.ZodMiniString<string>;
8
+ clientSecret: z.ZodMiniOptional<z.ZodMiniString<string>>;
9
+ requiredScopes: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniEnum<{
10
+ email: "email";
11
+ profile: "profile";
12
+ name: "name";
13
+ picture: "picture";
14
+ phone_number: "phone_number";
15
+ student_id: "student_id";
16
+ }>>>;
17
+ clientCredentialsScopes: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniEnum<{
18
+ email: "email";
19
+ profile: "profile";
20
+ name: "name";
21
+ picture: "picture";
22
+ phone_number: "phone_number";
23
+ student_id: "student_id";
24
+ }>>>;
25
+ fetch: z.ZodMiniOptional<z.ZodMiniCustom<typeof fetch, typeof fetch>>;
26
+ }, z.core.$strip>;
27
+ type AccountServerOptions<RequiredScopes extends readonly ClientScope$1[] = readonly ClientScope$1[], LookupScopes extends readonly ClientScope$1[] = readonly ClientScope$1[]> = Omit<z.input<typeof AccountServerOptionsSchema>, 'requiredScopes' | 'clientCredentialsScopes'> & {
28
+ /**
29
+ * 이 scope의 claim이 id_token에 빠져 있으면 로그인이 `missing_claims`로 실패한다. 선택 scope를 넣으면 그 scope를
30
+ * 거부한 사용자는 로그인하지 못한다.
31
+ */
32
+ requiredScopes?: RequiredScopes;
33
+ /** client에 등록한 scope 중에서 골라야 하므로 기본값이 없다. */
34
+ clientCredentialsScopes?: LookupScopes;
35
+ };
36
+ //#endregion
37
+ //#region src/account-server.d.ts
38
+ /** 로그인이 이 조건을 채우지 못하면 프론트가 `login({ prompt: 'login' })`으로 사용자를 다시 로그인하게 한다. */
39
+ interface AuthenticationRequirement {
40
+ /** 초 단위다. */
41
+ maxAge?: number;
42
+ /** RFC 8176에 정의된 값을 하나 이상 넣는다. 비밀번호는 `pwd`, 패스키는 `hwk`다. */
43
+ amr?: readonly string[];
44
+ }
45
+ interface LoginWithCodeParams extends ExchangeCodeParams$1 {
46
+ /** authorization 요청에 보낸 nonce다. 이 값은 다른 로그인의 id_token을 재사용하지 못하게 한다. */
47
+ nonce: string;
48
+ }
49
+ interface AccountServer<RequiredScope extends ClientScope$1 = never, LookupScope extends ClientScope$1 = never> {
50
+ metadata(): Promise<AccountMetadata$1>;
51
+ /**
52
+ * 사용자는 이 client가 직접 교환한 id_token으로만 확인한다. account-be의 access token에는 대상 client가 적혀 있지
53
+ * 않아서, 프론트가 보낸 access token을 믿으면 누구나 등록할 수 있는 다른 client의 토큰으로도 로그인할 수 있다.
54
+ *
55
+ * @throws {@link AccountError} code가 이미 쓰였거나 만료됐으면 `invalid_grant`. id_token이 없거나 nonce가 다르면
56
+ * `invalid_id_token`. 필수 scope의 claim이 빠졌으면 `missing_claims`. `requirement`를 채우지 못하면
57
+ * `insufficient_authentication`.
58
+ */
59
+ loginWithCode(params: LoginWithCodeParams, requirement?: AuthenticationRequirement): Promise<{
60
+ tokens: TokenResponse$1;
61
+ user: UserInfo$1<RequiredScope>;
62
+ }>;
63
+ /**
64
+ * IdP가 재시작해 기존 토큰이 무효가 되면 401 대신 500을 돌려주므로, 두 응답 모두 토큰을 새로 받아 한 번 다시
65
+ * 시도한다.
66
+ *
67
+ * 이 client에 동의하지 않았거나 없는 사용자면 `null`이다. IdP는 둘을 구분해 주지 않는다.
68
+ *
69
+ * 사용자가 선택 scope를 거절했을 수 있어서, `requiredScopes`에도 있는 scope의 필드만 반드시 채워진다.
70
+ *
71
+ * @throws {@link AccountError} `requiredScopes`에도 있는 scope의 claim이 빠졌으면 `missing_claims`.
72
+ */
73
+ getUserInfoBySub(sub: string): Promise<UserInfo$1<Extract<LookupScope, RequiredScope>> | null>;
74
+ verifyIdToken(idToken: string, options?: {
75
+ nonce?: string;
76
+ }): Promise<IdTokenClaims$1>;
77
+ revoke(params: RevokeParams$1): Promise<void>;
78
+ /**
79
+ * 서버가 시작될 때 한 번 부른다. `requiredScopes`가 선택 scope로 등록되어 있으면 그 scope를 거부한 사용자가
80
+ * 로그인하지 못하므로, 이런 등록을 막는다.
81
+ *
82
+ * @throws {@link AccountError} 등록이 맞지 않으면 `invalid_client`로 실패하고, 틀린 점은 `description`에 있다.
83
+ */
84
+ verifyRegistration(): Promise<void>;
85
+ }
86
+ /** @throws {@link AccountError} 옵션이 없거나 비어 있으면 `invalid_request`. */
87
+ 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
+ //#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, type LoginWithCodeParams, type RevokeParams, type Scope, type TokenResponse, type UserInfo };
package/dist/index.js ADDED
@@ -0,0 +1,127 @@
1
+ import { AccountError, AccountError as AccountError$1, CLIENT_TOKEN_REFRESH_MARGIN_MS, ClientScopeSchema, ENVIRONMENTS, discover, exchangeCode, fetchClientRegistration, fetchUserInfo, requestClientCredentials, revokeToken, userInfoFromIdToken, verifyIdToken } from "@infoteam/account-core";
2
+ import * as z from "zod/mini";
3
+ import { Mutex, isFunction, isString } from "es-toolkit";
4
+ //#region src/client-token-cache.ts
5
+ function createClientTokenCache(request) {
6
+ const mutex = new Mutex();
7
+ let token;
8
+ return {
9
+ async get() {
10
+ await mutex.acquire();
11
+ try {
12
+ if (isFresh(token)) return token.value;
13
+ const tokens = await request();
14
+ token = {
15
+ value: tokens.accessToken,
16
+ expiresAt: Date.now() + (tokens.expiresIn ?? 0) * 1e3
17
+ };
18
+ return token.value;
19
+ } finally {
20
+ mutex.release();
21
+ }
22
+ },
23
+ invalidate() {
24
+ token = void 0;
25
+ }
26
+ };
27
+ }
28
+ function isFresh(token) {
29
+ return token !== void 0 && token.expiresAt - CLIENT_TOKEN_REFRESH_MARGIN_MS > Date.now();
30
+ }
31
+ //#endregion
32
+ //#region src/options.ts
33
+ const nonEmpty = () => z.string().check(z.minLength(1));
34
+ /** 값은 보통 환경 변수에서 오므로, 첫 요청이 아니라 서버가 시작될 때 검증한다. */
35
+ const AccountServerOptionsSchema = z.object({
36
+ /** `'production'`, `'staging'`, 또는 다른 account-be 배포의 `https:` API origin 중 하나다. */
37
+ issuer: z.custom((value) => isString(value) && value.length > 0),
38
+ clientId: nonEmpty(),
39
+ /** {@link AccountServer.loginWithCode}와 {@link AccountServer.getUserInfoBySub}에 필요하다. */
40
+ clientSecret: z.optional(nonEmpty()),
41
+ requiredScopes: z.optional(z.array(ClientScopeSchema)),
42
+ clientCredentialsScopes: z.optional(z.array(ClientScopeSchema)),
43
+ fetch: z.optional(z.custom(isFunction))
44
+ });
45
+ //#endregion
46
+ //#region src/account-server.ts
47
+ /** @throws {@link AccountError} 옵션이 없거나 비어 있으면 `invalid_request`. */
48
+ function createAccountServer(input) {
49
+ const parsed = AccountServerOptionsSchema.safeParse(input);
50
+ if (!parsed.success) throw new AccountError$1("invalid_request", { description: `createAccountServer options: ${z.prettifyError(parsed.error)}` });
51
+ const { issuer, clientId, clientSecret, requiredScopes, clientCredentialsScopes, fetch } = input;
52
+ const client = {
53
+ clientId,
54
+ clientSecret
55
+ };
56
+ const metadata = () => discover(issuer, { fetch });
57
+ const requireSecret = (operation) => {
58
+ if (!clientSecret) throw new AccountError$1("invalid_client", { description: `${operation} needs clientSecret` });
59
+ return clientSecret;
60
+ };
61
+ const requireScopes = (operation) => {
62
+ if (!clientCredentialsScopes?.length) throw new AccountError$1("invalid_request", { description: `${operation} needs clientCredentialsScopes` });
63
+ return clientCredentialsScopes;
64
+ };
65
+ const clientToken = createClientTokenCache(async () => requestClientCredentials(await metadata(), {
66
+ clientId,
67
+ clientSecret: requireSecret("getUserInfoBySub")
68
+ }, requireScopes("getUserInfoBySub"), { fetch }));
69
+ return {
70
+ metadata,
71
+ async loginWithCode(params, requirement = {}) {
72
+ requireSecret("loginWithCode");
73
+ const tokens = await exchangeCode(await metadata(), client, params, { fetch });
74
+ if (!tokens.idTokenClaims) throw new AccountError$1("invalid_id_token", { description: "the token response has no id_token; request the openid scope" });
75
+ checkAuthentication(tokens.idTokenClaims, requirement);
76
+ return {
77
+ tokens,
78
+ user: userInfoFromIdToken(tokens.idTokenClaims, requiredScopes)
79
+ };
80
+ },
81
+ async getUserInfoBySub(sub) {
82
+ const guaranteed = requireScopes("getUserInfoBySub").filter((scope) => requiredScopes?.some((required) => required === scope) ?? false);
83
+ const lookup = async (token) => fetchUserInfo(await metadata(), client, token, {
84
+ fetch,
85
+ sub,
86
+ requiredScopes: guaranteed
87
+ }).catch((error) => {
88
+ if (AccountError$1.is(error) && error.status === 404) return null;
89
+ throw error;
90
+ });
91
+ try {
92
+ return await lookup(await clientToken.get());
93
+ } catch (error) {
94
+ if (!(AccountError$1.is(error, "invalid_token") || AccountError$1.is(error, "server_error"))) throw error;
95
+ clientToken.invalidate();
96
+ return lookup(await clientToken.get());
97
+ }
98
+ },
99
+ async verifyIdToken(idToken, verifyOptions = {}) {
100
+ return verifyIdToken(await metadata(), idToken, {
101
+ fetch,
102
+ audience: clientId,
103
+ nonce: verifyOptions.nonce
104
+ });
105
+ },
106
+ async revoke(params) {
107
+ return revokeToken(await metadata(), client, params, { fetch });
108
+ },
109
+ async verifyRegistration() {
110
+ const registration = await fetchClientRegistration(await metadata(), clientId, { fetch });
111
+ const registered = [...registration.scopes, ...registration.optionalScopes];
112
+ const problems = [
113
+ ...(requiredScopes ?? []).filter((scope) => !registration.scopes.includes(scope)).map((scope) => `requiredScopes has ${scope}, which is not a required scope of the client`),
114
+ ...(clientCredentialsScopes ?? []).filter((scope) => !registered.includes(scope)).map((scope) => `clientCredentialsScopes has ${scope}, which the client does not have`),
115
+ ...clientSecret && registration.tokenEndpointAuthMethod !== "client_secret_post" ? [`the client authenticates with ${registration.tokenEndpointAuthMethod ?? "an unknown method"}, not client_secret_post`] : []
116
+ ];
117
+ if (problems.length) throw new AccountError$1("invalid_client", { description: problems.join("; ") });
118
+ }
119
+ };
120
+ }
121
+ function checkAuthentication(claims, { maxAge, amr }) {
122
+ const now = Math.floor(Date.now() / 1e3);
123
+ if (maxAge !== void 0 && (claims.auth_time === void 0 || now - claims.auth_time > maxAge)) throw new AccountError$1("insufficient_authentication", { description: `the IdP login is older than ${maxAge} s` });
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
+ }
126
+ //#endregion
127
+ export { AccountError, AccountServerOptionsSchema, ENVIRONMENTS, createAccountServer };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@infoteam/account-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.6.0",
4
+ "description": "Backend client for the Infoteam account IdP: code exchange with id_token login and user lookup with client credentials",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/gsainfoteam/account-sdk.git",
10
+ "directory": "packages/server"
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
+ "@types/node": "^24.0.0",
25
+ "tsdown": "^0.23.0",
26
+ "typescript": "~6.0.3",
27
+ "vitest": "^5.0.3",
28
+ "zod": "^4.6.5"
29
+ },
30
+ "engines": {
31
+ "node": ">=20.19"
32
+ },
33
+ "dependencies": {
34
+ "@infoteam/account-core": "^0.6.0",
35
+ "es-toolkit": "^1.52.0"
36
+ },
37
+ "peerDependencies": {
38
+ "zod": "^4.0.0"
39
+ },
40
+ "types": "./dist/index.d.ts",
41
+ "scripts": {
42
+ "build": "tsdown",
43
+ "typecheck": "tsc --noEmit",
44
+ "lint": "eslint .",
45
+ "test": "vitest run",
46
+ "test:live": "vitest run --config vitest.live.config.ts"
47
+ }
6
48
  }