@reopt-ai/workspace-sdk 0.1.0-rc.1 → 0.1.0-rc.9

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/CHANGELOG.md CHANGED
@@ -7,6 +7,86 @@ This project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.0-rc.9] — 2026-11-21
11
+
12
+ Pre-release (`npm i @reopt-ai/workspace-sdk@next`) — npm에는 rc.1 다음 이 버전이 처음이다. rc.2~rc.8은 로컬 tarball로만
13
+ 전달했고, 아래 그 절들의 변경이 모두 이 버전에 실린다.
14
+
15
+ ### Added
16
+
17
+ - `/operator` — 리옵트 운영자 가드(RFC-0034 §5.2: `requireOperator`·`evaluateOperator`·`decodeIdTokenClaims`·
18
+ `latestReoptAccount`·`stepUpAuthorizationParams`, 제공자 id·step-up 상한 상수). `@reopt-ai/brandapp-sdk/superadmin`에서
19
+ 옮겨 왔다 — 관리자 표면은 이 패키지가 갖는다. 문서 `docs/operator.md`.
20
+
21
+ ## [0.1.0-rc.8] — 2026-11-21 (tarball only — published in rc.9)
22
+
23
+ ### Added
24
+
25
+ - `ConnectFolder.fileCount`·`childCount` — `connect.folders.list()`가 폴더 카드의 파일·하위 폴더 수를 함께 준다(Studio 파일 관리자와
26
+ 같은 기준, 서버가 묶어서 셈 — 폴더마다 2번 부르던 것을 없앤다, bootstrap 보고).
27
+
28
+ ## [0.1.0-rc.7] — 2026-11-21 (tarball only — published in rc.9)
29
+
30
+ ### Added
31
+
32
+ - `REOPT_RECONSENT_PARAMS`(`{ prompt: "consent" }`)·`isReconsentRequired(error)` — 직원의 옛 동의가 설치되지 않은 워크스페이스에
33
+ 묶여 `/v1/connect/*`가 **403 `WORKSPACE_MISMATCH`**(새 코드)로 거절하면 동의 화면을 강제로 다시 열어 한 번에 다시 묶는다
34
+ (bootstrap 제안). `authClient.signIn.social({ provider: "reopt", additionalParams: REOPT_RECONSENT_PARAMS })`.
35
+
36
+ ### Changed
37
+
38
+ - 문서 "Credentials" — 워크스페이스 앱(설치) 클라이언트는 `private_key_jwt`뿐이다. 시크릿 예시를 옛 시드 클라이언트용으로 내렸다.
39
+
40
+ ## [0.1.0-rc.6] — 2026-11-21 (tarball only — published in rc.9)
41
+
42
+ ### Fixed
43
+
44
+ - `installation.health(id)`가 서버의 봉투(`{ id, status, health }`)를 그대로 돌려줘 `keys`·`jwks`가 한 단계 안에 묻혀 있었다
45
+ (bootstrap 보고) — 이제 `InstallationHealthView`를 돌려준다. `connection.health()`·`registerKeys()`도 같이 바로잡힌다.
46
+ - `installation.reinstall()`이 약속한 `pendingManifest`가 실제로는 오지 않았다(서버는 `pendingManifestHash`) — 파생해 돌려준다.
47
+ 타입 `InstallationReinstallResult`(`pendingManifest: boolean`·`pendingManifestHash`·`consoleUrl`).
48
+ - 두 결함 모두 단위 테스트의 가짜 서버가 SDK가 기대하는 모양을 직접 만들어 통과했다 — 가짜 응답을 실제 라우트 모양으로 바꿨고,
49
+ `health`는 실제 라우터를 SDK로 부르는 이음새(`rfc0043-installation-client-keys`)가 지킨다.
50
+
51
+ ## [0.1.0-rc.5] — 2026-11-21 (tarball only — published in rc.9)
52
+
53
+ ### Added
54
+
55
+ - `ConnectForm.intakePipelineId` — 제출이 카드로 쌓이는 운영 보드(Works 파이프라인). 제출이 없어도 `works.listPipelines()`에서
56
+ 그 보드의 단계(=`inquiries.moveStage` 대상)를 그릴 수 있다(bootstrap 제안). 연결되지 않은 폼·옛 서버는 null.
57
+
58
+ ## [0.1.0-rc.4] — 2026-11-20 (tarball only — published in rc.9)
59
+
60
+ ### Added
61
+
62
+ - `connect.files.get(id)`, `files.update`이 갱신된 `ConnectFile`을 돌려준다(`fileId` 호환 유지), `files.list({ limit, offset })`(최대 500).
63
+ - `ConnectFile.blobUrl` — 게시물 본문에 넣는 정본 주소(Studio 에디터와 같은 `/api/blob/…`). 발행하거나 발행된 글의 본문을 고치면
64
+ 리옵트가 본문이 참조하는 파일을 공개로 바꾼다 — 공개 사이트 본문 이미지(bootstrap 보고).
65
+
66
+ ### Added
67
+
68
+ - **`/better-auth` — 관리자(직원) 로그인 프리셋** `createReoptWorkspaceLogin()`(RFC-0043): 설치의 connect 클라이언트로
69
+ authorization code + PKCE + `private_key_jwt`(시크릿 없음), `resource`=플랫폼 origin을 인가·교환·refresh 모두에.
70
+ `database` 없이 stateless 세션. `login.getAccessToken(auth, headers)` → `createConnectClient({ accessToken })`. optional peer
71
+ `better-auth >=1.7.18`.
72
+ - 게시물 분류·SEO: 읽기(connect·platform)에 `tags`·`metaTitle`·`metaDescription`, 쓰기(`posts.create/update`)에 `tags`(통째 교체,
73
+ 없는 이름은 생성)·`metaTitle`·`metaDescription`·`coverImageId`(create에도). 대표 이미지는 이미지여야 하고 지정하면 공개가 된다.
74
+ - `platform.posts.list({ tag })`, `platform.posts.get(slug, { groupId })` — 다른 게시판의 같은 slug는 404.
75
+ - `connect.folders.update(id, { name, parentId })`·`connect.folders.delete(id)`(비어 있지 않으면 409, 시스템 폴더 403).
76
+ - `createPlatformClient({ dpop: false })` — fetch를 가짜 플랫폼에 꽂은 로컬 dev·테스트용(실서버는 DPoP를 요구한다).
77
+
78
+ - `login.refreshInProxy(auth, headers)` — `proxy.ts`에서 만료 전(기본 120초) refresh하고 새 계정 쿠키(`setCookies`)와 같은 요청의
79
+ 뒤쪽이 읽을 `cookieHeader`를 준다. 서버 컴포넌트는 쿠키를 못 써서 거기서 refresh하면 회전된 토큰을 잃는다.
80
+ `applySetCookiesToCookieHeader` 순수 함수, `onTokenError` 옵션.
81
+
82
+ ### Fixed
83
+
84
+ - 관리자 로그인 `getAccessToken`이 항상 `null`이었다 — better-auth 1.7.18+의 `/get-access-token` 본문은 `{ accountId }` 또는
85
+ `{ useAccountCookie: true }`인데 `providerId`를 보내 검증에서 거절됐고 그 오류를 삼켰다(bootstrap 세션 보고). 이제 계정 쿠키를
86
+ 고르고, 실패 코드는 `onTokenError`(기본 `console.warn`)로 드러낸다. `ReoptWorkspaceAuthLike`가 앱의 실제 인스턴스를 받는다.
87
+ - 플랫폼 클라이언트가 JSON이 아닌 응답(프록시 502·서버 오류 HTML)에 `SyntaxError`를 던졌다 — 이제 `PlatformApiError`
88
+ (`HTTP_ERROR`, 5xx는 retryable; 성공인데 JSON이 아니면 `INVALID_RESPONSE`).
89
+
10
90
  ## [0.1.0-rc.1] — 2026-11-20
