@reopt-ai/brandapp-sdk 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +29 -13
  3. package/dist/ai/index.js +4 -3
  4. package/dist/ai-provider/index.js +16 -2
  5. package/dist/auth/index.js +4 -3
  6. package/dist/better-auth/index.d.ts +1 -1
  7. package/dist/better-auth/index.js +35 -24
  8. package/dist/chunk-2LSCQHAU.js +21 -0
  9. package/dist/{chunk-IJOXTBIE.js → chunk-4U4ZPPL4.js} +4 -4
  10. package/dist/{chunk-RBHP7IZF.js → chunk-55KHY5GH.js} +3 -3
  11. package/dist/{chunk-MRQY45U5.js → chunk-C5VTRZWX.js} +21 -28
  12. package/dist/{chunk-2Q654O63.js → chunk-FJUCWXX3.js} +4 -4
  13. package/dist/{chunk-T7YTITRJ.js → chunk-H33OTQEN.js} +3 -3
  14. package/dist/{chunk-O3PUWIDJ.js → chunk-OG7R3UAR.js} +3 -3
  15. package/dist/{chunk-VRNBYSWU.js → chunk-PF24XU54.js} +3 -3
  16. package/dist/{chunk-R5CCGDUH.js → chunk-QN3QD67K.js} +3 -3
  17. package/dist/{chunk-JWXUVQRC.js → chunk-UGBBXCZE.js} +6 -6
  18. package/dist/{chunk-V73GORO3.js → chunk-UVT2E6KD.js} +6 -6
  19. package/dist/{chunk-POLKEOYH.js → chunk-YPLT3RFL.js} +3 -3
  20. package/dist/{chunk-N5JVE4WX.js → chunk-YTKSAWV2.js} +20 -6
  21. package/dist/cms/index.js +10 -6
  22. package/dist/dev/index.d.ts +19 -0
  23. package/dist/dev/index.js +107 -4
  24. package/dist/eav/index.d.ts +1 -1
  25. package/dist/eav/index.js +5 -4
  26. package/dist/{errors-DIAS8Rsl.d.ts → errors-BjDFIyA6.d.ts} +2 -2
  27. package/dist/feedback/index.js +4 -3
  28. package/dist/files/index.js +4 -3
  29. package/dist/index.d.ts +10 -1
  30. package/dist/index.js +14 -13
  31. package/dist/logout/index.d.ts +106 -0
  32. package/dist/logout/index.js +321 -0
  33. package/dist/plans/index.js +4 -3
  34. package/dist/push/index.js +4 -3
  35. package/dist/react/hooks.d.ts +5 -1
  36. package/dist/react/hooks.js +63 -15
  37. package/dist/terms/index.js +4 -3
  38. package/dist/testing/index.d.ts +1 -1
  39. package/dist/webhooks/index.d.ts +6 -3
  40. package/docs/api-reference.md +98 -2
  41. package/docs/dev-server.md +19 -18
  42. package/docs/errors.md +72 -15
  43. package/docs/logout.md +166 -0
  44. package/package.json +5 -1
@@ -20,6 +20,11 @@
20
20
  | `@reopt-ai/brandapp-sdk/testing` | `createTestSDK` for Vitest fixtures |
21
21
  | `@reopt-ai/brandapp-sdk/cms` | CMS posts/post-groups/tags (read-only) + SEO / Sitemap / RSS helpers + `EditorSpec` |
22
22
  | `@reopt-ai/brandapp-sdk/terms` | Terms list (with `contentRich`), consent, withdraw |
23
+ | `@reopt-ai/brandapp-sdk/plans` | Plan catalog + current plan + hosted checkout (subscribe/pay/cancel) |
24
+ | `@reopt-ai/brandapp-sdk/push` | Customer device FCM/APNs token register/unregister/list |
25
+ | `@reopt-ai/brandapp-sdk/feedback` | Customer feedback submission |
26
+ | `@reopt-ai/brandapp-sdk/logout` | OIDC Single Logout — back-channel receiver + RP-initiated end-session |
27
+ | `@reopt-ai/brandapp-sdk/eav/migrate` | EAV schema migration runner (`defineMigration`, `runMigrations`) |
23
28
 
