@reopt-ai/brandapp-sdk 4.5.0 → 4.7.0-rc.1
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 +62 -1
- package/README.md +13 -13
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.js +1 -1
- package/dist/ai-provider/index.d.ts +1 -1
- package/dist/ai-provider/index.js +1 -1
- package/dist/analytics/index.d.ts +1 -1
- package/dist/analytics/index.js +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/better-auth/index.d.ts +10 -9
- package/dist/better-auth/index.js +19 -6
- package/dist/{client-ijQDMf1X.js → client-BFl6cDAE.js} +23 -2
- package/dist/{client-DLvWSpaz.js → client-BJQzInqD.js} +4 -4
- package/dist/{client-IUSZDJio.d.ts → client-BQJepjoD.d.ts} +44 -4
- package/dist/{client-BlKXDOUb.js → client-BZ8-vFjk.js} +4 -4
- package/dist/{client-d0EwZNc4.js → client-Bf8mW6uO.js} +3 -3
- package/dist/client-C-LdW4gY.js +194 -0
- package/dist/{client-C6OXGMMV.d.ts → client-C2W4RAZV.d.ts} +2 -2
- package/dist/{client-7I-mz3Dw.d.ts → client-C6lx3RUQ.d.ts} +2 -2
- package/dist/{client-p-tpQ1xj.js → client-CLZie3Ym.js} +2 -2
- package/dist/{client-yKeRJnIB.d.ts → client-CSl3o0s3.d.ts} +2 -2
- package/dist/{client-D1AFtJRw.d.ts → client-Cnq_X3Wp.d.ts} +2 -2
- package/dist/{client-Bfutv3LK.d.ts → client-Cod87ThY.d.ts} +2 -2
- package/dist/{client-BSW0Ncjj.d.ts → client-CsWSxMhB.d.ts} +2 -2
- package/dist/{client-Cg_gl0Gk.js → client-CslasnqK.js} +2 -2
- package/dist/{client-CU9KBiDi.js → client-DGKq4Ml5.js} +3 -3
- package/dist/{client-BnRfa5hI.js → client-Db6Etco9.js} +2 -2
- package/dist/{client-Dmvtr1nS.d.ts → client-DfnaH99z.d.ts} +2 -2
- package/dist/{client-COKDtHO9.d.ts → client-MDNS9Ubf.d.ts} +2 -2
- package/dist/{client-D9QA4f3H.js → client-VKEJtLH0.js} +2 -2
- package/dist/{client-NQ0p6XSB.js → client-_2Avom0q.js} +2 -2
- package/dist/{client-CniCGdmi.d.ts → client-xblzWFAL.d.ts} +2 -2
- package/dist/cms/index.d.ts +1 -1
- package/dist/cms/index.js +1 -1
- package/dist/{config-D3SblxWt.d.ts → config-CnFnzh7Q.d.ts} +21 -6
- package/dist/{config-DCFgtfSu.js → config-Dy2oBn1a.js} +13 -10
- package/dist/dev/index.d.ts +1 -1
- package/dist/eav/index.d.ts +2 -2
- package/dist/eav/index.js +2 -2
- package/dist/eav/migrate.d.ts +2 -2
- package/dist/eav/schema.d.ts +2 -2
- package/dist/feedback/index.d.ts +1 -1
- package/dist/feedback/index.js +1 -1
- package/dist/files/index.d.ts +1 -1
- package/dist/files/index.js +1 -1
- package/dist/{http-client-CHXNS9TI.js → http-client-CW9wXANY.js} +9 -3
- package/dist/{index-BnAYxnwq.d.ts → index-Bkci7euU.d.ts} +14 -12
- package/dist/{index-C6fyJTud.d.ts → index-Dh8XMVFF.d.ts} +2 -2
- package/dist/index.d.ts +4 -4
- package/dist/index.js +12 -12
- package/dist/keys-B2pA8EkU.d.ts +44 -0
- package/dist/keys-B_R_lsyF.js +102 -0
- package/dist/logout/index.d.ts +1 -1
- package/dist/logout/index.js +1 -1
- package/dist/machine/index.d.ts +72 -0
- package/dist/machine/index.js +4 -0
- package/dist/machine/keygen-cli.d.ts +7 -0
- package/dist/machine/keygen-cli.js +57 -0
- package/dist/plans/index.d.ts +2 -2
- package/dist/plans/index.js +1 -1
- package/dist/push/index.d.ts +1 -1
- package/dist/push/index.js +1 -1
- package/dist/{query-ZVC28Rp8.js → query-DPD0WYlB.js} +2 -2
- package/dist/react/hooks.d.ts +4 -4
- package/dist/terms/index.d.ts +1 -1
- package/dist/terms/index.js +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/workspace/index.d.ts +61 -9
- package/dist/workspace/index.js +57 -9
- package/docs/api-reference.md +43 -24
- package/docs/dev-server.md +2 -2
- package/docs/environment.md +4 -4
- package/docs/machine.md +104 -0
- package/docs/workspace.md +12 -0
- package/package.json +19 -5
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,67 @@ This project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [4.7.0-rc.1] — 2026-10-10
|
|
11
|
+
|
|
12
|
+
Pre-release (`npm i @reopt-ai/brandapp-sdk@next`) — RFC-0034 machine credentials. Everything below ships here.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- **`@reopt-ai/brandapp-sdk/machine`** (RFC-0034) — 서버 간 호출용 기계 자격. 공유 시크릿 대신 **`private_key_jwt`**(RFC 7523)
|
|
17
|
+
단언과 **DPoP**(RFC 9449) 증명으로 id.reopt.ai에서 토큰을 받는다. `generateClientKeyPair()`(EdDSA, `kid`=JWK 지문),
|
|
18
|
+
`readClientKeyRing()`(env `REOPT_CLIENT_PRIVATE_KEY_JWK`, 회전 중 `_NEXT`), `buildClientJwks()`·`CLIENT_JWKS_PATH`
|
|
19
|
+
(`/.well-known/reopt-client-jwks.json`에 공개키 게시), `createMachineClient({ clientId, keyRing|privateKeyJwk, resource, scopes })`
|
|
20
|
+
— `getToken()`·`headers({ method, url })`·`fetch()`(401 시 한 번 재발급)·`invalidateToken()`. 토큰은 resource(audience) 하나에
|
|
21
|
+
묶이고 만료 60초 전 재발급된다. 실패는 `MachineTokenError`(`code`·`status`). **서버 전용**(브라우저에서 호출하면 throw).
|
|
22
|
+
- bin **`reopt-keygen`** — 개인키 env 한 줄과 JWKS 라우트 안내를 출력한다(키는 그 줄에만 찍힌다).
|
|
23
|
+
- `createReoptSDK({ authorization })` — 요청마다 인증 헤더를 만드는 훅. `authorization: machine.headers`로 어댑터·EAV 호출을
|
|
24
|
+
기계 토큰(DPoP)으로 보낸다. `clientSecret` 없이 만들 수 있다.
|
|
25
|
+
- `createReoptOAuth({ tokenEndpointAuthMethod: "private_key_jwt", privateKeyJwk? })` — 로그인 클라이언트의 토큰 엔드포인트
|
|
26
|
+
인증을 비대칭으로. 키는 인자 또는 env 키 링에서 읽고, 없으면 즉시 throw.
|
|
27
|
+
- `createPlatformClient({ privateKeyJwk | keyRing })` — 플랫폼 API 클라이언트도 시크릿 없이 private_key_jwt + DPoP로 간다
|
|
28
|
+
(`clientSecret`은 이제 선택). 요청마다 메서드·URL에 묶인 DPoP 증명이 붙는다.
|
|
29
|
+
- 플랫폼 OAuth 클라이언트 리소스에 **`purpose`**(`web`·`adapter`·`machine`·`connect`, `PLATFORM_OAUTH_CLIENT_PURPOSES`)·
|
|
30
|
+
`jwksUri`·`dpopBoundAccessTokens` 필드와 `tokenEndpointAuthMethod: "private_key_jwt"`가 생겼다. `purpose`를 생략하면
|
|
31
|
+
그랜트에서 추정한다(`client_credentials`만 → `machine`, 그 밖엔 `web`).
|
|
32
|
+
|
|
33
|
+
- `plans.getCustomerPlan(authUserId)` — 고객의 토큰 없이 **앱 자격 증명으로** 고객 한 명의 현재 플랜을
|
|
34
|
+
읽는다(`GET /plans/customers/{authUserId}/plan`). 백그라운드 작업, 자체 기기·API 토큰으로 들어온 요청,
|
|
35
|
+
토큰이 만료된 고객의 엔타이틀먼트 확인용이다. `authUserId`는 Better Auth `session.user.id`,
|
|
36
|
+
응답은 `getMyPlan`과 같은 모양이다. 서버 전용 — 고객 토큰으로 부르면 403 `APP_CREDENTIAL_REQUIRED`.
|
|
37
|
+
|
|
38
|
+
- `CurrentPlan.paymentEnvironment`(`"live" | "test" | "simulation" | null`) — 지금 플랜을 만든 체크아웃의
|
|
39
|
+
결제 환경. `paymentProvider`와 달리 해지 뒤 남은 이용 기간에도 유지되므로 "실 결제로 얻은 플랜만 인정"의
|
|
40
|
+
근거로 쓸 수 있다. `null`은 모름(체크아웃을 거치지 않은 플랜)이다. 타입 `PlanPaymentEnvironment` export.
|
|
41
|
+
- `getCustomerPlan`의 404가 탈퇴를 구분한다 — 연결된 적 없으면 `NOT_FOUND`, 탈퇴했으면 `CUSTOMER_WITHDRAWN`.
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
|
|
45
|
+
- 파일·폴더 라우트(`sdk.files`·폴더)는 **앱 자격 증명 전용**이다 — 고객 액세스 토큰을 거절한다
|
|
46
|
+
(403 `APP_CREDENTIAL_REQUIRED`). SDK는 이 라우트에 고객 토큰을 보낸 적이 없어 SDK 사용처는 영향이 없다.
|
|
47
|
+
- AI 라우트를 고객 액세스 토큰으로 부르면 사용량과 고객별 호출 제한이 **토큰 주인으로 고정**된다.
|
|
48
|
+
본문의 `customerId`가 토큰 주인과 다르면 403이다. 앱 자격으로 부르는 호출은 그대로 본문 값을 쓴다.
|
|
49
|
+
- CMS 미발행 글은 앱의 관리 자격에만 보인다 — `brandapp:write`가 실린 고객 토큰에는 발행된 글만 나간다.
|
|
50
|
+
- `PUT /plans/external-subscription`(스토어 구독 미러)은 **앱 자격 증명 전용**이다 — 플랫폼이 고객 액세스
|
|
51
|
+
토큰을 scope와 무관하게 거절한다(403 `APP_CREDENTIAL_REQUIRED`). Basic 자격이나 서비스 토큰으로
|
|
52
|
+
부르는 서버 호출은 그대로다.
|
|
53
|
+
|
|
54
|
+
- 개발 기본 호스트에서 포트를 뗐다. `REOPT_BASE_URLS`·`REOPT_ID_BASE_URLS`·`REOPT_PLATFORM_URLS`·
|
|
55
|
+
`REOPT_PLATFORM_ID_URLS`의 `development` 값이 `https://{brand,id,platform}.local.reopt.io`다(이전 `:3443`) —
|
|
56
|
+
dev-proxy가 표준 HTTPS 포트(443)에서 듣는다. `REOPT_BASE_URL`·`config.baseUrl` 등으로 직접 준 값은 그대로 쓴다.
|
|
57
|
+
|
|
58
|
+
## [4.6.0] — 2026-09-22
|
|
59
|
+
|
|
60
|
+
### Added
|
|
61
|
+
|
|
62
|
+
- `./workspace`에 `platformCustomerUpsertInputSchema`·`PlatformCustomerUpsertInput`을 추가했다
|
|
63
|
+
(RFC-0029 §13 — 외부 앱 고객을 워크스페이스 CRM에 미러링하는 입력). `attributes` 키는
|
|
64
|
+
워크스페이스에 선언된 속성 **이름**이고, 선언에 없거나 타입이 어긋나면 서버가 400으로 거절한다.
|
|
65
|
+
|
|
66
|
+
### Fixed
|
|
67
|
+
|
|
68
|
+
- Better Auth 의존성을 1.7.4로 갱신하고 제거된 `accountIssuer` 설정 전달을 중단했다.
|
|
69
|
+
SDK의 같은 이름 옵션은 소스 호환성을 위해 deprecated 상태로 유지하지만 동작하지 않는다.
|
|
70
|
+
|
|
10
71
|
## [4.5.0] — 2026-09-09
|
|
11
72
|
|
|
12
73
|
`4.5.0-platform.0`(platform 태그)의 정식 릴리스 — 그 프리릴리스 내용을 모두 포함한다.
|
|
@@ -711,7 +772,7 @@ reopt 플랫폼의 brandapp API host가 `brand.reopt.ai`로 분리됐다. Better
|
|
|
711
772
|
### Added
|
|
712
773
|
|
|
713
774
|
- **`ReoptSDKConfig.idBaseUrl`** — id (auth) 서버 URL을 명시 override. 미설정 시 `baseUrl` / `isProduction` / `NODE_ENV`로부터 derive.
|
|
714
|
-
- **`REOPT_ID_BASE_URLS`** export — `production: https://id.reopt.ai`, `development: https://id.reopt.
|
|
775
|
+
- **`REOPT_ID_BASE_URLS`** export — `production: https://id.reopt.ai`, `development: https://id.local.reopt.io:3443`.
|
|
715
776
|
- **`resolveIdBaseUrl(config)`** / **`deriveIdFromBaseUrl(baseUrl)`** export — id URL 해석 헬퍼.
|
|
716
777
|
- **`BaseHttpClient(config, pathPrefix, { useIdServer: true })`** — 옵션 인자로 id 서버 라우팅 활성화.
|
|
717
778
|
|
package/README.md
CHANGED
|
@@ -323,7 +323,7 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
|
|
|
323
323
|
brandappId: string; // Brandapp ID (required)
|
|
324
324
|
token?: string; // Short-lived Bearer token (Phase D-2b) —
|
|
325
325
|
// overrides Basic Auth when set
|
|
326
|
-
isProduction?: boolean; // true → brandapp.reopt.ai, false → brand.reopt.
|
|
326
|
+
isProduction?: boolean; // true → brandapp.reopt.ai, false → brand.local.reopt.io
|
|
327
327
|
// default: auto-detect from NODE_ENV
|
|
328
328
|
baseUrl?: string; // Main API host override (REOPT_BASE_URL env equivalent)
|
|
329
329
|
idBaseUrl?: string; // Auth host override (REOPT_ID_BASE_URL env equivalent)
|
|
@@ -347,11 +347,11 @@ const meta = asJson<Meta>(record.values.meta); // Meta | undefined
|
|
|
347
347
|
|
|
348
348
|
### Built-in URLs
|
|
349
349
|
|
|
350
|
-
| `isProduction` | Main API host
|
|
351
|
-
| --------------------- |
|
|
352
|
-
| `false` | `https://brand.reopt.
|
|
353
|
-
| `true` | `https://brandapp.reopt.ai`
|
|
354
|
-
| `undefined` (default) | auto from `NODE_ENV`
|
|
350
|
+
| `isProduction` | Main API host | Auth (id) host |
|
|
351
|
+
| --------------------- | ------------------------------ | --------------------------- |
|
|
352
|
+
| `false` | `https://brand.local.reopt.io` | `https://id.local.reopt.io` |
|
|
353
|
+
| `true` | `https://brandapp.reopt.ai` | `https://id.reopt.ai` |
|
|
354
|
+
| `undefined` (default) | auto from `NODE_ENV` | auto from `NODE_ENV` |
|
|
355
355
|
|
|
356
356
|
## Environment Variables
|
|
357
357
|
|
|
@@ -368,13 +368,13 @@ SDK는 `process.env`를 자동으로 읽습니다. 필수 변수 3개만 설정
|
|
|
368
368
|
|
|
369
369
|
**선택 (없으면 `NODE_ENV`로 자동 분기)**
|
|
370
370
|
|
|
371
|
-
| 변수 | 용도 | 기본값
|
|
372
|
-
| ------------------------- | -------------------------------------- |
|
|
373
|
-
| `REOPT_BASE_URL` | 메인 API host (reopt 플랫폼) | prod: `https://brandapp.reopt.ai`, dev: `https://brand.reopt.
|
|
374
|
-
| `REOPT_ID_BASE_URL` | 인증 host (reopt id 서버) | `REOPT_BASE_URL`에서 자동 유도
|
|
375
|
-
| `BRANDAPP_WEBHOOK_SECRET` | webhook HMAC 검증 | — (consumer가 `createWebhookHandler`에 명시 주입)
|
|
376
|
-
| `BRANDAPP_SDK_DEBUG` | 디버그 로그 (`trace` \| `info` \| `1`) | off
|
|
377
|
-
| `BRANDAPP_SDK_LOG_FORMAT` | 로그 포맷 (`json` 시 구조화) | plain
|
|
371
|
+
| 변수 | 용도 | 기본값 |
|
|
372
|
+
| ------------------------- | -------------------------------------- | ---------------------------------------------------------------------- |
|
|
373
|
+
| `REOPT_BASE_URL` | 메인 API host (reopt 플랫폼) | prod: `https://brandapp.reopt.ai`, dev: `https://brand.local.reopt.io` |
|
|
374
|
+
| `REOPT_ID_BASE_URL` | 인증 host (reopt id 서버) | `REOPT_BASE_URL`에서 자동 유도 |
|
|
375
|
+
| `BRANDAPP_WEBHOOK_SECRET` | webhook HMAC 검증 | — (consumer가 `createWebhookHandler`에 명시 주입) |
|
|
376
|
+
| `BRANDAPP_SDK_DEBUG` | 디버그 로그 (`trace` \| `info` \| `1`) | off |
|
|
377
|
+
| `BRANDAPP_SDK_LOG_FORMAT` | 로그 포맷 (`json` 시 구조화) | plain |
|
|
378
378
|
|
|
379
379
|
상세 우선순위·시나리오·트러블슈팅·브라우저(`NEXT_PUBLIC_BRANDAPP_*`)·CI/CD
|
|
380
380
|
패턴은 **[docs/environment.md](./docs/environment.md)**.
|
package/dist/ai/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as CompletionOptions, c as FinishReason, d as MessageRole, f as ModelInfo, i as ChatMessage, l as ImageGenerateOptions, m as StreamEvent, n as createReoptAiClient, o as CompletionResult, p as StreamDoneData, r as AgentInfo, s as CreditInfo, t as ReoptAiClient, u as ImageGenerateResult } from "../client-
|
|
1
|
+
import { a as CompletionOptions, c as FinishReason, d as MessageRole, f as ModelInfo, i as ChatMessage, l as ImageGenerateOptions, m as StreamEvent, n as createReoptAiClient, o as CompletionResult, p as StreamDoneData, r as AgentInfo, s as CreditInfo, t as ReoptAiClient, u as ImageGenerateResult } from "../client-Cnq_X3Wp.js";
|
|
2
2
|
export { type AgentInfo, type ChatMessage, type CompletionOptions, type CompletionResult, type CreditInfo, type FinishReason, type ImageGenerateOptions, type ImageGenerateResult, type MessageRole, type ModelInfo, ReoptAiClient, type StreamDoneData, type StreamEvent, createReoptAiClient };
|
package/dist/ai/index.js
CHANGED
|
@@ -73,7 +73,7 @@ type BrandappProviderConfig = {
|
|
|
73
73
|
/**
|
|
74
74
|
* 프로덕션 환경 여부.
|
|
75
75
|
* - `true`: https://brandapp.reopt.ai
|
|
76
|
-
* - `false`: https://brand.reopt.
|
|
76
|
+
* - `false`: https://brand.local.reopt.io (dev)
|
|
77
77
|
* - 미지정 (기본): `NODE_ENV === "production"` 자동 감지
|
|
78
78
|
*/
|
|
79
79
|
isProduction?: boolean;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-
|
|
1
|
+
import { i as resolveBaseUrl, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig, r as assertBrowserSafe } from "../config-Dy2oBn1a.js";
|
|
2
2
|
import { t as createManagedAbort } from "../abort--nOBFN4M.js";
|
|
3
3
|
import { t as createAuthHeader } from "../encoding-Bwfm3iaE.js";
|
|
4
4
|
import { t as createSSELineProcessor } from "../sse-parser-FMjxM7sY.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as createReoptAnalyticsClient, r as AnalyticsConfig, t as ReoptAnalyticsClient } from "../client-
|
|
1
|
+
import { n as createReoptAnalyticsClient, r as AnalyticsConfig, t as ReoptAnalyticsClient } from "../client-C6lx3RUQ.js";
|
|
2
2
|
import { identify, pageView, setConsent, track } from "@reopt-ai/data-sdk";
|
|
3
3
|
//#region src/analytics/browser.d.ts
|
|
4
4
|
type BrandappAnalytics = {
|
package/dist/analytics/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-
|
|
1
|
+
import { n as createReoptAnalyticsClient, t as ReoptAnalyticsClient } from "../client-Db6Etco9.js";
|
|
2
2
|
import { getInstance, identify, init, pageView, setConsent, track } from "@reopt-ai/data-sdk";
|
|
3
3
|
|
|
4
4
|
//#region src/analytics/browser.ts
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as UserInfoClaims, n as createReoptAuthClient, r as LinkCurrentUserResult, t as ReoptAuthClient } from "../client-
|
|
1
|
+
import { i as UserInfoClaims, n as createReoptAuthClient, r as LinkCurrentUserResult, t as ReoptAuthClient } from "../client-Cod87ThY.js";
|
|
2
2
|
//#region src/auth/session.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* 세션 쿠키 검증 — apps/id의 Better Auth `/api/auth/get-session`을 호출해
|
package/dist/auth/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { n as ReoptSDKConfig, t as REOPT_BASE_URLS } from "../config-
|
|
1
|
+
import { n as ReoptSDKConfig, t as REOPT_BASE_URLS } from "../config-CnFnzh7Q.js";
|
|
2
2
|
import { i as REOPT_PROVIDER_ID, n as AdapterRequestBody, r as REOPT_DEFAULT_SCOPES, t as AdapterOperation } from "../types-MXLudLBP.js";
|
|
3
|
+
import { i as ClientPrivateJwk } from "../keys-B2pA8EkU.js";
|
|
3
4
|
import { T as isReoptSDKError, _ as RateLimitError, t as AuthError, v as ReoptSDKError, x as ServerError } from "../errors-U3TsyWVq.js";
|
|
4
5
|
import { AdapterFactory } from "better-auth/adapters";
|
|
5
6
|
import { BetterAuthOptions, BetterAuthPlugin } from "better-auth";
|
|
@@ -26,13 +27,8 @@ type ReoptOAuthOptions = ReoptSDKConfig & {
|
|
|
26
27
|
/** Additional OAuth scopes */
|
|
27
28
|
additionalScopes?: string[];
|
|
28
29
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* Reopt's OIDC discovery document reports as `issuer` — so the default
|
|
32
|
-
* changes nothing for existing accounts.
|
|
33
|
-
*
|
|
34
|
-
* Set this only if you point `idBaseUrl` at a proxy whose discovery
|
|
35
|
-
* `issuer` differs from the URL you configured.
|
|
30
|
+
* @deprecated Better Auth 1.7.3+ identifies accounts by providerId/accountId.
|
|
31
|
+
* Retained for source compatibility; this option is no longer forwarded.
|
|
36
32
|
*/
|
|
37
33
|
accountIssuer?: string;
|
|
38
34
|
/**
|
|
@@ -42,9 +38,14 @@ type ReoptOAuthOptions = ReoptSDKConfig & {
|
|
|
42
38
|
* method (`invalid_client`). Reopt brandapp clients are registered with
|
|
43
39
|
* `client_secret_post` unless noted otherwise in the studio.
|
|
44
40
|
*
|
|
41
|
+
* `private_key_jwt`(RFC-0034)면 clientSecret 대신 `privateKeyJwk`(또는 env `REOPT_CLIENT_PRIVATE_KEY_JWK`)로
|
|
42
|
+
* RFC 7523 단언을 서명한다 — 서버에는 공개키 주소(`jwksUri`)만 등록돼 있고 비밀이 오가지 않는다.
|
|
43
|
+
*
|
|
45
44
|
* @default "client_secret_post"
|
|
46
45
|
*/
|
|
47
|
-
tokenEndpointAuthMethod?: "client_secret_post" | "client_secret_basic";
|
|
46
|
+
tokenEndpointAuthMethod?: "client_secret_post" | "client_secret_basic" | "private_key_jwt";
|
|
47
|
+
/** `private_key_jwt`용 개인키 JWK(kid·alg 포함). 생략하면 env `REOPT_CLIENT_PRIVATE_KEY_JWK`(+`_NEXT`)를 읽는다. */
|
|
48
|
+
privateKeyJwk?: ClientPrivateJwk;
|
|
48
49
|
/**
|
|
49
50
|
* Also end the user's Reopt (identity provider) session when your app calls
|
|
50
51
|
* `authClient.signOut()` — OIDC RP-Initiated Logout through Reopt's
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { O as isReoptSDKError, S as ReoptSDKError, a as resolveIdBaseUrl, s as AuthError, t as REOPT_BASE_URLS, w as ServerError, x as RateLimitError } from "../config-
|
|
2
|
-
import { t as BaseHttpClient } from "../http-client-
|
|
1
|
+
import { O as isReoptSDKError, S as ReoptSDKError, a as resolveIdBaseUrl, s as AuthError, t as REOPT_BASE_URLS, w as ServerError, x as RateLimitError } from "../config-Dy2oBn1a.js";
|
|
2
|
+
import { t as BaseHttpClient } from "../http-client-CW9wXANY.js";
|
|
3
|
+
import { o as readClientKeyRing } from "../keys-B_R_lsyF.js";
|
|
3
4
|
import { n as REOPT_PROVIDER_ID, t as REOPT_DEFAULT_SCOPES } from "../types-DjDRszNj.js";
|
|
4
5
|
import { createAdapterFactory } from "better-auth/adapters";
|
|
6
|
+
import { createPrivateKeyJwtClientAssertionGetter } from "@better-auth/core/oauth2";
|
|
5
7
|
import { genericOAuth } from "better-auth/plugins";
|
|
6
8
|
|
|
7
9
|
//#region src/better-auth/adapter.ts
|
|
@@ -159,18 +161,29 @@ function createReoptAdapter(config) {
|
|
|
159
161
|
*/
|
|
160
162
|
function createReoptOAuth(options) {
|
|
161
163
|
if (typeof window !== "undefined") throw new Error("[@reopt-ai/brandapp-sdk] createReoptOAuth() must be called on the server. It uses clientSecret — exposing it to the browser is a security risk. For client-side OAuth sign-in, use signInWithReopt() from '@reopt-ai/brandapp-sdk/better-auth/client' instead.");
|
|
162
|
-
|
|
164
|
+
const method = options.tokenEndpointAuthMethod ?? "client_secret_post";
|
|
165
|
+
if (!options.clientId) throw new Error("[@reopt-ai/brandapp-sdk] createReoptOAuth() requires clientId.");
|
|
166
|
+
const privateKey = method === "private_key_jwt" ? options.privateKeyJwk ?? readClientKeyRing()?.signing ?? null : null;
|
|
167
|
+
if (method === "private_key_jwt" && !privateKey) throw new Error("[@reopt-ai/brandapp-sdk] createReoptOAuth() with private_key_jwt requires privateKeyJwk or REOPT_CLIENT_PRIVATE_KEY_JWK.");
|
|
168
|
+
if (method !== "private_key_jwt" && !options.clientSecret) throw new Error("[@reopt-ai/brandapp-sdk] createReoptOAuth() requires clientSecret for secret-based token endpoint auth (or use tokenEndpointAuthMethod: \"private_key_jwt\").");
|
|
163
169
|
const idBaseUrl = resolveIdBaseUrl(options);
|
|
164
170
|
return genericOAuth({ config: [{
|
|
165
171
|
providerId: REOPT_PROVIDER_ID,
|
|
166
172
|
discoveryUrl: `${idBaseUrl}/api/auth/.well-known/openid-configuration`,
|
|
167
|
-
accountIssuer: options.accountIssuer ?? idBaseUrl,
|
|
168
173
|
authorizationUrl: `${idBaseUrl}/api/auth/oauth2/authorize`,
|
|
169
174
|
tokenUrl: `${idBaseUrl}/api/auth/oauth2/token`,
|
|
170
175
|
userInfoUrl: `${idBaseUrl}/api/auth/oauth2/userinfo`,
|
|
171
176
|
clientId: options.clientId,
|
|
172
|
-
clientSecret: options.clientSecret,
|
|
173
|
-
tokenEndpointAuth:
|
|
177
|
+
...options.clientSecret ? { clientSecret: options.clientSecret } : {},
|
|
178
|
+
tokenEndpointAuth: privateKey ? {
|
|
179
|
+
method: "private_key_jwt",
|
|
180
|
+
getClientAssertion: createPrivateKeyJwtClientAssertionGetter({
|
|
181
|
+
privateKeyJwk: privateKey,
|
|
182
|
+
kid: privateKey.kid,
|
|
183
|
+
algorithm: privateKey.alg,
|
|
184
|
+
expiresIn: 120
|
|
185
|
+
})
|
|
186
|
+
} : { method },
|
|
174
187
|
disableProviderLogout: !options.providerLogout,
|
|
175
188
|
...typeof options.providerLogout === "object" && options.providerLogout.postLogoutRedirectURI ? { postLogoutRedirectURI: options.providerLogout.postLogoutRedirectURI } : {},
|
|
176
189
|
scopes: Array.from(/* @__PURE__ */ new Set([...REOPT_DEFAULT_SCOPES, ...options.additionalScopes ?? []])),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as BaseHttpClient } from "./http-client-
|
|
1
|
+
import { t as BaseHttpClient } from "./http-client-CW9wXANY.js";
|
|
2
2
|
|
|
3
3
|
//#region src/plans/client.ts
|
|
4
4
|
function unwrap(body) {
|
|
@@ -30,6 +30,27 @@ var ReoptPlansClient = class {
|
|
|
30
30
|
return unwrap(await this.http.fetch("GET", "/me/plan", void 0, { bearerToken: accessToken }));
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
33
|
+
* Fetch one customer's current plan / entitlement with **app credentials** —
|
|
34
|
+
* no customer token needed. Use it where there is no live user session to take
|
|
35
|
+
* a token from: background jobs, requests authenticated by your own device or
|
|
36
|
+
* API token, or a customer whose OAuth tokens have expired.
|
|
37
|
+
*
|
|
38
|
+
* `authUserId` is your Better Auth `session.user.id` (the same id the EAV API
|
|
39
|
+
* calls `authUserId`). The result has the same shape as {@link getMyPlan} and
|
|
40
|
+
* is `null` when the customer has no plan.
|
|
41
|
+
*
|
|
42
|
+
* Server-only: the request is signed with this client's own credentials
|
|
43
|
+
* (Basic, or the service token in `config.token`). The platform rejects a
|
|
44
|
+
* customer access token on this route with 403 `APP_CREDENTIAL_REQUIRED`, so
|
|
45
|
+
* one customer can never read another's plan.
|
|
46
|
+
*
|
|
47
|
+
* @throws {ReoptSDKError} 404 when that user has no customer link to this
|
|
48
|
+
* Brandapp (never signed in with `brandapp:write`, or withdrew).
|
|
49
|
+
*/
|
|
50
|
+
async getCustomerPlan(authUserId) {
|
|
51
|
+
return unwrap(await this.http.fetch("GET", `/customers/${encodeURIComponent(authUserId)}/plan`));
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
33
54
|
* Start a hosted checkout to subscribe the current customer (identified by
|
|
34
55
|
* `accessToken`) to `input.planId`, then redirect the browser to the returned
|
|
35
56
|
* `checkoutUrl`. That URL is an order-review page on id.reopt.ai showing the
|
|
@@ -78,4 +99,4 @@ function createReoptPlansClient(config) {
|
|
|
78
99
|
|
|
79
100
|
//#endregion
|
|
80
101
|
export { createReoptPlansClient as n, ReoptPlansClient as t };
|
|
81
|
-
//# sourceMappingURL=client-
|
|
102
|
+
//# sourceMappingURL=client-BFl6cDAE.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { u as BadRequestError } from "./config-
|
|
2
|
-
import { t as BaseHttpClient } from "./http-client-
|
|
3
|
-
import { t as buildQuery } from "./query-
|
|
1
|
+
import { u as BadRequestError } from "./config-Dy2oBn1a.js";
|
|
2
|
+
import { t as BaseHttpClient } from "./http-client-CW9wXANY.js";
|
|
3
|
+
import { t as buildQuery } from "./query-DPD0WYlB.js";
|
|
4
4
|
|
|
5
5
|
//#region src/eav/cache.ts
|
|
6
6
|
var SchemaCache = class {
|
|
@@ -564,4 +564,4 @@ function createReoptEavClient(config) {
|
|
|
564
564
|
|
|
565
565
|
//#endregion
|
|
566
566
|
export { RECORDS_PAGE_LIMIT_MAX as i, ATTRIBUTE_FILTER_LIST_MAX as n, ATTRIBUTE_FILTER_OPERATORS as r, createReoptEavClient as t };
|
|
567
|
-
//# sourceMappingURL=client-
|
|
567
|
+
//# sourceMappingURL=client-BJQzInqD.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as ReoptSDKConfig } from "./config-
|
|
1
|
+
import { n as ReoptSDKConfig } from "./config-CnFnzh7Q.js";
|
|
2
2
|
//#region src/plans/types.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Brandapp Plans types.
|
|
@@ -69,6 +69,8 @@ type Plan = {
|
|
|
69
69
|
type CheckoutStatus = "pending" | "completed" | "canceled" | "expired" | "failed";
|
|
70
70
|
/** `plans.createCheckout` 입력. */
|
|
71
71
|
type CreateCheckoutInput = {
|
|
72
|
+
/** Opaque Reopt click proofs; the server verifies brand ownership and click evidence. */
|
|
73
|
+
linkAttribution?: Partial<Record<"firstAcquisition" | "lastAcquisition" | "lastNavigation" | "referral", string>>;
|
|
72
74
|
/** 구독할 플랜 ID (`plans.list()`가 반환하는 `Plan.id`). */
|
|
73
75
|
planId: string;
|
|
74
76
|
/**
|
|
@@ -148,9 +150,28 @@ type CurrentPlan = {
|
|
|
148
150
|
planStartedAt: string | null;
|
|
149
151
|
/** ISO-8601 문자열. `null`이면 무기한. */
|
|
150
152
|
planExpiresAt: string | null;
|
|
151
|
-
/**
|
|
153
|
+
/**
|
|
154
|
+
* **활성** 결제 연결의 제공자 — "paddle" | "toss" | null.
|
|
155
|
+
*
|
|
156
|
+
* ⚠️ "실 결제인가"의 근거로 쓰지 말 것. 해지하면 연결이 보관되어 남은 이용 기간 동안
|
|
157
|
+
* `null`이 되고, 가상 결제·스토어 구독·운영자 배정도 모두 `null`이다. 그 판정에는
|
|
158
|
+
* {@link CurrentPlan.paymentEnvironment}를 쓴다.
|
|
159
|
+
*/
|
|
152
160
|
paymentProvider: string | null;
|
|
161
|
+
/**
|
|
162
|
+
* 이 플랜을 만든 체크아웃의 결제 환경. 해지 뒤 남은 기간에도 유지된다.
|
|
163
|
+
* - `"live"` — 실 결제
|
|
164
|
+
* - `"test"` — 결제사의 테스트 환경(테스트 카드)
|
|
165
|
+
* - `"simulation"` — 가상 결제(결제사를 거치지 않음)
|
|
166
|
+
* - `null` — **모름**: 체크아웃을 거치지 않은 플랜(스토어 구독 미러, 운영자 배정)이거나
|
|
167
|
+
* 환경을 기록하기 전의 구독. "실 결제가 아니다"로 읽지 말 것.
|
|
168
|
+
*
|
|
169
|
+
* 구버전 서버는 내려주지 않는다.
|
|
170
|
+
*/
|
|
171
|
+
paymentEnvironment?: PlanPaymentEnvironment | null;
|
|
153
172
|
};
|
|
173
|
+
/** {@link CurrentPlan.paymentEnvironment}. */
|
|
174
|
+
type PlanPaymentEnvironment = "live" | "test" | "simulation";
|
|
154
175
|
//#endregion
|
|
155
176
|
//#region src/plans/client.d.ts
|
|
156
177
|
declare class ReoptPlansClient {
|
|
@@ -168,6 +189,25 @@ declare class ReoptPlansClient {
|
|
|
168
189
|
* `accessToken`. Returns `null` when the customer has no active plan.
|
|
169
190
|
*/
|
|
170
191
|
getMyPlan(accessToken: string): Promise<CurrentPlan | null>;
|
|
192
|
+
/**
|
|
193
|
+
* Fetch one customer's current plan / entitlement with **app credentials** —
|
|
194
|
+
* no customer token needed. Use it where there is no live user session to take
|
|
195
|
+
* a token from: background jobs, requests authenticated by your own device or
|
|
196
|
+
* API token, or a customer whose OAuth tokens have expired.
|
|
197
|
+
*
|
|
198
|
+
* `authUserId` is your Better Auth `session.user.id` (the same id the EAV API
|
|
199
|
+
* calls `authUserId`). The result has the same shape as {@link getMyPlan} and
|
|
200
|
+
* is `null` when the customer has no plan.
|
|
201
|
+
*
|
|
202
|
+
* Server-only: the request is signed with this client's own credentials
|
|
203
|
+
* (Basic, or the service token in `config.token`). The platform rejects a
|
|
204
|
+
* customer access token on this route with 403 `APP_CREDENTIAL_REQUIRED`, so
|
|
205
|
+
* one customer can never read another's plan.
|
|
206
|
+
*
|
|
207
|
+
* @throws {ReoptSDKError} 404 when that user has no customer link to this
|
|
208
|
+
* Brandapp (never signed in with `brandapp:write`, or withdrew).
|
|
209
|
+
*/
|
|
210
|
+
getCustomerPlan(authUserId: string): Promise<CurrentPlan | null>;
|
|
171
211
|
/**
|
|
172
212
|
* Start a hosted checkout to subscribe the current customer (identified by
|
|
173
213
|
* `accessToken`) to `input.planId`, then redirect the browser to the returned
|
|
@@ -207,5 +247,5 @@ declare class ReoptPlansClient {
|
|
|
207
247
|
}
|
|
208
248
|
declare function createReoptPlansClient(config: ReoptSDKConfig): ReoptPlansClient;
|
|
209
249
|
//#endregion
|
|
210
|
-
export { CheckoutStatus as a, MeterPricingMode as c, PlanInterval as d, PlanMeter as f, CheckoutSession as i, Plan as l,
|
|
211
|
-
//# sourceMappingURL=client-
|
|
250
|
+
export { CheckoutStatus as a, MeterPricingMode as c, PlanInterval as d, PlanMeter as f, PlanRequiredTerms as h, CheckoutSession as i, Plan as l, PlanPaymentEnvironment as m, createReoptPlansClient as n, CreateCheckoutInput as o, PlanMeterTier as p, CancelSubscriptionResult as r, CurrentPlan as s, ReoptPlansClient as t, PlanBillingModel as u };
|
|
251
|
+
//# sourceMappingURL=client-BQJepjoD.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as ReoptSDKError, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig } from "./config-
|
|
1
|
+
import { S as ReoptSDKError, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig } from "./config-Dy2oBn1a.js";
|
|
2
2
|
import { t as createManagedAbort } from "./abort--nOBFN4M.js";
|
|
3
|
-
import { t as BaseHttpClient } from "./http-client-
|
|
3
|
+
import { t as BaseHttpClient } from "./http-client-CW9wXANY.js";
|
|
4
4
|
import { n as parseSSEStream } from "./sse-parser-FMjxM7sY.js";
|
|
5
5
|
|
|
6
6
|
//#region src/ai/client.ts
|
|
@@ -231,7 +231,7 @@ var ReoptAiClient = class {
|
|
|
231
231
|
}
|
|
232
232
|
async fetchSSE(options) {
|
|
233
233
|
const url = `${this.http.requestBaseUrl}/chat/completions`;
|
|
234
|
-
const requestId = globalThis.crypto?.randomUUID?.() ?? `sdk-${"4.
|
|
234
|
+
const requestId = globalThis.crypto?.randomUUID?.() ?? `sdk-${"4.7.0-rc.1"}-${url.length}`;
|
|
235
235
|
const ctx = {
|
|
236
236
|
method: "POST",
|
|
237
237
|
url,
|
|
@@ -309,4 +309,4 @@ function createReoptAiClient(config) {
|
|
|
309
309
|
|
|
310
310
|
//#endregion
|
|
311
311
|
export { createReoptAiClient as n, ReoptAiClient as t };
|
|
312
|
-
//# sourceMappingURL=client-
|
|
312
|
+
//# sourceMappingURL=client-BZ8-vFjk.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as ReoptSDKError, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig } from "./config-
|
|
1
|
+
import { S as ReoptSDKError, j as mapHttpStatusToError, n as SDK_VERSION, o as validateConfig } from "./config-Dy2oBn1a.js";
|
|
2
2
|
import { t as createManagedAbort } from "./abort--nOBFN4M.js";
|
|
3
|
-
import { n as parseFieldErrors, t as BaseHttpClient } from "./http-client-
|
|
3
|
+
import { n as parseFieldErrors, t as BaseHttpClient } from "./http-client-CW9wXANY.js";
|
|
4
4
|
|
|
5
5
|
//#region src/files/client.ts
|
|
6
6
|
var ReoptFileClient = class {
|
|
@@ -270,4 +270,4 @@ function createReoptFileClient(config) {
|
|
|
270
270
|
|
|
271
271
|
//#endregion
|
|
272
272
|
export { createReoptFileClient as n, ReoptFileClient as t };
|
|
273
|
-
//# sourceMappingURL=client-
|
|
273
|
+
//# sourceMappingURL=client-Bf8mW6uO.js.map
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { a as resolveIdBaseUrl } from "./config-Dy2oBn1a.js";
|
|
2
|
+
import { o as readClientKeyRing, s as toPublicJwk } from "./keys-B_R_lsyF.js";
|
|
3
|
+
import { createPrivateKeyJwtClientAssertionGetter } from "@better-auth/core/oauth2";
|
|
4
|
+
import * as jose from "jose";
|
|
5
|
+
|
|
6
|
+
//#region src/machine/client.ts
|
|
7
|
+
/**
|
|
8
|
+
* 기계 클라이언트 (RFC-0034 §3.2) — `private_key_jwt` 단언으로 `client_credentials` 토큰을 받고,
|
|
9
|
+
* 매 요청에 DPoP 증명을 붙인다. 리옵트 플랫폼 API·브랜드앱 API·서브 제품 리소스(reopt-data 등)
|
|
10
|
+
* 전부 같은 클라이언트로 부른다 — **호출 대상(resource)마다 토큰이 따로**다(aud 하나, RFC-0034 §3.2).
|
|
11
|
+
*
|
|
12
|
+
* 서버 전용이다. 개인키는 env(`REOPT_CLIENT_PRIVATE_KEY_JWK`)에서 읽고 브라우저 번들에 들어갈 수 없다.
|
|
13
|
+
*
|
|
14
|
+
* 흐름:
|
|
15
|
+
* token(): POST {id}/api/auth/oauth2/token
|
|
16
|
+
* grant_type=client_credentials · client_assertion(JWS, exp≤5m, jti) · scope · resource
|
|
17
|
+
* 헤더 DPoP: 증명(htm=POST, htu=token endpoint) → access_token(`cnf.jkt` 바인딩)
|
|
18
|
+
* headers(): Authorization: DPoP <token> · DPoP: 증명(htm, htu=요청 URL, ath=sha256(token))
|
|
19
|
+
*
|
|
20
|
+
* 🔑 better-auth core가 단언 서명(`createPrivateKeyJwtClientAssertionGetter`)과 서버 쪽 DPoP 검증을
|
|
21
|
+
* 내장하므로 클라이언트 쪽 DPoP 증명만 jose로 만든다(core의 `clientCredentialsToken`은 DPoP 헤더를
|
|
22
|
+
* 싣지 않아 토큰 요청은 직접 조립한다).
|
|
23
|
+
*/
|
|
24
|
+
var MachineTokenError = class extends Error {
|
|
25
|
+
status;
|
|
26
|
+
code;
|
|
27
|
+
constructor(input) {
|
|
28
|
+
super(input.message);
|
|
29
|
+
this.name = "MachineTokenError";
|
|
30
|
+
this.status = input.status;
|
|
31
|
+
this.code = input.code;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const REFRESH_SKEW_MS = 6e4;
|
|
35
|
+
const CLIENT_ASSERTION_TTL_SECONDS = 120;
|
|
36
|
+
function assertServerRuntime() {
|
|
37
|
+
if (typeof window !== "undefined") throw new Error("[@reopt-ai/brandapp-sdk/machine] createMachineClient() must be called on the server — it holds the client private key.");
|
|
38
|
+
}
|
|
39
|
+
async function importPrivateKey(jwk) {
|
|
40
|
+
return jose.importJWK(jwk, jwk.alg);
|
|
41
|
+
}
|
|
42
|
+
/** DPoP 증명(RFC 9449 §4) — htm·htu(쿼리·프래그먼트 제거)·jti·iat, 리소스 요청이면 ath. */
|
|
43
|
+
async function createDpopProof(input) {
|
|
44
|
+
const parsed = new URL(input.url);
|
|
45
|
+
const htu = `${parsed.origin}${parsed.pathname}`;
|
|
46
|
+
const payload = {
|
|
47
|
+
htm: input.method.toUpperCase(),
|
|
48
|
+
htu,
|
|
49
|
+
jti: crypto.randomUUID()
|
|
50
|
+
};
|
|
51
|
+
if (input.accessToken) {
|
|
52
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input.accessToken));
|
|
53
|
+
payload.ath = jose.base64url.encode(new Uint8Array(digest));
|
|
54
|
+
}
|
|
55
|
+
return new jose.SignJWT(payload).setProtectedHeader({
|
|
56
|
+
alg: input.key.alg,
|
|
57
|
+
typ: "dpop+jwt",
|
|
58
|
+
jwk: toPublicJwk(input.key)
|
|
59
|
+
}).setIssuedAt(input.now !== void 0 ? Math.floor(input.now / 1e3) : void 0).sign(await importPrivateKey(input.key));
|
|
60
|
+
}
|
|
61
|
+
function createMachineClient(config) {
|
|
62
|
+
assertServerRuntime();
|
|
63
|
+
if (!config.clientId) throw new Error("[@reopt-ai/brandapp-sdk/machine] clientId is required");
|
|
64
|
+
if (!config.resource) throw new Error("[@reopt-ai/brandapp-sdk/machine] resource (token audience) is required");
|
|
65
|
+
const ring = config.keyRing ?? (config.privateKeyJwk ? {
|
|
66
|
+
signing: config.privateKeyJwk,
|
|
67
|
+
published: [config.privateKeyJwk]
|
|
68
|
+
} : null) ?? readClientKeyRing();
|
|
69
|
+
if (!ring) throw new Error("[@reopt-ai/brandapp-sdk/machine] no client private key — pass privateKeyJwk or set REOPT_CLIENT_PRIVATE_KEY_JWK (generate with `npx @reopt-ai/brandapp-sdk reopt-keygen`)");
|
|
70
|
+
const key = ring.signing;
|
|
71
|
+
const useDpop = config.dpop ?? true;
|
|
72
|
+
const tokenEndpoint = `${resolveIdBaseUrl({
|
|
73
|
+
brandappId: "",
|
|
74
|
+
...config.idBaseUrl ? { idBaseUrl: config.idBaseUrl } : {}
|
|
75
|
+
})}/api/auth/oauth2/token`;
|
|
76
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
77
|
+
const timeoutMs = config.timeoutMs ?? 1e4;
|
|
78
|
+
const now = config.now ?? (() => Date.now());
|
|
79
|
+
const scope = config.scopes.join(" ");
|
|
80
|
+
const getClientAssertion = createPrivateKeyJwtClientAssertionGetter({
|
|
81
|
+
privateKeyJwk: key,
|
|
82
|
+
kid: key.kid,
|
|
83
|
+
algorithm: key.alg,
|
|
84
|
+
expiresIn: CLIENT_ASSERTION_TTL_SECONDS
|
|
85
|
+
});
|
|
86
|
+
let state = null;
|
|
87
|
+
let inflight = null;
|
|
88
|
+
async function requestToken() {
|
|
89
|
+
const assertion = await getClientAssertion({
|
|
90
|
+
clientId: config.clientId,
|
|
91
|
+
tokenEndpoint,
|
|
92
|
+
grantType: "client_credentials"
|
|
93
|
+
});
|
|
94
|
+
const body = new URLSearchParams({
|
|
95
|
+
grant_type: "client_credentials",
|
|
96
|
+
client_id: config.clientId,
|
|
97
|
+
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
|
|
98
|
+
client_assertion: assertion,
|
|
99
|
+
scope,
|
|
100
|
+
resource: config.resource
|
|
101
|
+
});
|
|
102
|
+
const headers = {
|
|
103
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
104
|
+
accept: "application/json"
|
|
105
|
+
};
|
|
106
|
+
if (useDpop) headers.DPoP = await createDpopProof({
|
|
107
|
+
key,
|
|
108
|
+
method: "POST",
|
|
109
|
+
url: tokenEndpoint,
|
|
110
|
+
now: now()
|
|
111
|
+
});
|
|
112
|
+
const res = await fetchImpl(tokenEndpoint, {
|
|
113
|
+
method: "POST",
|
|
114
|
+
headers,
|
|
115
|
+
body,
|
|
116
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
117
|
+
});
|
|
118
|
+
const json = await res.json().catch(() => null);
|
|
119
|
+
if (!res.ok || !json?.access_token) throw new MachineTokenError({
|
|
120
|
+
status: res.status,
|
|
121
|
+
code: json?.error ?? "token_error",
|
|
122
|
+
message: json?.error_description ?? `Failed to obtain machine access token (${res.status})`
|
|
123
|
+
});
|
|
124
|
+
const tokenType = (json.token_type ?? (useDpop ? "DPoP" : "Bearer")).toLowerCase() === "dpop" ? "DPoP" : "Bearer";
|
|
125
|
+
if (useDpop && tokenType !== "DPoP") throw new MachineTokenError({
|
|
126
|
+
status: res.status,
|
|
127
|
+
code: "dpop_not_bound",
|
|
128
|
+
message: "Token endpoint returned a Bearer token although DPoP was requested — is `dpopBoundAccessTokens` set on the client?"
|
|
129
|
+
});
|
|
130
|
+
return {
|
|
131
|
+
accessToken: json.access_token,
|
|
132
|
+
tokenType,
|
|
133
|
+
expiresAt: now() + (json.expires_in ?? 3600) * 1e3,
|
|
134
|
+
scope: json.scope ?? scope
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
async function getToken(force = false) {
|
|
138
|
+
if (!force && state && state.expiresAt - REFRESH_SKEW_MS > now()) return state.accessToken;
|
|
139
|
+
if (!inflight) inflight = requestToken().finally(() => {
|
|
140
|
+
inflight = null;
|
|
141
|
+
});
|
|
142
|
+
state = await inflight;
|
|
143
|
+
return state.accessToken;
|
|
144
|
+
}
|
|
145
|
+
async function headers(request) {
|
|
146
|
+
const token = await getToken();
|
|
147
|
+
if (!useDpop) return { Authorization: `Bearer ${token}` };
|
|
148
|
+
return {
|
|
149
|
+
Authorization: `DPoP ${token}`,
|
|
150
|
+
DPoP: await createDpopProof({
|
|
151
|
+
key,
|
|
152
|
+
method: request.method,
|
|
153
|
+
url: request.url,
|
|
154
|
+
accessToken: token,
|
|
155
|
+
now: now()
|
|
156
|
+
})
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
async function authedFetch(input, init = {}) {
|
|
160
|
+
const url = typeof input === "string" ? input : input.toString();
|
|
161
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
162
|
+
const send = async () => fetchImpl(url, {
|
|
163
|
+
...init,
|
|
164
|
+
method,
|
|
165
|
+
headers: {
|
|
166
|
+
...init.headers,
|
|
167
|
+
...await headers({
|
|
168
|
+
method,
|
|
169
|
+
url
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
const first = await send();
|
|
174
|
+
if (first.status !== 401) return first;
|
|
175
|
+
state = null;
|
|
176
|
+
await getToken(true);
|
|
177
|
+
return send();
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
clientId: config.clientId,
|
|
181
|
+
resource: config.resource,
|
|
182
|
+
kid: key.kid,
|
|
183
|
+
getToken,
|
|
184
|
+
headers,
|
|
185
|
+
fetch: authedFetch,
|
|
186
|
+
invalidateToken: () => {
|
|
187
|
+
state = null;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
//#endregion
|
|
193
|
+
export { createDpopProof as n, createMachineClient as r, MachineTokenError as t };
|
|
194
|
+
//# sourceMappingURL=client-C-LdW4gY.js.map
|