11
91
 
12
92
  Pre-release (`npm i @reopt-ai/workspace-sdk@next`).
@@ -0,0 +1,97 @@
1
+ import { r as ClientKeyRing } from "../keys-B2pA8EkU.js";
2
+ import { genericOAuth } from "better-auth/plugins";
3
+ //#region src/better-auth/index.d.ts
4
+ /** Better Auth 제공자 id — `signIn.social({ provider })`와 콜백 경로(`/api/auth/callback/reopt`)의 마지막 조각. */
5
+ declare const REOPT_WORKSPACE_PROVIDER_ID = "reopt";
6
+ /**
7
+ * 기본 scope — 로그인(`openid profile email`) + refresh(`offline_access`) + 워크스페이스 읽기. 쓰기·도메인 scope는
8
+ * `scopes`로 더한다(설치의 connect 클라이언트에 허용된 것만 발급된다).
9
+ */
10
+ declare const REOPT_WORKSPACE_LOGIN_SCOPES: readonly string[];
11
+ /**
12
+ * 동의 화면을 다시 연다 — `authClient.signIn.social({ provider: "reopt", additionalParams: REOPT_RECONSENT_PARAMS })`.
13
+ * 기존 동의가 있으면 리옵트는 동의 화면을 건너뛰므로(RFC-0043 Q1) 워크스페이스를 다시 고르게 하려면 이것이 필요하다.
14
+ */
15
+ declare const REOPT_RECONSENT_PARAMS: Readonly<{
16
+ prompt: "consent";
17
+ }>;
18
+ /**
19
+ * 위임 호출이 "동의를 다시 받아야 함"으로 거절됐는가 — 직원의 동의가 이 앱이 설치되지 않은 워크스페이스에 묶여 있다
20
+ * (`/v1/connect/*` 403 `WORKSPACE_MISMATCH`). 그러면 `REOPT_RECONSENT_PARAMS`로 다시 로그인시킨다. `PlatformApiError`를
21
+ * import하지 않고 모양으로 본다 — 이 진입점이 zod를 끌어오지 않게.
22
+ */
23
+ declare function isReconsentRequired(error: unknown): boolean;
24
+ type ReoptWorkspaceLoginOptions = {
25
+ /** 설치의 connect 클라이언트 id. 생략 시 env `REOPT_CONNECT_CLIENT_ID`. */
26
+ clientId?: string;
27
+ /** 서명 키. 생략 시 env `REOPT_CLIENT_PRIVATE_KEY_JWK`(+`_NEXT`) — 기계 자격과 같은 키다(같은 설치·같은 JWKS). */
28
+ keyRing?: ClientKeyRing;
29
+ /** 기본 scope에 더할 것(예: `workspace:write`, `customer:read`, `eav:read`). */
30
+ scopes?: readonly string[];
31
+ /** 플랫폼 origin(= 토큰 audience). 생략 시 env `REOPT_PLATFORM_URL` → 환경 기본값. */
32
+ platformUrl?: string;
33
+ /** id 호스트. 생략 시 env `REOPT_ID_BASE_URL` → 환경 기본값. */
34
+ idBaseUrl?: string;
35
+ isProduction?: boolean;
36
+ /**
37
+ * 리옵트 로그아웃까지 할지(end_session). 기본은 이 앱의 세션만 지운다 — 직원이 리옵트 스튜디오에서도 로그아웃되면 놀란다.
38
+ */
39
+ providerLogout?: boolean | {
40
+ postLogoutRedirectURI?: string;
41
+ };
42
+ /**
43
+ * 토큰을 꺼내지 못했을 때(재로그인 필요) 그 코드를 받는다 — `UNAUTHORIZED`(세션 없음)·`ACCOUNT_NOT_FOUND`(계정 쿠키 없음)·
44
+ * `FAILED_TO_GET_ACCESS_TOKEN`(refresh 거절 — 동의 철회·멤버 제외·refresh token 재사용). 기본은 `console.warn` 한 줄.
45
+ */
46
+ onTokenError?: (code: string, error: unknown) => void;
47
+ };
48
+ /**
49
+ * 앱의 Better Auth 인스턴스 — `auth.api.getAccessToken`·`auth.api.refreshToken`만 쓴다. 매개변수를 `never`로 둬서 앱 인스턴스의
50
+ * 정밀한 엔드포인트 타입이 그대로 들어온다(좁은 함수 타입으로 적으면 반공변이라 TS2345로 거절된다).
51
+ */
52
+ type ReoptWorkspaceAuthLike = {
53
+ api: {
54
+ getAccessToken: (...args: never[]) => unknown;
55
+ refreshToken: (...args: never[]) => unknown;
56
+ };
57
+ };
58
+ /** `refreshInProxy`의 결과 — 응답에 붙일 Set-Cookie와, 같은 요청의 뒤쪽(RSC)이 읽을 쿠키 헤더. */
59
+ type ReoptWorkspaceRefreshResult = {
60
+ /** 응답에 `append("set-cookie", …)`로 그대로 붙인다. 바뀐 것이 없으면 빈 배열. */
61
+ setCookies: string[];
62
+ /** 원 요청의 Cookie 헤더에 새 값을 반영한 것 — `NextResponse.next({ request: { headers } })`로 넘긴다. */
63
+ cookieHeader: string | null;
64
+ /** 이번에 refresh했는가(진단용). */
65
+ refreshed: boolean;
66
+ };
67
+ type ReoptWorkspaceLogin = {
68
+ /** Better Auth `plugins`에 넣는다. */
69
+ plugin: ReturnType<typeof genericOAuth>;
70
+ providerId: typeof REOPT_WORKSPACE_PROVIDER_ID;
71
+ /** 토큰 audience(플랫폼 origin) — 진단용. */
72
+ resource: string;
73
+ /** 요청한 scope(기본 + 추가). */
74
+ scopes: string[];
75
+ /**
76
+ * 로그인한 직원의 위임 access token(만료 임박이면 refresh). 로그인이 없거나 refresh가 끝났으면(재로그인 필요) `null`.
77
+ * `createConnectClient({ accessToken })`의 함수로 넘기면 호출마다 최신 값을 쓴다.
78
+ */
79
+ getAccessToken: (auth: ReoptWorkspaceAuthLike, headers: Headers) => Promise<string | null>;
80
+ /**
81
+ * 🔑 `proxy.ts`(쿠키를 쓸 수 있는 곳)에서 부른다 — 만료가 `withinSeconds`(기본 120초) 안이면 **미리** refresh하고 새 계정
82
+ * 쿠키를 돌려준다. 리옵트 id는 refresh token을 회전시키고 **이미 쓴 토큰이 다시 오면 그 사용자의 refresh token 전부를
83
+ * 폐기**한다. 서버 컴포넌트 렌더는 쿠키를 쓸 수 없으므로 거기서 refresh가 일어나면 새 토큰이 저장되지 않고, 다음 refresh가
84
+ * 쓴 토큰을 다시 보내 로그아웃된다 — 그래서 refresh는 프록시에서 끝내 두고 RSC는 유효한 토큰을 읽기만 하게 한다.
85
+ * 세션이 없거나 꺼낼 수 없으면 `null`(그대로 통과시키면 된다).
86
+ */
87
+ refreshInProxy: (auth: ReoptWorkspaceAuthLike, headers: Headers, options?: {
88
+ withinSeconds?: number;
89
+ now?: () => number;
90
+ }) => Promise<ReoptWorkspaceRefreshResult | null>;
91
+ };
92
+ /** Set-Cookie 목록을 Cookie 헤더에 반영한다(이름이 같으면 교체, 만료·Max-Age=0이면 삭제) — 순수 함수. */
93
+ declare function applySetCookiesToCookieHeader(cookieHeader: string | null, setCookies: readonly string[]): string | null;
94
+ declare function createReoptWorkspaceLogin(options?: ReoptWorkspaceLoginOptions): ReoptWorkspaceLogin;
95
+ //#endregion
96
+ export { REOPT_RECONSENT_PARAMS, REOPT_WORKSPACE_LOGIN_SCOPES, REOPT_WORKSPACE_PROVIDER_ID, ReoptWorkspaceAuthLike, ReoptWorkspaceLogin, ReoptWorkspaceLoginOptions, ReoptWorkspaceRefreshResult, applySetCookiesToCookieHeader, createReoptWorkspaceLogin, isReconsentRequired };
97
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,206 @@
1
+ import { resolvePlatformUrls } from "../urls.js";
2
+ import { o as readClientKeyRing } from "../keys-6gwtNd0g.js";
3
+ import { createPrivateKeyJwtClientAssertionGetter } from "@better-auth/core/oauth2";
4
+ import { genericOAuth } from "better-auth/plugins";
5
+
6
+ //#region src/better-auth/index.ts
7
+ /**
8
+ * `@reopt-ai/workspace-sdk/better-auth` — 워크스페이스 앱의 **관리자(직원) 로그인**(RFC-0043 §3.3).
9
+ *
10
+ * 워크스페이스 앱은 브랜드앱이 아니다 — 직원은 리옵트 계정으로 로그인하고, 그 로그인이 곧 위임이다. 설치의 `connect` 클라이언트
11
+ * 하나가 둘을 겸한다:
12
+ *
13
+ * - 첫 로그인의 동의 화면이 워크스페이스를 묻고 묶는다. 비멤버는 리옵트가 막고 매 요청 멤버십을 다시 본다 — 앱이 관리자 명단을
14
+ * 따로 들 필요가 없다(`ADMIN_EMAILS` 같은 것은 지운다). 무엇을 할 수 있는지는 `connect.me()`의 권한 키가 말한다.
15
+ * - 토큰 엔드포인트 인증은 `private_key_jwt`(앱의 개인키, 시크릿 없음) + PKCE. 받은 토큰은 플랫폼 API가 audience라
16
+ * (`resource` = 플랫폼 origin) 그대로 `createConnectClient`에 넣는다.
17
+ * - 앱은 DB가 없어도 된다 — Better Auth에 `database`를 주지 않으면 세션이 쿠키(stateless)이고 계정 토큰도 암호화 쿠키에
18
+ * 든다(`account.storeAccountCookie`). 만료된 access token은 `auth.api.getAccessToken`이 refresh token으로 갱신한다.
19
+ *
20
+ * 브랜드(브랜드앱) 리소스 — 그 브랜드의 고객 로그인·플랜·결제·약관 — 는 `@reopt-ai/brandapp-sdk`가 맡는다. 이 모듈은 직원 로그인만.
21
+ *
22
+ * ```ts
23
+ * import { betterAuth } from "better-auth";
24
+ * import { createReoptWorkspaceLogin } from "@reopt-ai/workspace-sdk/better-auth";
25
+ *
26
+ * const login = createReoptWorkspaceLogin(); // env: REOPT_CONNECT_CLIENT_ID, REOPT_CLIENT_PRIVATE_KEY_JWK, REOPT_PLATFORM_URL
27
+ * export const auth = betterAuth({ secret, baseURL, plugins: [login.plugin, nextCookies()] });
28
+ *
29
+ * // 서버(라우트·RSC·액션)에서 직원 본인의 토큰으로 리옵트 호출
30
+ * const connect = createConnectClient({ accessToken: () => login.getAccessToken(auth, await headers()) });
31
+ * ```
32
+ *
33
+ * 브라우저는 Better Auth 1.7의 `authClient.signIn.social({ provider: "reopt" })`로 시작하고, 콜백은
34
+ * `${baseURL}/api/auth/callback/reopt` — 리옵트 콘솔 연동 상세의 "주소"에 등록돼 있어야 한다(바꾸면 "주소 수정", client_id 유지).
35
+ */
36
+ /** Better Auth 제공자 id — `signIn.social({ provider })`와 콜백 경로(`/api/auth/callback/reopt`)의 마지막 조각. */
37
+ const REOPT_WORKSPACE_PROVIDER_ID = "reopt";
38
+ /**
39
+ * 기본 scope — 로그인(`openid profile email`) + refresh(`offline_access`) + 워크스페이스 읽기. 쓰기·도메인 scope는
40
+ * `scopes`로 더한다(설치의 connect 클라이언트에 허용된 것만 발급된다).
41
+ */
42
+ const REOPT_WORKSPACE_LOGIN_SCOPES = [
43
+ "openid",
44
+ "profile",
45
+ "email",
46
+ "offline_access",
47
+ "workspace:read"
48
+ ];
49
+ /**
50
+ * 동의 화면을 다시 연다 — `authClient.signIn.social({ provider: "reopt", additionalParams: REOPT_RECONSENT_PARAMS })`.
51
+ * 기존 동의가 있으면 리옵트는 동의 화면을 건너뛰므로(RFC-0043 Q1) 워크스페이스를 다시 고르게 하려면 이것이 필요하다.
52
+ */
53
+ const REOPT_RECONSENT_PARAMS = { prompt: "consent" };
54
+ /**
55
+ * 위임 호출이 "동의를 다시 받아야 함"으로 거절됐는가 — 직원의 동의가 이 앱이 설치되지 않은 워크스페이스에 묶여 있다
56
+ * (`/v1/connect/*` 403 `WORKSPACE_MISMATCH`). 그러면 `REOPT_RECONSENT_PARAMS`로 다시 로그인시킨다. `PlatformApiError`를
57
+ * import하지 않고 모양으로 본다 — 이 진입점이 zod를 끌어오지 않게.
58
+ */
59
+ function isReconsentRequired(error) {
60
+ return !!error && typeof error === "object" && error.code === "WORKSPACE_MISMATCH";
61
+ }
62
+ /** Set-Cookie 목록을 Cookie 헤더에 반영한다(이름이 같으면 교체, 만료·Max-Age=0이면 삭제) — 순수 함수. */
63
+ function applySetCookiesToCookieHeader(cookieHeader, setCookies) {
64
+ const jar = /* @__PURE__ */ new Map();
65
+ for (const part of (cookieHeader ?? "").split(";")) {
66
+ const index = part.indexOf("=");
67
+ if (index <= 0) continue;
68
+ jar.set(part.slice(0, index).trim(), part.slice(index + 1).trim());
69
+ }
70
+ for (const line of setCookies) {
71
+ const [pair = "", ...attributes] = line.split(";");
72
+ const index = pair.indexOf("=");
73
+ if (index <= 0) continue;
74
+ const name = pair.slice(0, index).trim();
75
+ const value = pair.slice(index + 1).trim();
76
+ if (attributes.some((attribute) => {
77
+ const [key = "", raw = ""] = attribute.split("=");
78
+ const k = key.trim().toLowerCase();
79
+ if (k === "max-age") return Number(raw.trim()) <= 0;
80
+ if (k === "expires") return Date.parse(raw.trim()) <= Date.now();
81
+ return false;
82
+ }) || value === "") jar.delete(name);
83
+ else jar.set(name, value);
84
+ }
85
+ if (jar.size === 0) return null;
86
+ return [...jar].map(([name, value]) => `${name}=${value}`).join("; ");
87
+ }
88
+ function errorCode(error) {
89
+ const body = error?.body;
90
+ if (typeof body?.code === "string") return body.code;
91
+ const status = error?.status;
92
+ return typeof status === "string" ? status : "UNKNOWN";
93
+ }
94
+ function setCookiesOf(headers) {
95
+ if (!headers || typeof headers.get !== "function") return [];
96
+ const h = headers;
97
+ if (typeof h.getSetCookie === "function") return h.getSetCookie();
98
+ const raw = h.get("set-cookie");
99
+ return raw ? [raw] : [];
100
+ }
101
+ function readEnv(name) {
102
+ if (typeof process === "undefined") return void 0;
103
+ const value = process.env?.[name]?.trim();
104
+ return value ? value : void 0;
105
+ }
106
+ function createReoptWorkspaceLogin(options = {}) {
107
+ if (typeof window !== "undefined" && typeof document !== "undefined") throw new Error("[@reopt-ai/workspace-sdk/better-auth] createReoptWorkspaceLogin() must run on the server — it signs with the app's private key.");
108
+ const clientId = options.clientId ?? readEnv("REOPT_CONNECT_CLIENT_ID");
109
+ if (!clientId) throw new Error("[@reopt-ai/workspace-sdk/better-auth] clientId is required — pass it or set REOPT_CONNECT_CLIENT_ID (the installation's connect client).");
110
+ const ring = options.keyRing ?? readClientKeyRing();
111
+ if (!ring) throw new Error("[@reopt-ai/workspace-sdk/better-auth] no client private key — pass keyRing or set REOPT_CLIENT_PRIVATE_KEY_JWK (generate with `npx -p @reopt-ai/workspace-sdk reopt-keygen`).");
112
+ const { platformUrl, idBaseUrl } = resolvePlatformUrls({
113
+ ...options.platformUrl ? { platformUrl: options.platformUrl } : {},
114
+ ...options.idBaseUrl ? { idBaseUrl: options.idBaseUrl } : {},
115
+ ...options.isProduction !== void 0 ? { isProduction: options.isProduction } : {}
116
+ });
117
+ const key = ring.signing;
118
+ const scopes = [.../* @__PURE__ */ new Set([...REOPT_WORKSPACE_LOGIN_SCOPES, ...options.scopes ?? []])];
119
+ const resourceParams = { resource: platformUrl };
120
+ const plugin = genericOAuth({ config: [{
121
+ providerId: REOPT_WORKSPACE_PROVIDER_ID,
122
+ discoveryUrl: `${idBaseUrl}/api/auth/.well-known/openid-configuration`,
123
+ authorizationUrl: `${idBaseUrl}/api/auth/oauth2/authorize`,
124
+ tokenUrl: `${idBaseUrl}/api/auth/oauth2/token`,
125
+ userInfoUrl: `${idBaseUrl}/api/auth/oauth2/userinfo`,
126
+ clientId,
127
+ tokenEndpointAuth: {
128
+ method: "private_key_jwt",
129
+ getClientAssertion: createPrivateKeyJwtClientAssertionGetter({
130
+ privateKeyJwk: key,
131
+ ...key.kid ? { kid: key.kid } : {},
132
+ ...key.alg ? { algorithm: key.alg } : {},
133
+ expiresIn: 120
134
+ })
135
+ },
136
+ scopes,
137
+ pkce: true,
138
+ authorizationUrlParams: resourceParams,
139
+ tokenUrlParams: resourceParams,
140
+ refreshTokenParams: resourceParams,
141
+ disableProviderLogout: !options.providerLogout,
142
+ ...typeof options.providerLogout === "object" && options.providerLogout.postLogoutRedirectURI ? { postLogoutRedirectURI: options.providerLogout.postLogoutRedirectURI } : {}
143
+ }] });
144
+ function reportTokenError(error) {
145
+ const code = errorCode(error);
146
+ if (options.onTokenError) options.onTokenError(code, error);
147
+ else console.warn(`[@reopt-ai/workspace-sdk/better-auth] staff token unavailable: ${code} — the staff member has to sign in again`);
148
+ }
149
+ return {
150
+ plugin,
151
+ providerId: REOPT_WORKSPACE_PROVIDER_ID,
152
+ resource: platformUrl,
153
+ scopes,
154
+ async getAccessToken(auth, headers) {
155
+ const call = auth.api.getAccessToken;
156
+ try {
157
+ return (await call({
158
+ body: { useAccountCookie: true },
159
+ headers
160
+ }))?.accessToken ?? null;
161
+ } catch (error) {
162
+ reportTokenError(error);
163
+ return null;
164
+ }
165
+ },
166
+ async refreshInProxy(auth, headers, proxyOptions = {}) {
167
+ const now = proxyOptions.now ?? (() => Date.now());
168
+ const withinMs = (proxyOptions.withinSeconds ?? 120) * 1e3;
169
+ const getCall = auth.api.getAccessToken;
170
+ const refreshCall = auth.api.refreshToken;
171
+ let setCookies = [];
172
+ let refreshed = false;
173
+ try {
174
+ const current = await getCall({
175
+ body: { useAccountCookie: true },
176
+ headers,
177
+ returnHeaders: true
178
+ });
179
+ setCookies = setCookiesOf(current.headers);
180
+ refreshed = setCookies.length > 0;
181
+ const expiresAt = current.response?.accessTokenExpiresAt;
182
+ const remaining = expiresAt == null ? Infinity : new Date(expiresAt).getTime() - now();
183
+ if (!refreshed && remaining < withinMs) {
184
+ setCookies = setCookiesOf((await refreshCall({
185
+ body: { useAccountCookie: true },
186
+ headers,
187
+ returnHeaders: true
188
+ })).headers);
189
+ refreshed = true;
190
+ }
191
+ } catch (error) {
192
+ if (errorCode(error) !== "UNAUTHORIZED") reportTokenError(error);
193
+ return null;
194
+ }
195
+ return {
196
+ setCookies,
197
+ cookieHeader: applySetCookiesToCookieHeader(headers.get("cookie"), setCookies),
198
+ refreshed
199
+ };
200
+ }
201
+ };
202
+ }
203
+
204
+ //#endregion
205
+ export { REOPT_RECONSENT_PARAMS, REOPT_WORKSPACE_LOGIN_SCOPES, REOPT_WORKSPACE_PROVIDER_ID, applySetCookiesToCookieHeader, createReoptWorkspaceLogin, isReconsentRequired };
206
+ //# sourceMappingURL=index.js.map
@@ -1,4 +1,5 @@
1
1
  import { i as ClientPrivateJwk, r as ClientKeyRing } from "./keys-B2pA8EkU.js";
