@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
@@ -1,4 +1,5 @@
1
- import { validateConfig, resolveIdBaseUrl, resolveBaseUrl, createAuthHeader, SDK_VERSION, mapHttpStatusToError, ReoptSDKError, RateLimitError, ServerError } from './chunk-MRQY45U5.js';
1
+ import { createAuthHeader } from './chunk-2LSCQHAU.js';
2
+ import { validateConfig, resolveIdBaseUrl, resolveBaseUrl, SDK_VERSION, mapHttpStatusToError, ReoptSDKError, RateLimitError, ServerError } from './chunk-C5VTRZWX.js';
2
3
 
3
4
  // src/core/debug.ts
4
5
  function resolveLevel(configDebug) {
@@ -271,7 +272,7 @@ var BaseHttpClient = class {
271
272
  const url = `${this.baseUrl}${path}`;
272
273
  const requestId = crypto.randomUUID();
273
274
  const timeout = options?.timeout ?? this.timeout;
274
- const methodRetryable = this.retryNonIdempotent || isIdempotentMethod(method);
275
+ const methodRetryable = this.retryNonIdempotent || isIdempotentMethod(method) || options?.idempotent === true;
275
276
  let lastError;
276
277
  this.debug.request(method, url, requestId, body);
277
278
  const startTime = Date.now();
@@ -380,6 +381,16 @@ var BaseHttpClient = class {
380
381
  lastError = error;
381
382
  canRetry = methodRetryable;
382
383
  } else if (error instanceof Error && error.name === "AbortError") {
384
+ if (externalSignal?.aborted) {
385
+ const cancelled = new ReoptSDKError(
386
+ "Request aborted by caller",
387
+ 0,
388
+ "CANCELLED",
389
+ ctx
390
+ );
391
+ cancelled.name = "AbortError";
392
+ throw cancelled;
393
+ }
383
394
  lastError = new ReoptSDKError(
384
395
  "Request timed out",
385
396
  408,
@@ -410,9 +421,12 @@ var BaseHttpClient = class {
410
421
  }
411
422
  this.debug.error(method, url, lastError?.message ?? "unknown", requestId);
412
423
  if (lastError instanceof ReoptSDKError && !lastError.context?.requestId) {
413
- Object.assign(lastError.context ?? {}, { requestId });
424
+ lastError.context = {
425
+ ...lastError.context ?? {},
426
+ requestId
427
+ };
414
428
  }
415
- throw lastError ?? new ServerError("All retry attempts failed");
429
+ throw lastError ?? new ServerError("All retry attempts failed", { requestId });
416
430
  }
417
431
  };
418
432
  function parseFieldErrors(body) {
@@ -445,5 +459,5 @@ function parseFieldErrors(body) {
445
459
  }
446
460
 
447
461
  export { BaseHttpClient, parseFieldErrors };
448
- //# sourceMappingURL=chunk-N5JVE4WX.js.map
449
- //# sourceMappingURL=chunk-N5JVE4WX.js.map
462
+ //# sourceMappingURL=chunk-YTKSAWV2.js.map
463
+ //# sourceMappingURL=chunk-YTKSAWV2.js.map
package/dist/cms/index.js CHANGED
@@ -1,7 +1,8 @@
1
- export { createReoptCmsClient } from '../chunk-V73GORO3.js';
2
- import '../chunk-VRNBYSWU.js';
3
- import '../chunk-N5JVE4WX.js';
4
- import '../chunk-MRQY45U5.js';
1
+ export { createReoptCmsClient } from '../chunk-UVT2E6KD.js';
2
+ import '../chunk-PF24XU54.js';
3
+ import '../chunk-YTKSAWV2.js';
4
+ import '../chunk-2LSCQHAU.js';
5
+ import '../chunk-C5VTRZWX.js';
5
6
 
6
7
  // src/cms/helpers.ts
7
8
  function joinUrl(siteUrl, path) {
@@ -13,11 +14,14 @@ function postUrl(post, opts) {
13
14
  const basePath = opts.basePath ?? "/blog";
14
15
  return joinUrl(opts.siteUrl, `${basePath}/${post.slug}`);
15
16
  }
17
+ function stripXmlInvalidChars(input) {
18
+ return input.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "");
19
+ }
16
20
  function escapeXml(input) {
17
- return input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
21
+ return stripXmlInvalidChars(input).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
18
22
  }
19
23
  function cdataSafe(input) {
20
- return input.replace(/]]>/g, "]]]]><![CDATA[>");
24
+ return stripXmlInvalidChars(input).replace(/]]>/g, "]]]]><![CDATA[>");
21
25
  }