24
29
  ## Core SDK
25
30
 
@@ -43,7 +48,7 @@ const sdk = createReoptSDK({
43
48
  debug?: boolean; // Enable debug logging
44
49
  });
45
50
 
46
- // Returns: { config, ai, auth, cms, eav, files }
51
+ // Returns: { config, ai, auth, cms, eav, feedback, files, plans, push, terms }
47
52
  ```
48
53
 
49
54
  ### Errors
@@ -74,7 +79,14 @@ optional fourth argument for per-call cancellation / timeout overrides:
74
79
 
75
80
  ```typescript
76
81
  import type { FetchOptions } from "@reopt-ai/brandapp-sdk";
77
- // type FetchOptions = { signal?: AbortSignal; timeout?: number };
82
+ // type FetchOptions = {
83
+ // signal?: AbortSignal; // caller cancellation → rejects with CANCELLED
84
+ // // (err.name === "AbortError"), stops retrying
85
+ // timeout?: number; // per-call timeout override (ms)
86
+ // bearerToken?: string; // Bearer instead of Basic for this call
87
+ // idempotent?: boolean; // treat a POST/PATCH read as retryable on 5xx
88
+ // // (never set on a real mutation)
89
+ // };
78
90
  ```
79
91
 
80
92
  ## AI Client (`sdk.ai`)
@@ -481,6 +493,51 @@ const { count } = await sdk.terms.consent({ consents: [...] }, accessToken);
481
493
  const { id } = await sdk.terms.withdraw(consentId, accessToken);
482
494
  ```
483
495
 
496
+ ## Plans Client (`sdk.plans`) — catalog + hosted checkout (3.1+)
497
+
498
+ ```typescript
499
+ import {
500
+ isRequiredTermsError,
501
+ type Plan,
502
+ type CheckoutSession,
503
+ type CurrentPlan,
504
+ } from "@reopt-ai/brandapp-sdk/plans";
505
+
506
+ // Catalog — Basic Auth (or pass an accessToken to use Bearer)
507
+ const plans: Plan[] = await sdk.plans.list();
508
+
509
+ // The current customer's plan / entitlement (Bearer). null if none.
510
+ const current: CurrentPlan | null = await sdk.plans.getMyPlan(accessToken);
511
+
512
+ // Hosted checkout (Bearer). In sandbox mode checkoutUrl is an id.reopt.ai
513
+ // virtual-payment page; redirect the browser there.
514
+ try {
515
+ const checkout: CheckoutSession = await sdk.plans.createCheckout(
516
+ { planId: plans[0].id, successUrl, cancelUrl },
517
+ accessToken,
518
+ );
519
+ redirect(checkout.checkoutUrl!); // → pay, then back to successUrl/cancelUrl
520
+ } catch (e) {
521
+ if (isRequiredTermsError(e)) {
522
+ // collect consent for e.missingTermsIds via sdk.terms, then retry
523
+ } else throw e;
524
+ }
525
+
526
+ // On the return page, confirm the checkout / entitlement:
527
+ const session = await sdk.plans.getCheckout(checkout.checkoutId, accessToken);
528
+ if (session.status === "completed") {
529
+ /* granted */
530
+ }
531
+
532
+ // Cancel the current sandbox subscription (access kept until period end):
533
+ await sdk.plans.cancel(accessToken);
534
+ ```
535
+
536
+ > Live Toss/Paddle checkout is not driven through the SDK yet — `createCheckout`
537
+ > returns HTTP 409 `LIVE_MODE_UNSUPPORTED` when the Brandapp is set to live
538
+ > payments (use the first-party brandfront flow). usage-model meters are
539
+ > read-only metadata.
540
+
484
541
  ## Webhooks
