@reopt-ai/workspace-sdk 0.1.0-rc.1 → 0.1.0-rc.11
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 +194 -0
- package/README.md +21 -7
- package/dist/better-auth/index.d.ts +97 -0
- package/dist/better-auth/index.js +235 -0
- package/dist/{client-CwInApBf.d.ts → client-ByIjKnf3.d.ts} +24 -49
- package/dist/client-WEomQekp.js +275 -0
- package/dist/connect-BBf9QfQB.d.ts +803 -0
- package/dist/connect.d.ts +5 -0
- package/dist/connect.js +5 -0
- package/dist/errors-C5_fhcqb.js +123 -0
- package/dist/errors-DLJlABJL.d.ts +76 -0
- package/dist/index.d.ts +7 -400
- package/dist/index.js +7 -341
- package/dist/installation/index.d.ts +13 -7
- package/dist/installation/index.js +13 -3
- package/dist/operator/index.d.ts +87 -0
- package/dist/operator/index.js +158 -0
- package/dist/page-79Ab4UGQ.d.ts +47 -0
- package/dist/page-SjWh1rqY.js +606 -0
- package/dist/permissions-COCbNJeQ.d.ts +64 -0
- package/dist/permissions.d.ts +2 -0
- package/dist/permissions.js +430 -0
- package/dist/resource/index.d.ts +24 -1
- package/dist/resource/index.js +76 -29
- package/dist/{client-Bm8YrIx2.js → schemas-eWh_FUfh.js} +6 -315
- package/dist/social/index.d.ts +3 -1
- package/dist/social/index.js +3 -1
- package/dist/testing/index.d.ts +207 -0
- package/dist/testing/index.js +2122 -0
- package/dist/transport-CN64IoHx.js +192 -0
- package/dist/urls-DiYp_PHg.d.ts +47 -0
- package/dist/urls.d.ts +2 -26
- package/dist/urls.js +20 -1
- package/dist/webhooks.d.ts +145 -0
- package/dist/webhooks.js +199 -0
- package/docs/operator.md +55 -0
- package/docs/resource.md +9 -0
- package/docs/testing.md +167 -0
- package/docs/workspace.md +407 -43
- package/package.json +31 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,200 @@ This project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.1.0-rc.11] — 2026-11-22
|
|
11
|
+
|
|
12
|
+
Pre-release (`npm i @reopt-ai/workspace-sdk@next`). 깨지는 변경 없음.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- **고객(CRM)** — `reopt.customers`: `list`(검색·태그·기록 종류·여정·브랜드·기간, `total` 포함)·`get`·`create`·`update`·
|
|
17
|
+
`updateTags`·`listTags`·`listFields`·`listNotes`·`addNote`·`updateNote`·`deleteNote`·`timeline`. 코어는 Studio·CLI와 같은
|
|
18
|
+
함수다(연락처 정규화·충돌 판정·커스텀 필드 검증).
|
|
19
|
+
- 명부는 연락처라 읽기는 `customer:read` scope, 쓰기는 `workspace:write`에 **더해** `customer:read`가 필요하다
|
|
20
|
+
(`CONNECT_OPERATIONS[…].alsoScopes`, `canCall`이 함께 본다). 리옵트는 명부 읽기를 감사에 남긴다.
|
|
21
|
+
- 연락처가 다른 고객과 겹치면 409 **`CONTACT_TAKEN`**(새 코드) — `error.fieldMap()`이 `email`·`phoneNumber`를 짚는다.
|
|
22
|
+
`create({ onConflict: "link" })`는 그 고객에 덧붙이고 그 고객을 돌려준다.
|
|
23
|
+
- **`NOT_IMPLEMENTED`(501)·`isNotImplemented(error)`** — 서버에 그 라우트가 없다(서버가 SDK보다 오래됐다). 화면에서 그 기능을
|
|
24
|
+
"아직 쓸 수 없음"으로 보이게 한다. 🔴 예전 서버는 위임 표면에 없는 경로에 **401**("machine tokens only")로 답했다 — 새 SDK를
|
|
25
|
+
먼저 올린 앱이 그것을 "다시 로그인"으로 읽어 로그인 루프에 빠진다. 이 버전의 클라이언트는 그 401도 `NOT_IMPLEMENTED`로
|
|
26
|
+
맞춰 던진다(서버도 501로 고쳤다).
|
|
27
|
+
- `Page.total` — 서버가 세는 목록(`customers.list`)에 전체 건수가 실린다.
|
|
28
|
+
- `/testing` — 고객(`seed.customers`·`customerFields`)과 위 규칙, `seed.pipelines[].stages[].isEntry`(시작 단계 지정),
|
|
29
|
+
폼 선택지 `{ value, label }`, `machine.clientName`. `requests`는 최근 1,000건만 남긴다.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
|
|
33
|
+
- **id 모양이 아닌 값은 404 `NOT_FOUND`다**(예전엔 400 `VALIDATION_ERROR`) — `getTask("아무거나")`가 "그런 것이 없다"로
|
|
34
|
+
답해 잘못된 주소가 404 화면으로 간다. 위임 표면의 id 자리 전부.
|
|
35
|
+
|
|
36
|
+
### Fixed
|
|
37
|
+
|
|
38
|
+
- `/testing` — 글 주소를 영문 소문자·숫자·하이픈만 받던 것(실제 서버는 1~64자면 한글도 받는다), id 모양이 아닌 경로가 501이던
|
|
39
|
+
것(404). 둘 다 계약 시나리오에 넣어 실제 서버와 대조한다(bootstrap 보고).
|
|
40
|
+
|
|
41
|
+
## [0.1.0-rc.10] — 2026-11-22
|
|
42
|
+
|
|
43
|
+
Pre-release (`npm i @reopt-ai/workspace-sdk@next`). 위임 클라이언트(`createConnectClient`)의 계약을 한 번에 정리했다 — **깨지는 변경이 있다**. 옮기는 표는
|
|
44
|
+
[docs/workspace.md](./docs/workspace.md#migrating-from-010-rc9). 서버 응답은 덧붙이는 방식으로만 바뀌어 rc.9 이하는 새 서버에서
|
|
45
|
+
그대로 동작한다.
|
|
46
|
+
|
|
47
|
+
### Changed (breaking)
|
|
48
|
+
|
|
49
|
+
- **목록은 전부 `Page<T>`** — `{ items, nextOffset }`. `members`·`works.listPipelines`·`works.listTasks`·`posts.listGroups`·
|
|
50
|
+
`posts.list`·`folders.list`·`files.list`·`forms.list`·`inquiries.list`·`eav.listEntities`가 배열 대신 이 모양을 돌려주고,
|
|
51
|
+
`eav.listRecords`(`records` → `items`)·기계 `platform.posts.list`(`posts` → `items`)도 같다. `limit`·`offset`·`sort`
|
|
52
|
+
(`"-updatedAt"`)를 받는다. `works.listTasks`는 이제 한 장(기본 200)이다 — 전부는 `listAll(reopt.works.listTasks, query)`.
|
|
53
|
+
- **쓰기는 고친 뒤의 객체 전체를 돌려준다** — `works.createTask/updateTask/moveTask` → `ConnectTask`, `posts.create/update/
|
|
54
|
+
publish/unpublish` → `ConnectPost`, `folders.create` → `ConnectFolder`. 삭제 응답은 모두 `{ id }`.
|
|
55
|
+
- **던지는 것은 언제나 `PlatformApiError`** — 타임아웃(`TIMEOUT`)·연결 실패(`NETWORK_ERROR`)·JSON 아닌 성공 응답과 약속과 다른
|
|
56
|
+
모양(`INVALID_RESPONSE`)을 포함한다. 예전엔 `DOMException`·`SyntaxError`·`ZodError`가 그대로 나갔다.
|
|
57
|
+
- 타입을 조였다: `ConnectPost.contentRich: ConnectPostSpec | null`, `status`·`visibility`·폼 `status`는 유니온,
|
|
58
|
+
`coverImage.url: string | null`(주소 없는 커버 하나가 `posts.list` 전체를 깨던 결함), `ConnectFolder.fileCount/childCount:
|
|
59
|
+
number | null`(수를 싣지 않는 응답은 0이 아니라 null).
|
|
60
|
+
- 서버 코드가 바뀐 곳: 본문·레코드 버전 충돌 `CONFLICT` → `VERSION_CONFLICT`, 레코드·용량 한도 → `QUOTA_EXCEEDED`, 플랜 거절
|
|
61
|
+
`FORBIDDEN` → `TIER_REQUIRED`, 업로드 초과·타입 400 → 413 `PAYLOAD_TOO_LARGE`·415 `UNSUPPORTED_MEDIA_TYPE`. 상태 코드 409·403은
|
|
62
|
+
그대로다.
|
|
63
|
+
- 업로드는 정확한 타입의 허용 목록이다 — `text/*`는 `plain`·`csv`·`markdown`만. 타입 없는 Blob은 415.
|
|
64
|
+
- `engines.node`는 `>=20`.
|
|
65
|
+
|
|
66
|
+
### Security
|
|
67
|
+
|
|
68
|
+
- **검증기(`/resource`)가 키에 묶인 위임 토큰의 DPoP 증명을 본다.** `allowUserTokens`를 켠 검증기에서 위임 토큰(`sub ≠ client_id`)이
|
|
69
|
+
DPoP 판정을 건너뛰어, `cnf.jkt`가 있는 토큰을 훔치면 증명 없이 Bearer로 쓸 수 있었다. 이제 증명(htm·htu·ath·jti)을 멤버십 콜백
|
|
70
|
+
앞에서 검증한다. 바인딩 없는 위임 토큰은 그대로 받고, `allowUserTokens.requireDpop: true`면 거절한다.
|
|
71
|
+
- **`dpop.replayStore`를 생략해도 재생 검사가 돈다**(메모리 저장소 + 경고 한 번, `onWarning`). 예전엔 생략하면 검사가 통째로
|
|
72
|
+
빠졌다. 인스턴스가 여럿이면 `createRedisDpopReplayStore`를 준다.
|
|
73
|
+
- **`refreshInProxy`가 같은 쿠키의 동시 요청을 한 번만 refresh한다**(끝난 결과도 10초 공유). 페이지 하나가 한꺼번에 보내는
|
|
74
|
+
요청들이 같은 refresh token을 각자 쓰면 리옵트가 재사용으로 보고 그 직원의 refresh token을 전부 폐기한다.
|
|
75
|
+
|
|
76
|
+
### Added
|
|
77
|
+
|
|
78
|
+
- `@reopt-ai/workspace-sdk/testing` — **메모리 안의 리옵트**(`createDevPlatform({ seed, key })`). 개발 모드·E2E에서 진짜 SDK
|
|
79
|
+
클라이언트를 그대로 쓰고 `fetch`만 바꾼다. 위임 표면 전부 + 기계 토큰·`/v1/me`·`/v1/posts` + 브라우저가 직접 여는 경로
|
|
80
|
+
(`handler` — 서명 주소·공개 파일·공개 폼 제출)를 답하고, 계약 규칙(창·정렬·전체 객체·`VERSION_CONFLICT`·`SLUG_TAKEN`·
|
|
81
|
+
`fields`·413/415·`QUOTA_EXCEEDED`·시스템 폴더)을 따른다. 시드는 key로 서로를 가리키고, `me.permissions`를 좁히면
|
|
82
|
+
`CONNECT_OPERATIONS`대로 403을 낸다. `reset()`·`requests`·`latencyMs`·`fail`·고정 시계. 같은 시나리오 코드가 이
|
|
83
|
+
에뮬레이터와 리옵트의 실제 라우터(실 DB)에 함께 돈다. 인증은 흉내 내지 않으며 프로덕션에서는 만들어지지 않는다.
|
|
84
|
+
문서 `docs/testing.md`.
|
|
85
|
+
- `@reopt-ai/workspace-sdk/webhooks`(의존 없음) — `createWebhookHandler`(Fetch 표준 핸들러: 서명·시각 검증, 종류별 핸들러,
|
|
86
|
+
`seen` 저장소로 중복 전달 거르기)·`readWebhook`·`verifyWebhookSignature`·`createMemoryWebhookSeenStore`, 타입
|
|
87
|
+
`WebhookEvent`·`WorkTaskStageChangedData`. 예전엔 워크스페이스 앱이 웹훅 서명을 검증하려면 brandapp-sdk를 설치해야 했다.
|
|
88
|
+
`secret`에 배열을 주면 비밀을 바꾸는 동안 옛 값과 새 값을 함께 받는다.
|
|
89
|
+
- `works.getTask(id)`·`inquiries.get(submissionId)`(운영 보드 카드 `task` 포함)·`brands()`(서버에는 있었지만 SDK에 없었다).
|
|
90
|
+
- 업무의 낙관적 동시성 — `ConnectTask.version`과 수정·이동의 `ifVersion`(409 `VERSION_CONFLICT`). 옆 카드의 순서 변경은 버전을
|
|
91
|
+
바꾸지 않는다.
|
|
92
|
+
- `works.deleteTasks(ids)` — 100건까지, 이미 없는 id는 `notFound`.
|
|
93
|
+
- `inquiries.moveStage`가 옮긴 뒤의 문의 전체(카드 `task` 포함)를 돌려준다 — 이동이 올린 `task.version`으로 다시 읽지 않고 메모를
|
|
94
|
+
고친다. 이동 결과 필드(`fromStageLabel`·`toStageLabel`·`journeySynced`)는 그대로다.
|
|
95
|
+
- `folders.list`가 `limit`·`offset`을 받는다(`listAll(reopt.folders.list, { parentId })`). 안 주면 예전처럼 전부.
|
|
96
|
+
- `files.signedUrls`는 건수 제한 없이 받는다 — SDK가 100건씩 나눠 보내고 합친다. 이미 공개인 파일(정적 커버 등)은 서명 주소
|
|
97
|
+
대신 그 공개 주소가 온다.
|
|
98
|
+
- `updateTask`·`moveTask`의 `ifVersion`은 `null`도 받는다(`task.version`을 그대로 넘긴다).
|
|
99
|
+
- `works.listTasks`: `ids`·`sort`(`sortOrder`·`updatedAt`·`createdAt`·`dueDate`·`priority`). `ConnectTask`에 `brand`·`goal`·
|
|
100
|
+
`stage.color`·`externalRefs`(서버가 보내던 것을 타입에 올렸다).
|
|
101
|
+
- 글: `posts.listTags()`, `posts.checkSlug(slug, { exceptId })`, 주소 중복 409 `SLUG_TAKEN`(예전엔 500), `author`
|
|
102
|
+
(`{ userId, name, image }`), `createdAt`, 목록의 `tag`·`q`·`sort`.
|
|
103
|
+
- 파일: `files.list`의 `folderId: "all"`(읽을 수 있는 폴더 전부)·`contentType`·`q`·`sort`, `files.usage()`,
|
|
104
|
+
`files.signedUrl(id)`·`files.signedUrls(ids)`(브라우저에 직접 넣는 짧은 수명의 읽기 주소 — 이미지·다운로드).
|
|
105
|
+
- `inquiries.list`의 `offset`, `inquiries.moveStage` 응답의 `journeySynced`.
|
|
106
|
+
- 에러 도우미 — `PLATFORM_ERROR_CODES`·`PlatformErrorCode`(유니온), `isPlatformError(error, ...codes)`·`isPlatformApiError`
|
|
107
|
+
(패키지가 두 벌이어도 성립)·`isSignInRequired`·`isPermissionDenied`, `error.fieldMap()`·`error.retryAfterMs`.
|
|
108
|
+
- 목록 도우미 — `listAll`·`iterate`, 타입 `Page`·`PageQuery`·`SortOf`.
|
|
109
|
+
- `@reopt-ai/workspace-sdk/permissions`(의존 없음 — 클라이언트 컴포넌트에서도 쓴다): `WORKSPACE_PERMISSION_KEYS`·
|
|
110
|
+
`WorkspacePermissionKey`, `can`·`canAll`·`canAny`, `canCall(me, "posts.publish")`, 메서드별 권한·scope 표
|
|
111
|
+
`CONNECT_OPERATIONS`. `ConnectMe.permissions`가 이 키의 배열이다.
|
|
112
|
+
- `@reopt-ai/workspace-sdk/connect` — 위임 클라이언트만(zod만 필요하다. 패키지 루트는 기계 자격 클라이언트 때문에
|
|
113
|
+
`@better-auth/core`가 필요하다).
|
|
114
|
+
- 모든 메서드의 마지막 인자 `{ signal }` — 호출별 취소. 취소는 `PlatformApiError`가 아니라 취소 이유 그대로 던진다.
|
|
115
|
+
- 401이면 `accessToken` 함수를 한 번 더 불러 다시 보낸다. `accessToken`은 `null`을 돌려줄 수 있다(요청을 보내지 않고 401
|
|
116
|
+
`UNAUTHORIZED`).
|
|
117
|
+
|
|
118
|
+
### Fixed
|
|
119
|
+
|
|
120
|
+
- `files.content`가 큰 파일을 받는 도중 10초에서 끊기던 것 — 제한 시간은 응답 헤더까지만 잰다.
|
|
121
|
+
- 문서: `works.upsertTask`·`setTaskStage` 예시가 실제 입력(`version` 필수·`pipelineId`·`stage: { outcome | stageId }`)과
|
|
122
|
+
달랐다. `platformTaskUpsertInputSchema.url`은 http(s)만 받는다.
|
|
123
|
+
|
|
124
|
+
## [0.1.0-rc.9] — 2026-11-21
|
|
125
|
+
|
|
126
|
+
Pre-release (`npm i @reopt-ai/workspace-sdk@next`) — npm에는 rc.1 다음 이 버전이 처음이다. rc.2~rc.8은 로컬 tarball로만
|
|
127
|
+
전달했고, 아래 그 절들의 변경이 모두 이 버전에 실린다.
|
|
128
|
+
|
|
129
|
+
### Added
|
|
130
|
+
|
|
131
|
+
- `/operator` — 리옵트 운영자 가드(RFC-0034 §5.2: `requireOperator`·`evaluateOperator`·`decodeIdTokenClaims`·
|
|
132
|
+
`latestReoptAccount`·`stepUpAuthorizationParams`, 제공자 id·step-up 상한 상수). `@reopt-ai/brandapp-sdk/superadmin`에서
|
|
133
|
+
옮겨 왔다 — 관리자 표면은 이 패키지가 갖는다. 문서 `docs/operator.md`.
|
|
134
|
+
|
|
135
|
+
## [0.1.0-rc.8] — 2026-11-21 (tarball only — published in rc.9)
|
|
136
|
+
|
|
137
|
+
### Added
|
|
138
|
+
|
|
139
|
+
- `ConnectFolder.fileCount`·`childCount` — `connect.folders.list()`가 폴더 카드의 파일·하위 폴더 수를 함께 준다(Studio 파일 관리자와
|
|
140
|
+
같은 기준, 서버가 묶어서 셈 — 폴더마다 2번 부르던 것을 없앤다, bootstrap 보고).
|
|
141
|
+
|
|
142
|
+
## [0.1.0-rc.7] — 2026-11-21 (tarball only — published in rc.9)
|
|
143
|
+
|
|
144
|
+
### Added
|
|
145
|
+
|
|
146
|
+
- `REOPT_RECONSENT_PARAMS`(`{ prompt: "consent" }`)·`isReconsentRequired(error)` — 직원의 옛 동의가 설치되지 않은 워크스페이스에
|
|
147
|
+
묶여 `/v1/connect/*`가 **403 `WORKSPACE_MISMATCH`**(새 코드)로 거절하면 동의 화면을 강제로 다시 열어 한 번에 다시 묶는다
|
|
148
|
+
(bootstrap 제안). `authClient.signIn.social({ provider: "reopt", additionalParams: REOPT_RECONSENT_PARAMS })`.
|
|
149
|
+
|
|
150
|
+
### Changed
|
|
151
|
+
|
|
152
|
+
- 문서 "Credentials" — 워크스페이스 앱(설치) 클라이언트는 `private_key_jwt`뿐이다. 시크릿 예시를 옛 시드 클라이언트용으로 내렸다.
|
|
153
|
+
|
|
154
|
+
## [0.1.0-rc.6] — 2026-11-21 (tarball only — published in rc.9)
|
|
155
|
+
|
|
156
|
+
### Fixed
|
|
157
|
+
|
|
158
|
+
- `installation.health(id)`가 서버의 봉투(`{ id, status, health }`)를 그대로 돌려줘 `keys`·`jwks`가 한 단계 안에 묻혀 있었다
|
|
159
|
+
(bootstrap 보고) — 이제 `InstallationHealthView`를 돌려준다. `connection.health()`·`registerKeys()`도 같이 바로잡힌다.
|
|
160
|
+
- `installation.reinstall()`이 약속한 `pendingManifest`가 실제로는 오지 않았다(서버는 `pendingManifestHash`) — 파생해 돌려준다.
|
|
161
|
+
타입 `InstallationReinstallResult`(`pendingManifest: boolean`·`pendingManifestHash`·`consoleUrl`).
|
|
162
|
+
- 두 결함 모두 단위 테스트의 가짜 서버가 SDK가 기대하는 모양을 직접 만들어 통과했다 — 가짜 응답을 실제 라우트 모양으로 바꿨고,
|
|
163
|
+
`health`는 실제 라우터를 SDK로 부르는 이음새(`rfc0043-installation-client-keys`)가 지킨다.
|
|
164
|
+
|
|
165
|
+
## [0.1.0-rc.5] — 2026-11-21 (tarball only — published in rc.9)
|
|
166
|
+
|
|
167
|
+
### Added
|
|
168
|
+
|
|
169
|
+
- `ConnectForm.intakePipelineId` — 제출이 카드로 쌓이는 운영 보드(Works 파이프라인). 제출이 없어도 `works.listPipelines()`에서
|
|
170
|
+
그 보드의 단계(=`inquiries.moveStage` 대상)를 그릴 수 있다(bootstrap 제안). 연결되지 않은 폼·옛 서버는 null.
|
|
171
|
+
|
|
172
|
+
## [0.1.0-rc.4] — 2026-11-20 (tarball only — published in rc.9)
|
|
173
|
+
|
|
174
|
+
### Added
|
|
175
|
+
|
|
176
|
+
- `connect.files.get(id)`, `files.update`이 갱신된 `ConnectFile`을 돌려준다(`fileId` 호환 유지), `files.list({ limit, offset })`(최대 500).
|
|
177
|
+
- `ConnectFile.blobUrl` — 게시물 본문에 넣는 정본 주소(Studio 에디터와 같은 `/api/blob/…`). 발행하거나 발행된 글의 본문을 고치면
|
|
178
|
+
리옵트가 본문이 참조하는 파일을 공개로 바꾼다 — 공개 사이트 본문 이미지(bootstrap 보고).
|
|
179
|
+
|
|
180
|
+
### Added
|
|
181
|
+
|
|
182
|
+
- **`/better-auth` — 관리자(직원) 로그인 프리셋** `createReoptWorkspaceLogin()`(RFC-0043): 설치의 connect 클라이언트로
|
|
183
|
+
authorization code + PKCE + `private_key_jwt`(시크릿 없음), `resource`=플랫폼 origin을 인가·교환·refresh 모두에.
|
|
184
|
+
`database` 없이 stateless 세션. `login.getAccessToken(auth, headers)` → `createConnectClient({ accessToken })`. optional peer
|
|
185
|
+
`better-auth >=1.7.18`.
|
|
186
|
+
- 게시물 분류·SEO: 읽기(connect·platform)에 `tags`·`metaTitle`·`metaDescription`, 쓰기(`posts.create/update`)에 `tags`(통째 교체,
|
|
187
|
+
없는 이름은 생성)·`metaTitle`·`metaDescription`·`coverImageId`(create에도). 대표 이미지는 이미지여야 하고 지정하면 공개가 된다.
|
|
188
|
+
- `platform.posts.list({ tag })`, `platform.posts.get(slug, { groupId })` — 다른 게시판의 같은 slug는 404.
|
|
189
|
+
- `connect.folders.update(id, { name, parentId })`·`connect.folders.delete(id)`(비어 있지 않으면 409, 시스템 폴더 403).
|
|
190
|
+
- `createPlatformClient({ dpop: false })` — fetch를 가짜 플랫폼에 꽂은 로컬 dev·테스트용(실서버는 DPoP를 요구한다).
|
|
191
|
+
|
|
192
|
+
- `login.refreshInProxy(auth, headers)` — `proxy.ts`에서 만료 전(기본 120초) refresh하고 새 계정 쿠키(`setCookies`)와 같은 요청의
|
|
193
|
+
뒤쪽이 읽을 `cookieHeader`를 준다. 서버 컴포넌트는 쿠키를 못 써서 거기서 refresh하면 회전된 토큰을 잃는다.
|
|
194
|
+
`applySetCookiesToCookieHeader` 순수 함수, `onTokenError` 옵션.
|
|
195
|
+
|
|
196
|
+
### Fixed
|
|
197
|
+
|
|
198
|
+
- 관리자 로그인 `getAccessToken`이 항상 `null`이었다 — better-auth 1.7.18+의 `/get-access-token` 본문은 `{ accountId }` 또는
|
|
199
|
+
`{ useAccountCookie: true }`인데 `providerId`를 보내 검증에서 거절됐고 그 오류를 삼켰다(bootstrap 세션 보고). 이제 계정 쿠키를
|
|
200
|
+
고르고, 실패 코드는 `onTokenError`(기본 `console.warn`)로 드러낸다. `ReoptWorkspaceAuthLike`가 앱의 실제 인스턴스를 받는다.
|
|
201
|
+
- 플랫폼 클라이언트가 JSON이 아닌 응답(프록시 502·서버 오류 HTML)에 `SyntaxError`를 던졌다 — 이제 `PlatformApiError`
|
|
202
|
+
(`HTTP_ERROR`, 5xx는 retryable; 성공인데 JSON이 아니면 `INVALID_RESPONSE`).
|
|
203
|
+
|
|
10
204
|
## [0.1.0-rc.1] — 2026-11-20
|
|
11
205
|
|
|
12
206
|
Pre-release (`npm i @reopt-ai/workspace-sdk@next`).
|
package/README.md
CHANGED
|
@@ -5,15 +5,26 @@ a company site, a service that files work into Studio) rather than being one bra
|
|
|
5
5
|
|
|
6
6
|
- **Platform API** (`createPlatformClient`) — your server's machine credential: Works tasks,
|
|
7
7
|
published posts for a public site, declarative workspace resources, webhooks.
|
|
8
|
-
- **Delegated access** (`createConnectClient`) — a staff member signs in with
|
|
9
|
-
acts as **them**: Works, posts, files
|
|
8
|
+
- **Delegated access** (`createConnectClient`, also at `/connect`) — a staff member signs in with
|
|
9
|
+
Reopt and your app acts as **them**: Works tasks, posts, files and folders, forms and
|
|
10
|
+
inquiries, brands, members and the app's own tables, limited by their workspace role.
|
|
11
|
+
Every list is a page (`{ items, nextOffset }`), every write returns the object, every failure
|
|
12
|
+
is a `PlatformApiError` with a typed `code`.
|
|
13
|
+
- **Permissions** (`/permissions`, no dependencies — safe in client components) — the permission
|
|
14
|
+
keys and `can(me, "post:publish")` / `canCall(me, "works.deleteTask")`.
|
|
15
|
+
- **Dev platform** (`/testing`) — an in-memory Reopt for dev mode and E2E: keep the real clients,
|
|
16
|
+
swap their `fetch`. See `docs/testing.md`.
|
|
17
|
+
- **Webhooks** (`/webhooks`, no dependencies) — receive Reopt's events with the signature and
|
|
18
|
+
replay window checked: `createWebhookHandler({ secret, handlers })`.
|
|
10
19
|
- **Machine credentials** (`/machine`) — `private_key_jwt` + DPoP, key generation (`reopt-keygen`), JWKS.
|
|
11
20
|
- **Installations** (`/installation`) — declare, sign and request your app's connection.
|
|
12
21
|
- **Resource verifier** (`/resource`), **social operations** (`/social`), **id host resolution** (`/urls`).
|
|
13
22
|
|
|
14
|
-
Server-only (it holds private keys and tokens)
|
|
15
|
-
`/
|
|
16
|
-
|
|
23
|
+
Server-only (it holds private keys and tokens) except `/permissions`, `/operator` and `/urls`
|
|
24
|
+
(`/webhooks` runs anywhere Web Crypto does, but holds your webhook secret — keep it on the server).
|
|
25
|
+
Optional peers: `zod` for `.`, `/connect`, `/social` and `/installation`; `@better-auth/core` for
|
|
26
|
+
`.`, `/machine` and `/resource` (the platform client signs DPoP proofs with it). An app that only
|
|
27
|
+
uses the delegated client imports `/connect` and needs `zod` alone. Node 20+.
|
|
17
28
|
|
|
18
29
|
```bash
|
|
19
30
|
npm i @reopt-ai/workspace-sdk zod @better-auth/core
|
|
@@ -30,13 +41,16 @@ const platform = createPlatformClient({
|
|
|
30
41
|
clientId: process.env.REOPT_MACHINE_CLIENT_ID!,
|
|
31
42
|
scopes: ["posts:read"],
|
|
32
43
|
});
|
|
33
|
-
const { posts } = await platform.posts.list({ limit: 10 });
|
|
44
|
+
const { items: posts } = await platform.posts.list({ limit: 10 });
|
|
34
45
|
|
|
35
46
|
// admin — the signed-in member's token from your `connect` OAuth client
|
|
36
47
|
const reopt = createConnectClient({
|
|
37
48
|
accessToken: () => getAccessTokenForUser(),
|
|
38
49
|
});
|
|
39
|
-
const me = await reopt.me(); // me
|
|
50
|
+
const me = await reopt.me(); // can(me, "post:publish") decides which buttons to show
|
|
51
|
+
const { items: tasks, nextOffset } = await reopt.works.listTasks({
|
|
52
|
+
outcome: "active",
|
|
53
|
+
});
|
|
40
54
|
```
|
|
41
55
|
|
|
42
56
|
Docs: `docs/workspace.md` (platform API and delegated access), `docs/machine.md`,
|
|
@@ -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,235 @@
|
|
|
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
|
+
/** 진행 중이거나 방금 끝난 프록시 refresh — 키는 요청의 Cookie 헤더(세션마다 다르다). */
|
|
150
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
151
|
+
const SHARED_REFRESH_MS = 1e4;
|
|
152
|
+
const MAX_SHARED_REFRESHES = 1e3;
|
|
153
|
+
async function refreshOnce(auth, headers, proxyOptions, now) {
|
|
154
|
+
{
|
|
155
|
+
const withinMs = (proxyOptions.withinSeconds ?? 120) * 1e3;
|
|
156
|
+
const getCall = auth.api.getAccessToken;
|
|
157
|
+
const refreshCall = auth.api.refreshToken;
|
|
158
|
+
let setCookies = [];
|
|
159
|
+
let refreshed = false;
|
|
160
|
+
try {
|
|
161
|
+
const current = await getCall({
|
|
162
|
+
body: { useAccountCookie: true },
|
|
163
|
+
headers,
|
|
164
|
+
returnHeaders: true
|
|
165
|
+
});
|
|
166
|
+
setCookies = setCookiesOf(current.headers);
|
|
167
|
+
refreshed = setCookies.length > 0;
|
|
168
|
+
const expiresAt = current.response?.accessTokenExpiresAt;
|
|
169
|
+
const remaining = expiresAt == null ? Infinity : new Date(expiresAt).getTime() - now();
|
|
170
|
+
if (!refreshed && remaining < withinMs) {
|
|
171
|
+
setCookies = setCookiesOf((await refreshCall({
|
|
172
|
+
body: { useAccountCookie: true },
|
|
173
|
+
headers,
|
|
174
|
+
returnHeaders: true
|
|
175
|
+
})).headers);
|
|
176
|
+
refreshed = true;
|
|
177
|
+
}
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if (errorCode(error) !== "UNAUTHORIZED") reportTokenError(error);
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
setCookies,
|
|
184
|
+
cookieHeader: applySetCookiesToCookieHeader(headers.get("cookie"), setCookies),
|
|
185
|
+
refreshed
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
plugin,
|
|
191
|
+
providerId: REOPT_WORKSPACE_PROVIDER_ID,
|
|
192
|
+
resource: platformUrl,
|
|
193
|
+
scopes,
|
|
194
|
+
async getAccessToken(auth, headers) {
|
|
195
|
+
const call = auth.api.getAccessToken;
|
|
196
|
+
try {
|
|
197
|
+
return (await call({
|
|
198
|
+
body: { useAccountCookie: true },
|
|
199
|
+
headers
|
|
200
|
+
}))?.accessToken ?? null;
|
|
201
|
+
} catch (error) {
|
|
202
|
+
reportTokenError(error);
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
async refreshInProxy(auth, headers, proxyOptions = {}) {
|
|
207
|
+
const now = proxyOptions.now ?? (() => Date.now());
|
|
208
|
+
const cookie = headers.get("cookie");
|
|
209
|
+
if (!cookie) return refreshOnce(auth, headers, proxyOptions, now);
|
|
210
|
+
const at = now();
|
|
211
|
+
for (const [key, entry] of inflight) if (entry.expiresAt <= at) inflight.delete(key);
|
|
212
|
+
const copy = (result) => result && {
|
|
213
|
+
...result,
|
|
214
|
+
setCookies: [...result.setCookies]
|
|
215
|
+
};
|
|
216
|
+
const shared = inflight.get(cookie);
|
|
217
|
+
if (shared) return copy(await shared.promise);
|
|
218
|
+
const promise = refreshOnce(auth, headers, proxyOptions, now);
|
|
219
|
+
const entry = {
|
|
220
|
+
promise,
|
|
221
|
+
expiresAt: Number.POSITIVE_INFINITY
|
|
222
|
+
};
|
|
223
|
+
if (inflight.size >= MAX_SHARED_REFRESHES) inflight.clear();
|
|
224
|
+
inflight.set(cookie, entry);
|
|
225
|
+
const result = await promise.catch(() => null);
|
|
226
|
+
if (result?.refreshed) entry.expiresAt = now() + SHARED_REFRESH_MS;
|
|
227
|
+
else if (inflight.get(cookie) === entry) inflight.delete(cookie);
|
|
228
|
+
return copy(result);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
//#endregion
|
|
234
|
+
export { REOPT_RECONSENT_PARAMS, REOPT_WORKSPACE_LOGIN_SCOPES, REOPT_WORKSPACE_PROVIDER_ID, applySetCookiesToCookieHeader, createReoptWorkspaceLogin, isReconsentRequired };
|
|
235
|
+
//# sourceMappingURL=index.js.map
|