22
26
  function toMetadata(post, opts) {
23
27
  const url = postUrl(post, opts);
@@ -252,6 +252,17 @@ declare class InMemoryStore {
252
252
  clear(): void;
253
253
  }
254
254
 
255
+ type MintLogoutTokenInput = {
256
+ /** The RP's OAuth client_id — becomes the logout_token `aud`. */
257
+ clientId: string;
258
+ /** The IdP session id being revoked — becomes `sid` (RP session-termination key). */
259
+ sessionId: string;
260
+ /** Optional subject (`sub`). */
261
+ userId?: string;
262
+ /** Override `iat` (epoch ms) — for testing max-age/expiry branches. */
263
+ issuedAtMs?: number;
264
+ };
265
+
255
266
  /**
256
267
  * Markdown → EditorSpec converter for dev seed workflows.
257
268
  *
@@ -501,6 +512,14 @@ type DevServer = {
501
512
  snapshot: (path: string) => Promise<void>;
502
513
  /** Restore state from a JSON file */
503
514
  restore: (path: string) => Promise<void>;
515
+ /**
516
+ * Mint a spec-compliant `logout_token` signed by the dev IdP, so you can
517
+ * exercise a `createBackchannelLogoutHandler` end-to-end against this server
518
+ * (which serves the matching JWKS at `/api/auth/jwks`). Point the SDK's logout
519
+ * verifier at `dev.url` as `idBaseUrl`. Rejects if the runtime lacks Ed25519
520
+ * Web Crypto (Node 20+).
521
+ */
522
+ mintLogoutToken: (input: MintLogoutTokenInput) => Promise<string>;
504
523
  /** Stop the dev server */
505
524
  close: () => Promise<void>;
506
525
  };
package/dist/dev/index.js CHANGED
@@ -2392,6 +2392,57 @@ function createTermsRoutes(store, brandappId) {
2392
2392
  return app;
2393
2393
  }
2394
2394
 
2395
+ // src/dev/oidc-signing.ts
2396
+ var BACKCHANNEL_LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
2397
+ function base64UrlEncode(bytes) {
2398
+ let binary = "";
2399
+ for (let i = 0; i < bytes.length; i++)
2400
+ binary += String.fromCharCode(bytes[i]);
2401
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2402
+ }
2403
+ function encodeSegment(obj) {
2404
+ return base64UrlEncode(new TextEncoder().encode(JSON.stringify(obj)));
2405
+ }
2406
+ async function createDevOidcSigning() {
2407
+ const keyPair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
2408
+ "sign",
2409
+ "verify"
2410
+ ]);
2411
+ const kid = "dev-ed25519";
2412
+ const jwk = await crypto.subtle.exportKey(
2413
+ "jwk",
2414
+ keyPair.publicKey
2415
+ );
2416
+ const publicJwk = { ...jwk, kid, alg: "EdDSA", use: "sig" };
2417
+ const sign = async (payload) => {
2418
+ const header = { alg: "EdDSA", typ: "JWT", kid };
2419
+ const signingInput = `${encodeSegment(header)}.${encodeSegment(payload)}`;
2420
+ const signature = new Uint8Array(
2421
+ await crypto.subtle.sign(
2422
+ { name: "Ed25519" },
2423
+ keyPair.privateKey,
2424
+ new TextEncoder().encode(signingInput)
2425
+ )
2426
+ );
2427
+ return `${signingInput}.${base64UrlEncode(signature)}`;
2428
+ };
2429
+ return { kid, publicJwk, sign };
2430
+ }
2431
+ var LOGOUT_TOKEN_TTL_SECONDS = 2 * 60;
2432
+ async function mintDevLogoutToken(signing, issuer, jti, input) {
2433
+ const nowSeconds = Math.floor((input.issuedAtMs ?? Date.now()) / 1e3);
2434
+ return signing.sign({
2435
+ iss: issuer,
2436
+ aud: input.clientId,
2437
+ iat: nowSeconds,
2438
+ exp: nowSeconds + LOGOUT_TOKEN_TTL_SECONDS,
2439
+ jti,
2440
+ events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
2441
+ sid: input.sessionId,
2442
+ ...input.userId ? { sub: input.userId } : {}
2443
+ });
2444
+ }
2445
+
2395
2446
  // src/dev/index.ts