485
542
 
486
543
  ```typescript
@@ -555,3 +612,42 @@ const { data: tags } = useCmsTags(sdk, { groupId? });
555
612
 
556
613
  > **1.8 변경**: `useCreatePost` / `useUpdatePost` / `useDeletePost`는 cms write
557
614
  > 표면 제거에 따라 함께 제거됐다. authoring은 Reopt Studio가 담당한다.
615
+
616
+ ## Logout — OIDC Single Logout (3.2+)
617
+
618
+ Two directions of session-termination interop with reopt. Full guide:
619
+ [`logout.md`](./logout.md).
620
+
621
+ ```typescript
622
+ import {
623
+ createBackchannelLogoutHandler,
624
+ verifyBackchannelLogoutToken,
625
+ buildEndSessionUrl,
626
+ } from "@reopt-ai/brandapp-sdk/logout";
627
+
628
+ // 1) RECEIVE — reopt POSTs a logout_token when it revokes the IdP session.
629
+ // Mount as a Web-standard Request→Response handler (Next.js/Hono/Fetch).
630
+ // app/api/auth/backchannel-logout/route.ts
631
+ export const POST = createBackchannelLogoutHandler({
632
+ onLogout: async ({ sid, sub }) => {
633
+ await revokeSessionsByReoptSid(sid); // end your derived RP sessions (idempotent)
634
+ },
635
+ });
636
+ // Responses: 200 ok · 400 invalid logout_token · 405 non-POST ·
637
+ // 501 onLogout threw (retry) · 503 verification infra unavailable (retry)
638
+ // Signature: Web Crypto Ed25519 (EdDSA), zero external deps. JWKS is fetched
639
+ // from discovery, cached, and force-refetched (throttled) on key rotation.
640
+
641
+ // verify without the HTTP wrapper (custom transport / tests):
642
+ const { sid, sub } = await verifyBackchannelLogoutToken(logoutToken, {
643
+ clientId, // or BRANDAPP_CLIENT_ID
644
+ });
645
+
646
+ // 2) TRIGGER — send the user to reopt's end_session_endpoint (RP-Initiated).
647
+ const url = buildEndSessionUrl({
648
+ idToken: session.idToken, // id_token_hint
649
+ postLogoutRedirectUri: "https://app.example.com/goodbye", // pre-registered
650
+ state: csrfToken,
651
+ });
652
+ redirect(url);
653
+ ```
@@ -53,16 +53,17 @@ const dev = await createDevServer({
53
53
 
54
54
  ### 반환 객체
55
55
 
56
- | 속성/메서드 | 설명 |
57
- | -------------------- | --------------------------------------- |
58
- | `dev.url` | 서버 URL (e.g. `http://localhost:4300`) |
59
- | `dev.port` | 서버 포트 |
60
- | `dev.store` | 인메모리 저장소 (InMemoryStore) |
61
- | `dev.seed(data)` | 엔티티별 레코드 시딩 |
62
- | `dev.reset()` | 전체 초기화 + 스키마 재시딩 |
63
- | `dev.snapshot(path)` | 현재 상태를 JSON 파일로 저장 |
64
- | `dev.restore(path)` | JSON 파일에서 상태 복원 |
65
- | `dev.close()` | 서버 종료 |
56
+ | 속성/메서드 | 설명 |
57
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
58
+ | `dev.url` | 서버 URL (e.g. `http://localhost:4300`) |
59
+ | `dev.port` | 서버 포트 |
60
+ | `dev.store` | 인메모리 저장소 (InMemoryStore) |
61
+ | `dev.seed(data)` | 엔티티별 레코드 시딩 |
62
+ | `dev.reset()` | 전체 초기화 + 스키마 재시딩 |
63
+ | `dev.snapshot(path)` | 현재 상태를 JSON 파일로 저장 |
64
+ | `dev.restore(path)` | JSON 파일에서 상태 복원 |
65
+ | `dev.mintLogoutToken(input)` | dev IdP가 서명한 실 EdDSA `logout_token` 발급 (OIDC Single Logout 핸들러 e2e 테스트용, 상세: [logout.md](./logout.md)) |
66
+ | `dev.close()` | 서버 종료 |
66
67
 