2
+ import { n as PlatformUrls } from "./urls-DiYp_PHg.js";
2
3
  import { z } from "zod";
3
4
  //#region src/workspace/schemas.d.ts
4
5
  /**
@@ -155,6 +156,8 @@ type PlatformPublishedPostSummary = {
155
156
  publishedAt: string | null;
156
157
  metaTitle: string | null;
157
158
  metaDescription: string | null;
159
+ /** 분류 태그 이름(Studio 글 태그와 같은 것) — 가나다순. 옛 서버 응답에는 없어 빈 배열로 읽는다. */
160
+ tags: string[];
158
161
  coverImage: {
159
162
  id: string;
160
163
  url: string;
@@ -214,17 +217,26 @@ declare const platformMeSchema: z.ZodType<PlatformMe>;
214
217
  declare const platformPublishedPostSummarySchema: z.ZodType<PlatformPublishedPostSummary>;
215
218
  declare const platformPublishedPostSchema: z.ZodType<PlatformPublishedPost>;
216
219
  declare const platformPublishedPostPageSchema: z.ZodType<PlatformPublishedPostPage>;
217
- /** 목록 질의 — `groupId`로 게시물 그룹을 좁힌다. `limit` 1~100(기본 20) */
220
+ /** 목록 질의 — `groupId`로 게시물 그룹을, `tag`로 분류 태그를 좁힌다. `limit` 1~100(기본 20) */
218
221
  type PlatformPublishedPostListOptions = {
219
222
  groupId?: string;
223
+ tag?: string;
220
224
  limit?: number;
221
225
  offset?: number;
222
226
  };
223
227
  declare const platformPublishedPostListQuerySchema: z.ZodType<{
224
228
  groupId?: string;
229
+ tag?: string;
225
230
  limit: number;
226
231
  offset: number;
227
232
  }, unknown>;
233
+ /** 한 편 질의 — `groupId`를 주면 그 게시물 그룹의 글만 찾는다(다른 그룹의 같은 slug는 404). */
234
+ type PlatformPublishedPostGetOptions = {
235
+ groupId?: string;
236
+ };
237
+ declare const platformPublishedPostDetailQuerySchema: z.ZodType<{
238
+ groupId?: string;
239
+ }, unknown>;
228
240
  declare const platformWebhookSchema: z.ZodType<PlatformWebhook>;
229
241
  declare const platformErrorSchema: z.ZodType<PlatformErrorBody>;
230
242
  declare const platformWorkTaskStageChangedEventSchema: z.ZodType<PlatformWorkTaskStageChangedEvent>;
@@ -553,24 +565,6 @@ type PlatformResourcesV2 = PlatformResources & {
553
565
  declare const platformResourcesV2Schema: z.ZodType<PlatformResourcesV2>;
554
566
  //#endregion
555
567
  //#region src/workspace/client.d.ts
556
- /**
557
- * 플랫폼 API(RFC-0029) 클라이언트 — **서버 전용**.
558
- *
559
- * `client_credentials`로 `platform.reopt.ai` audience 토큰을 받아(캐시·만료 60초 전 재발급·401 시 1회
560
- * 재발급) `/v1/*`를 부른다. 브라우저에서 만들면 던진다 — clientSecret이 곧 워크스페이스 쓰기 권한이다.
561
- *
562
- * 기본 origin은 환경에서 파생하고(`isProduction` 또는 `REOPT_PLATFORM_URL`/`REOPT_ID_BASE_URL` env),
563
- * 자체서명 dev 인증서는 `fetch` 주입(undici Agent 등)으로 요청 단위로 푼다 — 프로세스 전역
564
- * `NODE_TLS_REJECT_UNAUTHORIZED`는 쓰지 않는다.
565
- */
566
- declare const REOPT_PLATFORM_URLS: {
567
- readonly production: "https://platform.reopt.ai";
568
- readonly development: "https://platform.local.reopt.io";
569
- };
570
- declare const REOPT_PLATFORM_ID_URLS: {
571
- readonly production: "https://id.reopt.ai";
572
- readonly development: "https://id.local.reopt.io";
573
- };
574
568
  declare const DEFAULT_PLATFORM_SCOPES: readonly ["works:read", "works:write"];
575
569
  type PlatformClientConfig = {
576
570
  clientId: string;
@@ -594,6 +588,11 @@ type PlatformClientConfig = {
594
588
  timeoutMs?: number;
595
589
  /** fetch 주입 — 테스트·자체서명 인증서(undici dispatcher) 용 */
596
590
  fetch?: typeof fetch;
591
+ /**
592
+ * 기계 토큰을 DPoP로 결속하는가(기본 true). 리옵트 플랫폼 API는 DPoP를 **요구**한다 — `false`는 `fetch`를 가짜 플랫폼에
593
+ * 꽂은 로컬 dev·테스트에서만 쓴다.
594
+ */
595
+ dpop?: boolean;
597
596
  /** 서버 로그 상관관계용 — 요청마다 `X-Request-Id`로 실린다(생략 시 UUID) */
598
597
  requestId?: () => string;
599
598
  };
@@ -622,11 +621,6 @@ declare class PlatformApiError extends Error {
622
621
  requestId?: string;
623
622
  });
624
623
  }
625
- type PlatformUrls = {
626
- platformUrl: string;
627
- idBaseUrl: string;
628
- };
629
- declare function resolvePlatformUrls(config: Pick<PlatformClientConfig, "platformUrl" | "idBaseUrl" | "isProduction">): PlatformUrls;
630
624
  type PlatformClient = {
631
625
  /** 진단 — 이 자격이 어느 워크스페이스·source에 묶였는가 */
632
626
  me: () => Promise<PlatformMe>;
@@ -653,7 +647,7 @@ type PlatformClient = {
653
647
  */
654
648
  posts: {
655
649
  list: (options?: PlatformPublishedPostListOptions) => Promise<PlatformPublishedPostPage>;
656
- get: (slug: string) => Promise<PlatformPublishedPost>;
650
+ get: (slug: string, options?: PlatformPublishedPostGetOptions) => Promise<PlatformPublishedPost>;
657
651
  };
658
652
  /** RFC-0030 — plan이 한 왕복으로 읽는 워크스페이스 자원 전부(파이프라인·웹훅·브랜드·브랜드앱·OAuth·EAV). scope `workspace:admin` */
659
653
  resources: {
@@ -710,5 +704,5 @@ type PlatformClient = {
710
704
  };
711
705
  declare function createPlatformClient(config: PlatformClientConfig): PlatformClient;
712
706
  //#endregion
713
- export { PlatformPublishedPostPage as $, platformWebhookUpsertInputSchema as $t, PlatformDomainStatus as A, platformLockReleasedSchema as At, PlatformManagedBy as B, platformPublishedPostListQuerySchema as Bt, PLATFORM_WEBHOOK_TRIGGERS as C, platformEavEntityResourceSchema as Ct, PlatformBrandappResource as D, platformErrorSchema as Dt, PlatformBrandUpsertInput as E, platformEavSchemaOperationSchema as Et, PlatformEavSchemaApplyResult as F, platformPipelineImportInputSchema as Ft, PlatformOAuthClientUpsertInput as G, platformResourcesSchema as Gt, PlatformOAuthClientImportInput as H, platformPublishedPostSchema as Ht, PlatformEavSchemaOperation as I, platformPipelineResourceSchema as It, PlatformPipelineResource as J, platformTaskStageInputSchema as Jt, PlatformPipeline as K, platformResourcesV2Schema as Kt, PlatformErrorBody as L, platformPipelineSchema as Lt, PlatformEavDataType as M, platformOAuthClientImportInputSchema as Mt, PlatformEavEntityResource as N, platformOAuthClientResourceSchema as Nt, PlatformBrandappUpsertInput as O, platformExternalIdSchema as Ot, PlatformEavSchemaApplyInput as P, platformOAuthClientUpsertInputSchema as Pt, PlatformPublishedPostListOptions as Q, platformWebhookSchema as Qt, PlatformLockAcquired as R, platformPipelineStageInputSchema as Rt, PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS as S, platformEavBrandappResourcesSchema as St, PlatformBrandResource as T, platformEavSchemaApplyResultSchema as Tt, PlatformOAuthClientPurpose as U, platformPublishedPostSummarySchema as Ut, PlatformMe as V, platformPublishedPostPageSchema as Vt, PlatformOAuthClientResource as W, platformResourceKeySchema as Wt, PlatformPipelineUpsertInput as X, platformTaskUpsertInputSchema as Xt, PlatformPipelineStageInput as Y, platformTaskStageSchema as Yt, PlatformPublishedPost as Z, platformWebhookResourceSchema as Zt, PLATFORM_OAUTH_CLIENT_PURPOSES as _, platformBrandResourceSchema as _t, PlatformUrls as a, PlatformTaskOutcome as at, PLATFORM_TASK_OUTCOMES as b, platformBrandappUpsertInputSchema as bt, REOPT_PLATFORM_URLS as c, PlatformTaskStageInput as ct, PLATFORM_ADMIN_SCOPE as d, PlatformWebhookResource as dt, platformWorkTaskStageChangedEventSchema as en, PlatformPublishedPostSummary as et, PLATFORM_BRANDAPP_STATUSES as f, PlatformWebhookTrigger as ft, PLATFORM_OAUTH_APPLICATION_TYPES as g, platformBrandImportInputSchema as gt, PLATFORM_MANAGED_BY_VALUES as h, PlatformWriteMeta as ht, PlatformClientConfig as i, PlatformTask as it, PlatformEavBrandappResources as j, platformMeSchema as jt, PlatformCustomerUpsertInput as k, platformLockAcquiredSchema as kt, createPlatformClient as l, PlatformTaskUpsertInput as lt, PLATFORM_EAV_DATA_TYPES as m, PlatformWorkTaskStageChangedEvent as mt, PlatformApiError as n, PlatformResourcesV2 as nt, PlatformWriteResult as o, PlatformTaskPriority as ot, PLATFORM_DOMAIN_STATUSES as p, PlatformWebhookUpsertInput as pt, PlatformPipelineImportInput as q, platformTaskSchema as qt, PlatformClient as r, PlatformStageColor as rt, REOPT_PLATFORM_ID_URLS as s, PlatformTaskStage as st, DEFAULT_PLATFORM_SCOPES as t, platformWriteMetaSchema as tn, PlatformResources as tt, resolvePlatformUrls as u, PlatformWebhook as ut, PLATFORM_OAUTH_GRANT_TYPES as v, platformBrandUpsertInputSchema as vt, PlatformBrandImportInput as w, platformEavSchemaApplyInputSchema as wt, PLATFORM_TASK_PRIORITIES as x, platformCustomerUpsertInputSchema as xt, PLATFORM_STAGE_COLORS as y, platformBrandappResourceSchema as yt, PlatformLockReleased as z, platformPipelineUpsertInputSchema as zt };
714
- //# sourceMappingURL=client-CwInApBf.d.ts.map
707
+ export { PlatformResourcesV2 as $, platformWriteMetaSchema as $t, PlatformEavSchemaApplyInput as A, platformOAuthClientResourceSchema as At, PlatformOAuthClientResource as B, platformPublishedPostSchema as Bt, PlatformBrandappResource as C, platformEavSchemaOperationSchema as Ct, PlatformEavBrandappResources as D, platformLockReleasedSchema as Dt, PlatformDomainStatus as E, platformLockAcquiredSchema as Et, PlatformLockReleased as F, platformPipelineStageInputSchema as Ft, PlatformPipelineStageInput as G, platformTaskSchema as Gt, PlatformPipeline as H, platformResourceKeySchema as Ht, PlatformManagedBy as I, platformPipelineUpsertInputSchema as It, PlatformPublishedPostGetOptions as J, platformTaskUpsertInputSchema as Jt, PlatformPipelineUpsertInput as K, platformTaskStageInputSchema as Kt, PlatformMe as L, platformPublishedPostDetailQuerySchema as Lt, PlatformEavSchemaOperation as M, platformPipelineImportInputSchema as Mt, PlatformErrorBody as N, platformPipelineResourceSchema as Nt, PlatformEavDataType as O, platformMeSchema as Ot, PlatformLockAcquired as P, platformPipelineSchema as Pt, PlatformResources as Q, platformWorkTaskStageChangedEventSchema as Qt, PlatformOAuthClientImportInput as R, platformPublishedPostListQuerySchema as Rt, PlatformBrandUpsertInput as S, platformEavSchemaApplyResultSchema as St, PlatformCustomerUpsertInput as T, platformExternalIdSchema as Tt, PlatformPipelineImportInput as U, platformResourcesSchema as Ut, PlatformOAuthClientUpsertInput as V, platformPublishedPostSummarySchema as Vt, PlatformPipelineResource as W, platformResourcesV2Schema as Wt, PlatformPublishedPostPage as X, platformWebhookSchema as Xt, PlatformPublishedPostListOptions as Y, platformWebhookResourceSchema as Yt, PlatformPublishedPostSummary as Z, platformWebhookUpsertInputSchema as Zt, PLATFORM_TASK_PRIORITIES as _, platformBrandappUpsertInputSchema as _t, PlatformWriteResult as a, PlatformTaskStageInput as at, PlatformBrandImportInput as b, platformEavEntityResourceSchema as bt, PLATFORM_BRANDAPP_STATUSES as c, PlatformWebhookResource as ct, PLATFORM_MANAGED_BY_VALUES as d, PlatformWorkTaskStageChangedEvent as dt, PlatformStageColor as et, PLATFORM_OAUTH_APPLICATION_TYPES as f, PlatformWriteMeta as ft, PLATFORM_TASK_OUTCOMES as g, platformBrandappResourceSchema as gt, PLATFORM_STAGE_COLORS as h, platformBrandUpsertInputSchema as ht, PlatformClientConfig as i, PlatformTaskStage as it, PlatformEavSchemaApplyResult as j, platformOAuthClientUpsertInputSchema as jt, PlatformEavEntityResource as k, platformOAuthClientImportInputSchema as kt, PLATFORM_DOMAIN_STATUSES as l, PlatformWebhookTrigger as lt, PLATFORM_OAUTH_GRANT_TYPES as m, platformBrandResourceSchema as mt, PlatformApiError as n, PlatformTaskOutcome as nt, createPlatformClient as o, PlatformTaskUpsertInput as ot, PLATFORM_OAUTH_CLIENT_PURPOSES as p, platformBrandImportInputSchema as pt, PlatformPublishedPost as q, platformTaskStageSchema as qt, PlatformClient as r, PlatformTaskPriority as rt, PLATFORM_ADMIN_SCOPE as s, PlatformWebhook as st, DEFAULT_PLATFORM_SCOPES as t, PlatformTask as tt, PLATFORM_EAV_DATA_TYPES as u, PlatformWebhookUpsertInput as ut, PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS as v, platformCustomerUpsertInputSchema as vt, PlatformBrandappUpsertInput as w, platformErrorSchema as wt, PlatformBrandResource as x, platformEavSchemaApplyInputSchema as xt, PLATFORM_WEBHOOK_TRIGGERS as y, platformEavBrandappResourcesSchema as yt, PlatformOAuthClientPurpose as z, platformPublishedPostPageSchema as zt };
708
+ //# sourceMappingURL=client-B8AzOiLZ.d.ts.map