2396
2447
  function seedSchema(store, brandappId, schema) {
2397
2448
  for (const [key, entityDef] of Object.entries(schema.entities)) {
@@ -2702,6 +2753,17 @@ async function createDevServer(options = {}) {
2702
2753
  </html>`);
2703
2754
  });
2704
2755
  app.get("/health", (c) => c.json({ ok: true, mode: "dev" }));
2756
+ let devSigning = null;
2757
+ try {
2758
+ devSigning = await createDevOidcSigning();
2759
+ } catch {
2760
+ devSigning = null;
2761
+ if (verbose) {
2762
+ console.warn(
2763
+ "[reopt-dev] Ed25519 Web Crypto unavailable \u2014 OIDC discovery omits JWKS/EdDSA/end-session (id_token stays a mock literal)."
2764
+ );
2765
+ }
2766
+ }
2705
2767
  app.get("/api/auth/.well-known/openid-configuration", (c) => {
2706
2768
  const baseUrl = `http://localhost:${actualPort}`;
2707
2769
  return c.json({
@@ -2709,26 +2771,59 @@ async function createDevServer(options = {}) {
2709
2771
  authorization_endpoint: `${baseUrl}/api/auth/authorize`,
2710
2772
  token_endpoint: `${baseUrl}/api/auth/token`,
2711
2773
  userinfo_endpoint: `${baseUrl}/api/auth/userinfo`,
2712
- jwks_uri: `${baseUrl}/api/auth/jwks`,
2713
2774
  response_types_supported: ["code"],
2714
2775
  subject_types_supported: ["public"],
2715
- id_token_signing_alg_values_supported: ["RS256"],
2716
2776
  scopes_supported: ["openid", "profile", "email"],
2717
2777
  token_endpoint_auth_methods_supported: [
2718
2778
  "client_secret_basic",
2719
2779
  "client_secret_post"
2720
2780
  ],
2721
2781
  grant_types_supported: ["authorization_code", "refresh_token"],
2722
- code_challenge_methods_supported: ["S256"]
2782
+ code_challenge_methods_supported: ["S256"],
2783
+ // Signing-backed capabilities: advertised only when the mock can actually
2784
+ // serve them (Ed25519 keypair up + JWKS/end-session routes mounted).
2785
+ ...devSigning ? {
2786
+ jwks_uri: `${baseUrl}/api/auth/jwks`,
2787
+ end_session_endpoint: `${baseUrl}/api/auth/oauth2/end-session`,
2788
+ id_token_signing_alg_values_supported: ["EdDSA"]
2789
+ } : {}
2723
2790
  });
2724
2791
  });
2792
+ app.get("/api/auth/jwks", (c) => {
2793
+ return c.json({ keys: devSigning ? [devSigning.publicJwk] : [] });
2794
+ });
2795
+ app.get("/api/auth/oauth2/end-session", (c) => {
2796
+ const redirectUri = c.req.query("post_logout_redirect_uri");
2797
+ const state = c.req.query("state");
2798
+ if (redirectUri) {
2799
+ try {
2800
+ const target = new URL(redirectUri);
2801
+ if (state) target.searchParams.set("state", state);
2802
+ return c.redirect(target.toString(), 302);
2803
+ } catch {
2804
+ return c.json({ error: "invalid_request" }, 400);
2805
+ }
2806
+ }
2807
+ return c.json({ ok: true, loggedOut: true });
2808
+ });
2725
2809
  app.post("/api/auth/token", async (c) => {
2810
+ const baseUrl = `http://localhost:${actualPort}`;
2811
+ const nowSeconds = Math.floor(Date.now() / 1e3);
2812
+ const idToken = devSigning ? await devSigning.sign({
2813
+ iss: baseUrl,
2814
+ sub: "dev-user-id",
2815
+ aud: "dev-client",
2816
+ iat: nowSeconds,
2817
+ exp: nowSeconds + 3600,
2818
+ email: "dev@example.com",
2819
+ email_verified: true
2820
+ }) : "dev-id-token";
2726
2821
  return c.json({
2727
2822
  access_token: `dev-access-token-${store.generateId()}`,
2728
2823
  token_type: "Bearer",
2729
2824
  expires_in: 3600,
2730
2825
  refresh_token: `dev-refresh-token-${store.generateId()}`,
2731
- id_token: "dev-id-token",
2826
+ id_token: idToken,
2732
2827
  scope: "openid profile email"
2733
2828
  });
2734
2829
  });
@@ -3049,6 +3144,14 @@ async function createDevServer(options = {}) {
3049
3144
  store.fromJSON(json);
3050
3145
  persistIfNeeded();
3051
3146
  },
3147
+ async mintLogoutToken(input) {
3148
+ if (!devSigning) {
3149
+ throw new Error(
3150
+ "[@reopt-ai/brandapp-sdk/dev] mintLogoutToken requires Ed25519 Web Crypto (Node 20+), which is unavailable in this runtime."
3151
+ );
3152
+ }
3153
+ return mintDevLogoutToken(devSigning, url, store.generateId(), input);
3154
+ },
3052
3155
  async close() {
3053
3156
  if (persistTimer) clearTimeout(persistTimer);
3054
3157
  if (dataPath) {
@@ -3,7 +3,7 @@ export { c as createReoptEavClient } from '../client-BkcO-0C2.js';
3
3
  import { a as AttributeFilter } from '../config-CtxyJsDR.js';
4
4
  export { b as AttributeFilterOperator, d as BulkUpdateItem, C as CountRecordsQuery, e as CreateAttributeInput, f as CreateEntityInput, g as CreateRecordInput, i as DeleteWhereInput, E as EavAttribute, j as EavAttributeOption, k as EavDataType, l as EavEntity, m as EavRecord, n as EavSchemaLinkedTo, o as EavValidation, L as ListRecordsQuery, P as PaginatedResponse, q as ReoptSDKConfig, U as UpdateAttributeInput, r as UpdateEntityInput, s as UpdateRecordInput, t as UpsertRecordInput, u as UpsertRecordResult } from '../config-CtxyJsDR.js';
5
5
  export { E as EntityClient, T as TypedEavRecord } from '../typed-client-BxOVIiMU.js';
6
- export { a as AuthUserNotFoundError, b as AuthUserRecordExistsError, D as DuplicateAuthUserError, L as LimitExceededError } from '../errors-DIAS8Rsl.js';
6
+ export { a as AuthUserNotFoundError, b as AuthUserRecordExistsError, D as DuplicateAuthUserError, L as LimitExceededError } from '../errors-BjDFIyA6.js';
7
7
 
8
8
  /**
9
9
  * Runtime drift check between a deployed bundle and the live server schema
package/dist/eav/index.js CHANGED
@@ -1,7 +1,8 @@
1
- export { createReoptEavClient } from '../chunk-IJOXTBIE.js';
2
- import '../chunk-VRNBYSWU.js';
3
- import '../chunk-N5JVE4WX.js';
4
- export { AuthUserNotFoundError, AuthUserRecordExistsError, DuplicateAuthUserError, LimitExceededError } from '../chunk-MRQY45U5.js';
1
+ export { createReoptEavClient } from '../chunk-4U4ZPPL4.js';
2
+ import '../chunk-PF24XU54.js';
3
+ import '../chunk-YTKSAWV2.js';
4
+ import '../chunk-2LSCQHAU.js';
5
+ export { AuthUserNotFoundError, AuthUserRecordExistsError, DuplicateAuthUserError, LimitExceededError } from '../chunk-C5VTRZWX.js';
5
6
 
6
7
  // src/eav/verify.ts
7
8
  async function verifyEavSchema(input) {
@@ -31,10 +31,10 @@ declare class AuthError extends ReoptSDKError {
31
31
  constructor(message?: string, context?: ReoptSDKErrorContext);
32
32
  }
33
33
  declare class RateLimitError extends ReoptSDKError {
34
- constructor(message?: string, retryAfterMs?: number);
34
+ constructor(message?: string, retryAfterMs?: number, context?: ReoptSDKErrorContext);
35
35
  }
36
36
  declare class ServerError extends ReoptSDKError {
37
- constructor(message?: string);
37
+ constructor(message?: string, context?: ReoptSDKErrorContext);
38
38
  }
39
39
  /** AI 크레딧 잔액 부족 (HTTP 402). */
40
40
  declare class CreditLimitError extends ReoptSDKError {
@@ -1,5 +1,6 @@
1
- export { ReoptFeedbackClient, createReoptFeedbackClient } from '../chunk-RBHP7IZF.js';
2
- import '../chunk-N5JVE4WX.js';
3
- import '../chunk-MRQY45U5.js';
1
+ export { ReoptFeedbackClient, createReoptFeedbackClient } from '../chunk-55KHY5GH.js';
2
+ import '../chunk-YTKSAWV2.js';
3
+ import '../chunk-2LSCQHAU.js';
4
+ import '../chunk-C5VTRZWX.js';
4
5
  //# sourceMappingURL=index.js.map
5
6
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,8 @@
1
- export { ReoptFileClient, createReoptFileClient } from '../chunk-JWXUVQRC.js';
1
+ export { ReoptFileClient, createReoptFileClient } from '../chunk-UGBBXCZE.js';
2
2
  import '../chunk-F7BXBTZI.js';
3
- import '../chunk-N5JVE4WX.js';
4
- import '../chunk-MRQY45U5.js';
3
+ import '../chunk-YTKSAWV2.js';
4
+ import '../chunk-2LSCQHAU.js';
5
+ import '../chunk-C5VTRZWX.js';
5
6
 
6
7
  // src/files/helpers.ts
7
8
  var REOPT_IMAGE_REMOTE_PATTERNS = [
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import { a as ListPostsQuery, C as CmsPaginatedResponse, P as Post, c as PostDet
9
9
  import { R as ReoptAuthClient } from './client-DttyeM_h.js';
10
10
  import { ReoptAiClient } from './ai/index.js';
11
11
  export { AgentInfo, ChatMessage, CompletionOptions, CompletionResult, CreditInfo, FinishReason, ImageGenerateOptions, ImageGenerateResult, MessageRole, ModelInfo, StreamDoneData, StreamEvent } from './ai/index.js';
12
- export { A as AuthError, a as AuthUserNotFoundError, b as AuthUserRecordExistsError, B as BadRequestError, C as ConflictError, c as ContentFilterError, d as CreditLimitError, D as DuplicateAuthUserError, E as ErrorDiagnostic, F as FieldError, e as ForbiddenError, L as LimitExceededError, M as ModelAccessError, f as ModelNotFoundError, N as NotFoundError, R as RateLimitError, g as ReoptSDKError, h as ReoptSDKErrorContext, i as RequiredTermsError, S as ServerError, V as ValidationError, j as isCreditLimitError, k as isModelAccessError, l as isReoptSDKError, m as isRequiredTermsError, n as isValidationError, o as mapHttpStatusToError } from './errors-DIAS8Rsl.js';
12
+ export { A as AuthError, a as AuthUserNotFoundError, b as AuthUserRecordExistsError, B as BadRequestError, C as ConflictError, c as ContentFilterError, d as CreditLimitError, D as DuplicateAuthUserError, E as ErrorDiagnostic, F as FieldError, e as ForbiddenError, L as LimitExceededError, M as ModelAccessError, f as ModelNotFoundError, N as NotFoundError, R as RateLimitError, g as ReoptSDKError, h as ReoptSDKErrorContext, i as RequiredTermsError, S as ServerError, V as ValidationError, j as isCreditLimitError, k as isModelAccessError, l as isReoptSDKError, m as isRequiredTermsError, n as isValidationError, o as mapHttpStatusToError } from './errors-BjDFIyA6.js';
13
13
  import { E as EntityClient } from './typed-client-BxOVIiMU.js';
14
14
  export { T as TypedEavRecord } from './typed-client-BxOVIiMU.js';
15
15
  import './types-DskYLVb8.js';
@@ -26,6 +26,15 @@ type FetchOptions = {
26
26
  * than client credentials.
27
27
  */
28
28
  bearerToken?: string;
29
+ /**
30
+ * Treat this request as idempotent for retry purposes even when the HTTP
31
+ * method is POST/PATCH. Use for read-style operations tunneled over POST
32
+ * (e.g. the Better Auth adapter's `findOne`/`findMany`/`count`) so transient
33
+ * 5xx / network / timeout failures are retried without opting the whole
34
+ * client into `retryNonIdempotent`. **Never** set this on a mutation — a
35
+ * retried write may duplicate a committed side effect.
36
+ */
37
+ idempotent?: boolean;
29
38
  };
30
39
  type BaseHttpClientOptions = {
31
40
  /**
package/dist/index.js CHANGED
@@ -1,18 +1,19 @@
1
- import { createReoptPushClient } from './chunk-R5CCGDUH.js';
2
- import { createReoptTermsClient } from './chunk-T7YTITRJ.js';
3
- import { createReoptEavClient } from './chunk-IJOXTBIE.js';
4
- import { createReoptFeedbackClient } from './chunk-RBHP7IZF.js';
5
- import { createReoptFileClient } from './chunk-JWXUVQRC.js';
6
- import { createReoptPlansClient } from './chunk-O3PUWIDJ.js';
7
- import { createReoptAiClient } from './chunk-2Q654O63.js';
1
+ import { createReoptPlansClient } from './chunk-OG7R3UAR.js';
2
+ import { createReoptPushClient } from './chunk-QN3QD67K.js';
3
+ import { createReoptTermsClient } from './chunk-H33OTQEN.js';
4
+ import { createReoptEavClient } from './chunk-4U4ZPPL4.js';
5
+ import { createReoptFeedbackClient } from './chunk-55KHY5GH.js';
6
+ import { createReoptFileClient } from './chunk-UGBBXCZE.js';
7
+ import { createReoptAiClient } from './chunk-FJUCWXX3.js';
8
8
  import './chunk-L4DHB36G.js';
9
9
  import './chunk-F7BXBTZI.js';
10
- import { createReoptAuthClient } from './chunk-POLKEOYH.js';
11
- import { createReoptCmsClient } from './chunk-V73GORO3.js';
12
- import './chunk-VRNBYSWU.js';
13
- export { BaseHttpClient } from './chunk-N5JVE4WX.js';
14
- import { assertBrowserSafe } from './chunk-MRQY45U5.js';
15
- export { AuthError, AuthUserNotFoundError, AuthUserRecordExistsError, BadRequestError, ConflictError, ContentFilterError, CreditLimitError, DuplicateAuthUserError, ForbiddenError, LimitExceededError, ModelAccessError, ModelNotFoundError, NotFoundError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, RequiredTermsError, ServerError, ValidationError, isCreditLimitError, isModelAccessError, isReoptSDKError, isRequiredTermsError, isValidationError, mapHttpStatusToError, resolveBaseUrl } from './chunk-MRQY45U5.js';
10
+ import { createReoptAuthClient } from './chunk-YPLT3RFL.js';
11
+ import { createReoptCmsClient } from './chunk-UVT2E6KD.js';
12
+ import './chunk-PF24XU54.js';
13
+ export { BaseHttpClient } from './chunk-YTKSAWV2.js';
14
+ import './chunk-2LSCQHAU.js';
15
+ import { assertBrowserSafe } from './chunk-C5VTRZWX.js';
16
+ export { AuthError, AuthUserNotFoundError, AuthUserRecordExistsError, BadRequestError, ConflictError, ContentFilterError, CreditLimitError, DuplicateAuthUserError, ForbiddenError, LimitExceededError, ModelAccessError, ModelNotFoundError, NotFoundError, REOPT_BASE_URLS, RateLimitError, ReoptSDKError, RequiredTermsError, ServerError, ValidationError, isCreditLimitError, isModelAccessError, isReoptSDKError, isRequiredTermsError, isValidationError, mapHttpStatusToError, resolveBaseUrl } from './chunk-C5VTRZWX.js';
16
17
 
17
18
  // src/singleton.ts
18
19
  var _instance;
@@ -0,0 +1,106 @@
1
+ import { q as ReoptSDKConfig } from '../config-CtxyJsDR.js';
2
+
3
+ type VerifyLogoutTokenOptions = {
4
+ /** 자기 OAuth client_id — logout_token `aud` 검증. 미지정 시 config/env에서 유도. */
5
+ clientId?: string;
6
+ /** id(IdP) 호스트 override. 미지정 시 resolveIdBaseUrl(config). */
7
+ idBaseUrl?: string;
8
+ /** SDK config (clientId·idBaseUrl 유도용). 개별 옵션이 우선. */
9
+ config?: ReoptSDKConfig;
10
+ /** iat 허용 나이(ms). 기본 5분. */
11
+ maxTokenAgeMs?: number;
12
+ };
13
+ type LogoutTokenClaims = {
14
+ /** 폐기된 IdP 세션 ID — RP 세션 종료 키. */
15
+ sid: string;
16
+ /** 사용자 식별자(선택). */
17
+ sub?: string;
18
+ /** 검증된 issuer. */
19
+ iss: string;
20
+ /** 검증된 audience(들). */
21
+ aud: string[];
22
+ };
23
+ /**
24
+ * logout_token을 검증하고 폐기 대상 클레임(sid·sub)을 반환한다.
25
+ * 검증 실패는 ReoptSDKError(400, invalid_logout_token)로 던진다.
26
+ */
27
+ declare function verifyBackchannelLogoutToken(logoutToken: string, options?: VerifyLogoutTokenOptions): Promise<LogoutTokenClaims>;
28
+ /** 테스트·장수명 프로세스용 — JWKS/discovery 캐시와 refetch 스로틀 상태를 비운다. */
29
+ declare function clearLogoutTokenCaches(): void;
30
+
31
+ /**
32
+ * OIDC Back-Channel Logout 수신 핸들러 팩토리.
33
+ *
34
+ * reopt가 IdP 세션 폐기 시 등록된 `backchannel_logout_uri`로 보내는
35
+ * `application/x-www-form-urlencoded` POST(`logout_token=...`)를 받아 검증하고,
36
+ * 검증 성공 시 `onLogout({ sid, sub })` 콜백으로 RP(자기) 세션을 종료하게 한다.
37
+ *
38
+ * 웹 표준 `Request → Response` 시그니처라 Next.js Route Handler, Hono, 순수
39
+ * Fetch 서버 어디에나 그대로 마운트할 수 있다(webhooks 핸들러와 동일 패턴).
40
+ *
41
+ * @example
42
+ * // Next.js: app/api/auth/backchannel-logout/route.ts
43
+ * import { createBackchannelLogoutHandler } from "@reopt-ai/brandapp-sdk/logout";
44
+ * export const POST = createBackchannelLogoutHandler({
45
+ * onLogout: async ({ sid }) => { await revokeSessionsByReoptSid(sid); },
46
+ * });
47
+ */
48
+ type BackchannelLogoutHandlerConfig = {
49
+ /**
50
+ * 폐기 대상 통지 콜백. `sid`(reopt IdP 세션 ID)로 그 세션에서 파생된 RP
51
+ * 세션을 모두 종료한다. 발급 시 sid를 자기 세션에 저장해 두면 역참조가 쉽다.
52
+ * 예외를 던지면 501을 반환해 reopt가 재시도한다(멱등하게 구현할 것).
53
+ */
54
+ onLogout: (event: LogoutTokenClaims) => Promise<void> | void;
55
+ /** 자기 client_id — 미지정 시 config/BRANDAPP_CLIENT_ID. */
56
+ clientId?: string;
57
+ /** id 호스트 override — 미지정 시 resolveIdBaseUrl(config). */
58
+ idBaseUrl?: string;
59
+ /** SDK config (clientId·idBaseUrl 유도용). */
60
+ config?: ReoptSDKConfig;
61
+ /** logout_token iat 허용 나이(ms). 기본 5분. */
62
+ maxTokenAgeMs?: number;
63
+ };
64
+ declare function createBackchannelLogoutHandler(config: BackchannelLogoutHandlerConfig): (request: Request) => Promise<Response>;
65
+
66
+ /**
67
+ * RP-Initiated Logout — reopt의 `end_session_endpoint`로 보낼 URL을 조립한다.
68
+ *
69
+ * 외부 브랜드앱이 "reopt에서도 로그아웃" 같은 동작을 제공할 때, 사용자를 이
70
+ * URL로 보내면 reopt가 해당 id_token의 IdP 세션(및 그 세션에서 파생된 전
71
+ * RP 세션·토큰)을 폐기하고, 등록된 `post_logout_redirect_uri`로 되돌린다.
72
+ *
73
+ * 순수 URL 조립이라 서버·클라이언트 어디서나 쓸 수 있다.
74
+ *
75
+ * @example
76
+ * import { buildEndSessionUrl } from "@reopt-ai/brandapp-sdk/logout";
77
+ * const url = buildEndSessionUrl({
78
+ * idToken: session.idToken, // 로그인 시 받은 id_token
79
+ * postLogoutRedirectUri: "https://app.example.com/goodbye",
80
+ * state: csrfToken,
81
+ * });
82
+ * redirect(url); // 사용자를 reopt end-session으로 이동
83
+ */
84
+ type BuildEndSessionUrlOptions = {
85
+ /**
86
+ * `id_token_hint` — 로그인 시 받은 id_token. 어느 세션을 끝낼지 식별한다.
87
+ * 없으면 reopt가 어떤 세션인지 알 수 없어 로그아웃이 무의미하므로 필수.
88
+ */
89
+ idToken: string;
90
+ /** 자기 client_id(선택 — id_token_hint의 aud와 대조에 쓰이며 미지정 가능). */
91
+ clientId?: string;
92
+ /**
93
+ * 로그아웃 후 복귀 URL. reopt OAuth 클라이언트의 `post_logout_redirect_uris`에
94
+ * 사전 등록된 값이어야 reopt가 redirect한다(미등록 시 종료만 하고 안 돌아옴).
95
+ */
96
+ postLogoutRedirectUri?: string;
97
+ /** CSRF/상태 보존용 state — 복귀 URL에 그대로 실려 돌아온다. */
98
+ state?: string;
99
+ /** id 호스트 override — 미지정 시 resolveIdBaseUrl(config). */
100
+ idBaseUrl?: string;
101
+ /** SDK config (idBaseUrl 유도용). */
102
+ config?: ReoptSDKConfig;
103
+ };
104
+ declare function buildEndSessionUrl(options: BuildEndSessionUrlOptions): string;
105
+
106
+ export { type BackchannelLogoutHandlerConfig, type BuildEndSessionUrlOptions, type LogoutTokenClaims, type VerifyLogoutTokenOptions, buildEndSessionUrl, clearLogoutTokenCaches, createBackchannelLogoutHandler, verifyBackchannelLogoutToken };