67
68
  ### `seed(data)`
68
69
 
@@ -82,14 +83,14 @@ await dev.seed({
82
83
 
83
84
  ## 지원하는 API
84
85
 
85
- | 모듈 | 엔드포인트 | 동작 |
86
- | --------- | ------------------------------------ | ----------------------------------------------------------- |
87
- | **EAV** | `/api/v1/brandapp/{id}/eav/*` | Entity/Attribute/Record CRUD + 벌크 + 필터링 + 정렬 |
88
- | **Auth** | `/api/v1/brandapp/{id}/auth/adapter` | Better Auth 어댑터 (user/session/account/verification CRUD) |
89
- | **AI** | `/api/v1/brandapp/{id}/ai/*` | Mock 텍스트/이미지 생성, 모델 목록, 크레딧 |
90
- | **Files** | `/api/v1/brandapp/{id}/files/*` | 인메모리 파일 업로드/다운로드/삭제 |
91
- | **CMS** | `/api/v1/brandapp/{id}/cms/*` | Post/PostGroup CRUD |
92
- | **OAuth** | `/api/auth/.well-known/*` | OIDC Discovery + Mock 토큰 발급 |
86
+ | 모듈 | 엔드포인트 | 동작 |
87
+ | --------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
88
+ | **EAV** | `/api/v1/brandapp/{id}/eav/*` | Entity/Attribute/Record CRUD + 벌크 + 필터링 + 정렬 |
89
+ | **Auth** | `/api/v1/brandapp/{id}/auth/adapter` | Better Auth 어댑터 (user/session/account/verification CRUD) |
90
+ | **AI** | `/api/v1/brandapp/{id}/ai/*` | Mock 텍스트/이미지 생성, 모델 목록, 크레딧 |
91
+ | **Files** | `/api/v1/brandapp/{id}/files/*` | 인메모리 파일 업로드/다운로드/삭제 |
92
+ | **CMS** | `/api/v1/brandapp/{id}/cms/*` | Post/PostGroup CRUD |
93
+ | **OAuth** | `/api/auth/.well-known/*`, `/api/auth/{token,jwks,oauth2/end-session}` | OIDC Discovery + EdDSA로 서명된 mock `id_token` + JWKS + RP-initiated end-session (faithful OIDC mock) |
93
94
 
94
95
  ---
95
96
 
package/docs/errors.md CHANGED
@@ -6,21 +6,40 @@ All SDK errors extend `ReoptSDKError` and include a `.diagnostic` property with
6
6
 
7
7
  ### General
8
8
 
9
- | Error Class | Status | Code | When |
10
- | -------------------- | ------ | --------------------- | ---------------------------------------- |
11
- | `AuthError` | 401 | `AUTH_ERROR` | Invalid clientId/clientSecret |
12
- | `BadRequestError` | 400 | `BAD_REQUEST` | Malformed request (body / params) |
13
- | `ForbiddenError` | 403 | `FORBIDDEN` | No permission for the resource |
14
- | `NotFoundError` | 404 | `NOT_FOUND` | Resource does not exist (or was deleted) |
15
- | `ConflictError` | 409 | `CONFLICT` | State conflict (duplicate key, race) |
16
- | `ValidationError` | 422 | `VALIDATION_ERROR` | Field-level validation failure |
17
- | `RateLimitError` | 429 | `RATE_LIMIT` | Too many requests |
18
- | `CreditLimitError` | 402 | `CREDIT_LIMIT` | AI credit balance exhausted |
19
- | `ModelAccessError` | 403 | `MODEL_ACCESS_DENIED` | Model not available for this plan tier |
20
- | `ModelNotFoundError` | 404 | `MODEL_NOT_FOUND` | Unknown model id (typo / retired) |
21
- | `ContentFilterError` | 422 | `CONTENT_FILTER` | Blocked by moderation policy |
22
- | `ServerError` | 500 | `SERVER_ERROR` | Internal server error |
23
- | `ReoptSDKError` | varies | varies | Base class (other / future API errors) |
9
+ | Error Class | Status | Code | When |
10
+ | -------------------- | ------ | --------------------- | ------------------------------------------------------------ |
11
+ | `AuthError` | 401 | `AUTH_ERROR` | Invalid clientId/clientSecret |
12
+ | `BadRequestError` | 400 | `BAD_REQUEST` | Malformed request (body / params) |
13
+ | `ForbiddenError` | 403 | `FORBIDDEN` | No permission for the resource |
14
+ | `NotFoundError` | 404 | `NOT_FOUND` | Resource does not exist (or was deleted) |
15
+ | `ConflictError` | 409 | `CONFLICT` | State conflict (duplicate key, race) |
16
+ | `ValidationError` | 422 | `VALIDATION_ERROR` | Field-level validation failure |
17
+ | `RateLimitError` | 429 | `RATE_LIMIT` | Too many requests |
18
+ | `CreditLimitError` | 402 | `CREDIT_LIMIT` | AI credit balance exhausted |
19
+ | `ModelAccessError` | 403 | `MODEL_ACCESS_DENIED` | Model not available for this plan tier |
20
+ | `ModelNotFoundError` | 404 | `MODEL_NOT_FOUND` | Unknown model id (typo / retired) |
21
+ | `ContentFilterError` | 422 | `CONTENT_FILTER` | Blocked by moderation policy |
22
+ | `RequiredTermsError` | 422 | `REQUIRED_TERMS` | Plan checkout needs terms consent ([below](#required_terms)) |
23
+ | `ServerError` | 500 | `SERVER_ERROR` | Internal server error |
24
+ | `ReoptSDKError` | varies | varies | Base class (other / future API errors) |
25
+
26
+ `RequiredTermsError` (thrown by `sdk.plans.createCheckout`) carries
27
+ `missingTermsIds: string[]`; guard with `isRequiredTermsError(e)`.
28
+
29
+ ### Logout (OIDC Single Logout — `@reopt-ai/brandapp-sdk/logout`)
30
+
31
+ Raised by `verifyBackchannelLogoutToken` / `createBackchannelLogoutHandler`
32
+ (plain `ReoptSDKError` with a code — no dedicated subclass):
33
+
34
+ | Status | Code | When |
35
+ | ------ | --------------------------------- | --------------------------------------------------------------------- |
36
+ | 400 | `invalid_logout_token` | logout_token failed validation (bad signature / claims / structure) |
37
+ | 503 | `logout_verification_unavailable` | discovery/JWKS temporarily unreachable — **retryable**, not the token |
38
+
39
+ The handler maps `invalid_logout_token` → HTTP 400 and
40
+ `logout_verification_unavailable` → HTTP 503 (so the IdP retries instead of
41
+ treating a transient JWKS outage as a permanently bad token). See
42
+ [logout.md](./logout.md) for the full response contract.
24
43
 
25
44
  > Every subclass sets `error.name` to its own class name (e.g. `"AuthError"`,
26
45
  > `"RateLimitError"`, `"CreditLimitError"`) so log aggregation / Sentry grouping
@@ -203,6 +222,29 @@ type ErrorDiagnostic = {
203
222
  - **Fix**: Check `error.fieldErrors` for per-field details
204
223
  - **Example**: `error.toFieldMap()` returns `{ email: "Invalid email format" }`
205
224
 
225
+ <a id="required_terms"></a>
226
+
227
+ ### REQUIRED_TERMS: plan checkout needs terms consent (422)
228
+
229
+ - **Cause**: `sdk.plans.createCheckout` was called for a plan whose required
230
+ terms the customer has not yet consented to.
231
+ - **Fix**: read `error.missingTermsIds`, collect consent via `sdk.terms.list()`
232
+ \+ `sdk.terms.consent()`, then retry `createCheckout`.
233
+ - **Class**: `RequiredTermsError` — guard with `isRequiredTermsError(e)`; carries
234
+ `missingTermsIds: string[]`.
235
+
236
+ ```ts
237
+ import { isRequiredTermsError } from "@reopt-ai/brandapp-sdk";
238
+
239
+ try {
240
+ await sdk.plans.createCheckout({ planId, successUrl, cancelUrl }, token);
241
+ } catch (e) {
242
+ if (isRequiredTermsError(e)) {
243
+ // show consent UI for e.missingTermsIds, then retry
244
+ } else throw e;
245
+ }
246
+ ```
247
+
206
248
  ### FORBIDDEN: `Forbidden` / `Model tier not available` (403)
207
249
 
208
250
  - **Cause**: No permission for the resource — e.g. the requested model
@@ -272,6 +314,21 @@ type ErrorDiagnostic = {
272
314
  - **Retries**: 5xx/network/timeout failures are retried only for idempotent
273
315
  methods (GET/HEAD/PUT/DELETE) by default; POST/PATCH are not retried to avoid
274
316
  duplicate side effects (opt in via `retryNonIdempotent`). 429 is always retried.
317
+ A single read tunneled over POST can opt into retry per-call with the
318
+ `idempotent` fetch option (the Better Auth adapter uses this for
319
+ `findOne`/`findMany`/`count`).
320
+ - **Note**: `TIMEOUT` is reserved for the internal wall-clock/idle deadline. A
321
+ request you cancel via your own `AbortSignal` rejects with a distinct
322
+ `CANCELLED` error whose `name` is `"AbortError"` (the standard web
323
+ cancellation convention) and stops retrying immediately.
324
+
325
+ ### CANCELLED: caller aborted the request (0)
326
+
327
+ - **Cause**: The `AbortSignal` you passed as `FetchOptions.signal` was aborted
328
+ (e.g. React component unmount, request supersession).
329
+ - **Detect**: `err.name === "AbortError"` (or `err.code === "CANCELLED"`).
330
+ - **Note**: Distinct from `TIMEOUT` (408) — a caller cancel is not a server
331
+ timeout, and the retry loop breaks on it rather than burning retries.
275
332
 
276
333
  ## Debug Mode
277
334
 
package/docs/logout.md ADDED
@@ -0,0 +1,166 @@
1
+ # Logout — Single Logout across reopt and your app
2
+
3
+ `@reopt-ai/brandapp-sdk/logout` implements OIDC **Single Logout** so a session
4
+ can end in both directions between reopt (the Identity Provider) and your app
5
+ (a Relying Party):
6
+
7
+ - **Back-Channel Logout (receive)** — when a user logs out of reopt (or an admin
8
+ bans/deletes them, or another device is signed out), reopt notifies your app
9
+ server-to-server so you can end the matching session in your app.
10
+ - **RP-Initiated Logout (trigger)** — when a user logs out of **your** app, you
11
+ can optionally send them through reopt's `end_session_endpoint` to end their
12
+ reopt session too (and every session derived from it).
13
+
14
+ No external dependencies — signature verification uses Web Crypto (Ed25519).
15
+
16
+ > **Runtime**: Back-Channel Logout verification needs Ed25519 in Web Crypto —
17
+ > available on Node 20+, Deno, Cloudflare Workers, and modern browsers. Since the
18
+ > receiver runs server-side, any Node 20+ host (Firebase Functions, Vercel
19
+ > Functions, etc.) works.
20
+
21
+ ## 1. Receive Back-Channel Logout
22
+
23
+ Mount a handler at a stable URL and register that URL with reopt as your OAuth
24
+ client's `backchannel_logout_uri` (ask your reopt contact, or set it in Studio →
25
+ BrandApp → OAuth). reopt POSTs a signed `logout_token` there whenever the
26
+ originating reopt session is revoked.
27
+
28
+ ```ts
29
+ // Next.js App Router — app/api/auth/backchannel-logout/route.ts
30
+ import { createBackchannelLogoutHandler } from "@reopt-ai/brandapp-sdk/logout";
31
+
32
+ export const POST = createBackchannelLogoutHandler({
33
+ // Revoke every local session derived from this reopt session id.
34
+ onLogout: async ({ sid, sub }) => {
35
+ await db.sessions.deleteMany({ where: { reoptSid: sid } });
36
+ },
37
+ });
38
+ ```
39
+
40
+ The handler is a standard `(Request) => Promise<Response>`, so it also works with
41
+ Hono, plain Fetch servers, or any framework that speaks the Web `Request`/`Response`
42
+ API.
43
+
44
+ ### Wiring the `sid`
45
+
46
+ To end the right sessions, store the reopt **session id (`sid`)** when the user
47
+ logs in. It's the `sid` claim of the `id_token` you receive from the OAuth code
48
+ exchange. Persist it on your session row so `onLogout({ sid })` can find and
49
+ delete the matching sessions.
50
+
51
+ ```ts
52
+ // at login, after code exchange:
53
+ const { sid } = decodeIdToken(tokenResponse.id_token);
54
+ await db.sessions.create({ userId, reoptSid: sid, ... });
55
+ ```
56
+
57
+ ### Verify manually
58
+
59
+ If you need the claims without the HTTP wrapper (custom transport, testing):
60
+
61
+ ```ts
62
+ import { verifyBackchannelLogoutToken } from "@reopt-ai/brandapp-sdk/logout";
63
+
64
+ const { sid, sub } = await verifyBackchannelLogoutToken(logoutToken, {
65
+ clientId: process.env.BRANDAPP_CLIENT_ID,
66
+ });
67
+ ```
68
+
69
+ It throws `ReoptSDKError` (`code: "invalid_logout_token"`) on any failure:
70
+ bad signature, wrong issuer/audience, missing `backchannel-logout` event,
71
+ a forbidden `nonce`, a stale `iat`, or a non-`EdDSA` algorithm.
72
+
73
+ ### Response contract
74
+
75
+ | Situation | Status |
76
+ | ----------------------------------------------------------- | ------ |
77
+ | Valid token, `onLogout` succeeded | `200` |
78
+ | Missing/invalid `logout_token`, verification failed | `400` |
79
+ | Non-POST | `405` |
80
+ | `onLogout` threw (make it idempotent — reopt retries) | `501` |
81
+ | Verification infra (discovery/JWKS) temporarily unavailable | `503` |
82
+
83
+ All responses carry `Cache-Control: no-store` per the spec.
84
+
85
+ The `503` (code `logout_verification_unavailable`) is returned **instead of
86
+ `400`** when the reopt discovery/JWKS endpoint is briefly unreachable (e.g. a
87
+ deploy) — a transient infra failure is not a bad token, so the IdP is told the
88
+ request is retryable rather than permanently invalid.
89
+
90
+ Signatures are verified with Web Crypto **Ed25519** (zero external deps). The
91
+ JWKS is fetched from discovery and cached; on a signature miss it is force-
92
+ refetched once to survive key rotation, but that forced refetch is **throttled
93
+ per `jwks_uri`** and concurrent refetches are coalesced, so a flood of forged
94
+ tokens to this public endpoint cannot reflect load onto the shared JWKS
95
+ endpoint. Discovery/JWKS fetches carry a timeout and fail closed.
96
+
97
+ ## 2. Trigger RP-Initiated Logout
98
+
99
+ When the user logs out of your app, send them to reopt's `end_session_endpoint`
100
+ to also end the reopt session. Pass the `id_token` you got at login as the hint.
101
+
102
+ ```ts
103
+ import { buildEndSessionUrl } from "@reopt-ai/brandapp-sdk/logout";
104
+
105
+ const url = buildEndSessionUrl({
106
+ idToken: session.reoptIdToken, // id_token from login
107
+ postLogoutRedirectUri: "https://app.example.com/goodbye",
108
+ state: csrfToken, // optional, echoed back
109
+ });
110
+
111
+ // end your local session first, then:
112
+ redirect(url);
113
+ ```
114
+
115
+ For reopt to redirect back afterwards, `postLogoutRedirectUri` **must be
116
+ pre-registered** on your OAuth client's `post_logout_redirect_uris`. If it isn't
117
+ registered, reopt still ends the session but won't redirect.
118
+
119
+ ## How it fits together
120
+
121
+ ```
122
+ User logs out of reopt (or ban / delete / device sign-out)
123
+ │
124
+ ▼
125
+ reopt revokes the IdP session, then for each client with a
126
+ backchannel_logout_uri that holds tokens from that session:
127
+ │ POST logout_token (EdDSA JWT: aud, sid, events, …)
128
+ ▼
129
+ your handler → verify → onLogout({ sid }) → delete local sessions
130
+
131
+ User logs out of your app
132
+ │ redirect to buildEndSessionUrl({ idToken })
133
+ ▼
134
+ reopt end_session_endpoint → revokes that IdP session (cascades to all
135
+ derived sessions/tokens) → redirects to post_logout_redirect_uri
136
+ ```
137
+
138
+ ## Testing against the dev server
139
+
140
+ The in-memory dev server (`@reopt-ai/brandapp-sdk/dev`) is a faithful OIDC mock:
141
+ it signs real EdDSA tokens, serves its public key at `/api/auth/jwks`, and mounts
142
+ `/api/auth/oauth2/end-session`. Point your logout verifier at `dev.url` and mint a
143
+ `logout_token` to exercise your handler end-to-end — no reopt server required.
144
+
145
+ ```ts
146
+ import { createDevServer } from "@reopt-ai/brandapp-sdk/dev";
147
+
148
+ const dev = await createDevServer({ brandappId: "dev" });
149
+
150
+ const logoutToken = await dev.mintLogoutToken({
151
+ clientId: "my-brandapp",
152
+ sessionId: "idp-session-1",
153
+ userId: "user-1",
154
+ });
155
+
156
+ // Drive your handler with a form POST carrying logout_token=<token>, or verify
157
+ // directly — both fetch discovery + JWKS from the dev server:
158
+ const res = await POST(
159
+ new Request("http://localhost/api/auth/backchannel-logout", {
160
+ method: "POST",
161
+ headers: { "content-type": "application/x-www-form-urlencoded" },
162
+ body: new URLSearchParams({ logout_token: logoutToken }),
163
+ }),
164
+ );
165
+ // (configure the handler with idBaseUrl: dev.url, clientId: "my-brandapp")
166
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reopt-ai/brandapp-sdk",
3
- "version": "3.1.0",
3
+ "version": "3.3.0",
4
4
  "description": "Reopt Brandapp SDK — Better Auth adapter, OAuth login, and EAV client",
5
5
  "author": "Reopt",
6
6
  "license": "MIT",
@@ -57,6 +57,10 @@
57
57
  "types": "./dist/feedback/index.d.ts",
58
58
  "import": "./dist/feedback/index.js"
59
59
  },
60
+ "./logout": {
61
+ "types": "./dist/logout/index.d.ts",
62
+ "import": "./dist/logout/index.js"
63
+ },
60
64
  "./files": {
61
65
  "types": "./dist/files/index.d.ts",
62
66
  "import": "./dist/files/index.js"