@reopt-ai/brandapp-sdk 3.1.0 → 3.4.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 (104) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +39 -14
  3. package/dist/abort--nOBFN4M.js +50 -0
  4. package/dist/ai/index.d.ts +2 -314
  5. package/dist/ai/index.js +3 -7
  6. package/dist/ai-provider/index.d.ts +79 -163
  7. package/dist/ai-provider/index.js +752 -671
  8. package/dist/auth/index.d.ts +27 -27
  9. package/dist/auth/index.js +41 -33
  10. package/dist/better-auth/client.d.ts +6 -5
  11. package/dist/better-auth/client.js +28 -5
  12. package/dist/better-auth/index.d.ts +19 -17
  13. package/dist/better-auth/index.js +180 -133
  14. package/dist/client-B1q5P8rv.js +83 -0
  15. package/dist/client-B9QHVhdM.js +77 -0
  16. package/dist/client-BGGd_cpV.d.ts +103 -0
  17. package/dist/client-BJcy1V1a.js +140 -0
  18. package/dist/client-Beivhucf.js +55 -0
  19. package/dist/client-BruP5_nU.d.ts +147 -0
  20. package/dist/client-D-yNxNfk.js +28 -0
  21. package/dist/client-D0eBxh8j.d.ts +284 -0
  22. package/dist/client-D3RHHUUW.d.ts +207 -0
  23. package/dist/client-D6gs61w8.d.ts +53 -0
  24. package/dist/client-DBnK7ooQ.js +86 -0
  25. package/dist/client-DDw5yz_h.d.ts +53 -0
  26. package/dist/client-DPmoKuR9.js +305 -0
  27. package/dist/client-DsdakibF.js +503 -0
  28. package/dist/client-Dxg8_DIH.d.ts +71 -0
  29. package/dist/client-EbhUIhHq.js +53 -0
  30. package/dist/client-lk6wBu_0.d.ts +48 -0
  31. package/dist/client-p49ol9pg.d.ts +124 -0
  32. package/dist/cms/index.d.ts +52 -108
  33. package/dist/cms/index.js +105 -84
  34. package/dist/config-CRytOPPl.d.ts +394 -0
  35. package/dist/config-Cw0a3-C8.js +487 -0
  36. package/dist/dev/index.d.ts +2 -509
  37. package/dist/dev/index.js +2740 -2873
  38. package/dist/eav/coerce.d.ts +3 -1
  39. package/dist/eav/coerce.js +72 -46
  40. package/dist/eav/index.d.ts +72 -100
  41. package/dist/eav/index.js +158 -125
  42. package/dist/eav/migrate.d.ts +112 -109
  43. package/dist/eav/migrate.js +230 -196
  44. package/dist/eav/schema.d.ts +111 -150
  45. package/dist/eav/schema.js +624 -603
  46. package/dist/encoding-Bwfm3iaE.js +21 -0
  47. package/dist/{errors-DIAS8Rsl.d.ts → errors-CRCcErNC.d.ts} +55 -53
  48. package/dist/feedback/index.d.ts +2 -132
  49. package/dist/feedback/index.js +3 -5
  50. package/dist/files/index.d.ts +14 -14
  51. package/dist/files/index.js +41 -24
  52. package/dist/http-client-QKUvvirs.js +386 -0
  53. package/dist/index-DrVaKfhs.d.ts +456 -0
  54. package/dist/index-Z6OGcurJ.d.ts +169 -0
  55. package/dist/index.d.ts +6 -221
  56. package/dist/index.js +119 -70
  57. package/dist/logout/index.d.ts +109 -0
  58. package/dist/logout/index.js +264 -0
  59. package/dist/plans/index.d.ts +2 -236
  60. package/dist/plans/index.js +3 -5
  61. package/dist/push/index.d.ts +2 -79
  62. package/dist/push/index.js +3 -5
  63. package/dist/query-BvbCiGWb.js +35 -0
  64. package/dist/react/hooks.d.ts +97 -95
  65. package/dist/react/hooks.js +742 -356
  66. package/dist/sse-parser-FMjxM7sY.js +86 -0
  67. package/dist/terms/index.d.ts +3 -79
  68. package/dist/terms/index.js +3 -5
  69. package/dist/testing/index.d.ts +52 -104
  70. package/dist/testing/index.js +94 -72
  71. package/dist/types-B-SMkH6s.d.ts +26 -0
  72. package/dist/types-BXDcoJHG.d.ts +131 -0
  73. package/dist/types-BrghN2rJ.d.ts +105 -0
  74. package/dist/types-DjDRszNj.js +11 -0
  75. package/dist/webhooks/index.d.ts +77 -47
  76. package/dist/webhooks/index.js +150 -127
  77. package/docs/api-reference.md +179 -2
  78. package/docs/dev-server.md +19 -18
  79. package/docs/errors.md +72 -15
  80. package/docs/logout.md +166 -0
  81. package/package.json +10 -5
  82. package/dist/chunk-2Q654O63.js +0 -350
  83. package/dist/chunk-F7BXBTZI.js +0 -54
  84. package/dist/chunk-IJOXTBIE.js +0 -599
  85. package/dist/chunk-JWXUVQRC.js +0 -157
  86. package/dist/chunk-L4DHB36G.js +0 -75
  87. package/dist/chunk-MRQY45U5.js +0 -465
  88. package/dist/chunk-N5JVE4WX.js +0 -449
  89. package/dist/chunk-O3PUWIDJ.js +0 -105
  90. package/dist/chunk-POLKEOYH.js +0 -63
  91. package/dist/chunk-R5CCGDUH.js +0 -49
  92. package/dist/chunk-RBHP7IZF.js +0 -96
  93. package/dist/chunk-REIKXSMY.js +0 -7
  94. package/dist/chunk-T7YTITRJ.js +0 -112
  95. package/dist/chunk-V73GORO3.js +0 -81
  96. package/dist/chunk-VRNBYSWU.js +0 -32
  97. package/dist/client-BkcO-0C2.d.ts +0 -216
  98. package/dist/client-CN5_tNOC.d.ts +0 -147
  99. package/dist/client-DttyeM_h.d.ts +0 -102
  100. package/dist/config-CtxyJsDR.d.ts +0 -397
  101. package/dist/typed-client-BxOVIiMU.d.ts +0 -40
  102. package/dist/types-6E3ZLL9X.d.ts +0 -24
  103. package/dist/types-DskYLVb8.d.ts +0 -104
  104. package/dist/types-ckmDDW3N.d.ts +0 -129
@@ -1,142 +1,165 @@
1
- // src/webhooks/index.ts
2
- var DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1e3;
3
- var DEFAULT_IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1e3;
1
+ //#region src/webhooks/index.ts
2
+ /**
3
+ * Default replay-protection window (5 minutes). Webhooks whose
4
+ * `x-reopt-timestamp` is older than this are rejected with HTTP 410. Set
5
+ * `toleranceMs: 0` to disable.
6
+ */
7
+ const DEFAULT_WEBHOOK_TOLERANCE_MS = 300 * 1e3;
8
+ /** Default idempotency cache window — events processed within this window are
9
+ * deduplicated by `payload.id`. */
10
+ const DEFAULT_IDEMPOTENCY_TTL_MS = 1440 * 60 * 1e3;
11
+ /**
12
+ * In-memory idempotency store with a soft cap to avoid unbounded growth.
13
+ * Suitable for single-instance dev/preview deployments. For production with
14
+ * multiple replicas, supply a Redis/Postgres-backed store instead.
15
+ */
4
16
  function createMemoryIdempotencyStore(options) {
5
- const maxEntries = options?.maxEntries ?? 1e4;
6
- const seen = /* @__PURE__ */ new Map();
7
- const sweep = (now) => {
8
- for (const [id, exp] of seen) {
9
- if (exp <= now) seen.delete(id);
10
- }
11
- if (seen.size > maxEntries) {
12
- const drop = seen.size - maxEntries;
13
- let i = 0;
14
- for (const id of seen.keys()) {
15
- if (i++ >= drop) break;
16
- seen.delete(id);
17
- }
18
- }
19
- };
20
- return {
21
- has(id) {
22
- const now = Date.now();
23
- const exp = seen.get(id);
24
- if (exp == null) return false;
25
- if (exp <= now) {
26
- seen.delete(id);
27
- return false;
28
- }
29
- return true;
30
- },
31
- markProcessed(id, ttlMs) {
32
- const now = Date.now();
33
- sweep(now);
34
- seen.set(id, now + Math.max(ttlMs, 0));
35
- }
36
- };
17
+ const maxEntries = options?.maxEntries ?? 1e4;
18
+ const seen = /* @__PURE__ */ new Map();
19
+ const sweep = (now) => {
20
+ for (const [id, exp] of seen) if (exp <= now) seen.delete(id);
21
+ if (seen.size > maxEntries) {
22
+ const drop = seen.size - maxEntries;
23
+ let i = 0;
24
+ for (const id of seen.keys()) {
25
+ if (i++ >= drop) break;
26
+ seen.delete(id);
27
+ }
28
+ }
29
+ };
30
+ return {
31
+ has(id) {
32
+ const now = Date.now();
33
+ const exp = seen.get(id);
34
+ if (exp == null) return false;
35
+ if (exp <= now) {
36
+ seen.delete(id);
37
+ return false;
38
+ }
39
+ return true;
40
+ },
41
+ markProcessed(id, ttlMs) {
42
+ const now = Date.now();
43
+ sweep(now);
44
+ seen.set(id, now + Math.max(ttlMs, 0));
45
+ }
46
+ };
37
47
  }
48
+ /**
49
+ * Create a webhook handler for Web-standard `Request` → `Response` runtimes
50
+ * (Next.js App Router route handlers, Edge runtime, Hono, …).
51
+ *
52
+ * Usage:
53
+ * ```ts
54
+ * // app/api/webhooks/reopt/route.ts
55
+ * import { createWebhookHandler } from "@reopt-ai/brandapp-sdk/webhooks";
56
+ *
57
+ * export const POST = createWebhookHandler({
58
+ * secret: process.env.BRANDAPP_WEBHOOK_SECRET!,
59
+ * handlers: {
60
+ * contactCreated: async (payload) => { ... },
61
+ * workflowRunCompleted: async (payload) => { ... },
62
+ * },
63
+ * });
64
+ * ```
65
+ */
38
66
  function createWebhookHandler(config) {
39
- const toleranceMs = config.toleranceMs ?? DEFAULT_WEBHOOK_TOLERANCE_MS;
40
- const idempotencyStore = config.idempotency === true ? createMemoryIdempotencyStore() : config.idempotency && typeof config.idempotency === "object" ? config.idempotency : null;
41
- const idempotencyTtl = config.idempotencyTtlMs ?? DEFAULT_IDEMPOTENCY_TTL_MS;
42
- return async (request) => {
43
- const signature = request.headers.get("x-reopt-signature");
44
- const timestamp = request.headers.get("x-reopt-timestamp");
45
- const body = await request.text();
46
- if (!signature || !timestamp || !await verifySignature(timestamp, body, signature, config.secret)) {
47
- return jsonResponse({ error: "Invalid signature" }, 401);
48
- }
49
- let payload;
50
- try {
51
- payload = JSON.parse(body);
52
- } catch {
53
- return jsonResponse({ error: "Invalid JSON" }, 400);
54
- }
55
- if (toleranceMs > 0) {
56
- const ts = Number(timestamp);
57
- if (!Number.isFinite(ts)) {
58
- return jsonResponse({ error: "Invalid timestamp" }, 400);
59
- }
60
- if (Math.abs(Date.now() - ts) > toleranceMs) {
61
- return jsonResponse(
62
- { error: "Webhook timestamp outside tolerance" },
63
- 410
64
- );
65
- }
66
- }
67
- const attempt = parseAttemptHeader(
68
- request.headers.get("x-reopt-delivery-attempt")
69
- );
70
- if (idempotencyStore && payload.id) {
71
- if (await idempotencyStore.has(payload.id)) {
72
- return jsonResponse({ received: true, deduplicated: true }, 200);
73
- }
74
- }
75
- const handler = config.handlers[payload.type];
76
- if (handler) {
77
- try {
78
- await handler(payload);
79
- } catch (error) {
80
- await config.onError?.(
81
- error instanceof Error ? error : new Error(String(error)),
82
- payload,
83
- { attempt }
84
- );
85
- return jsonResponse({ error: "Handler error" }, 500);
86
- }
87
- }
88
- if (idempotencyStore && payload.id) {
89
- await idempotencyStore.markProcessed(payload.id, idempotencyTtl);
90
- }
91
- return jsonResponse({ received: true }, 200);
92
- };
67
+ const toleranceMs = config.toleranceMs ?? 3e5;
68
+ const idempotencyStore = config.idempotency === true ? createMemoryIdempotencyStore() : config.idempotency && typeof config.idempotency === "object" ? config.idempotency : null;
69
+ const idempotencyTtl = config.idempotencyTtlMs ?? 864e5;
70
+ return async (request) => {
71
+ const signature = request.headers.get("x-reopt-signature");
72
+ const timestamp = request.headers.get("x-reopt-timestamp");
73
+ const body = await request.text();
74
+ if (!signature || !timestamp || !await verifySignature(timestamp, body, signature, config.secret)) return jsonResponse({ error: "Invalid signature" }, 401);
75
+ let payload;
76
+ try {
77
+ payload = JSON.parse(body);
78
+ } catch {
79
+ return jsonResponse({ error: "Invalid JSON" }, 400);
80
+ }
81
+ if (toleranceMs > 0) {
82
+ const ts = Number(timestamp);
83
+ if (!Number.isFinite(ts)) return jsonResponse({ error: "Invalid timestamp" }, 400);
84
+ if (Math.abs(Date.now() - ts) > toleranceMs) return jsonResponse({ error: "Webhook timestamp outside tolerance" }, 410);
85
+ }
86
+ const attempt = parseAttemptHeader(request.headers.get("x-reopt-delivery-attempt"));
87
+ if (idempotencyStore && payload.id) {
88
+ if (await idempotencyStore.has(payload.id)) return jsonResponse({
89
+ received: true,
90
+ deduplicated: true
91
+ }, 200);
92
+ }
93
+ const handler = config.handlers[payload.type];
94
+ if (handler) try {
95
+ await handler(payload);
96
+ } catch (error) {
97
+ await config.onError?.(error instanceof Error ? error : new Error(String(error)), payload, { attempt });
98
+ return jsonResponse({ error: "Handler error" }, 500);
99
+ }
100
+ if (idempotencyStore && payload.id) await idempotencyStore.markProcessed(payload.id, idempotencyTtl);
101
+ return jsonResponse({ received: true }, 200);
102
+ };
93
103
  }
94
104
  function jsonResponse(body, status) {
95
- return new Response(JSON.stringify(body), {
96
- status,
97
- headers: { "Content-Type": "application/json" }
98
- });
105
+ return new Response(JSON.stringify(body), {
106
+ status,
107
+ headers: { "Content-Type": "application/json" }
108
+ });
99
109
  }
100
110
  function parseAttemptHeader(value) {
101
- if (!value) return 1;
102
- const n = Number(value);
103
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
111
+ if (!value) return 1;
112
+ const n = Number(value);
113
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
104
114
  }
115
+ /** Strip the `sha256=` prefix the platform sender prepends to the hex digest. */
105
116
  function stripSignaturePrefix(signature) {
106
- return signature.startsWith("sha256=") ? signature.slice("sha256=".length) : signature;
117
+ return signature.startsWith("sha256=") ? signature.slice(7) : signature;
107
118
  }
119
+ /**
120
+ * Verify a Reopt webhook signature.
121
+ *
122
+ * Recomputes `HMAC-SHA256(secret, "{timestamp}.{body}")` and compares it against
123
+ * the hex digest carried in the `x-reopt-signature` header (the `sha256=` prefix
124
+ * is accepted and stripped). Uses a double-HMAC constant-time comparison so it
125
+ * is safe against timing side-channels and works in Node, Edge, and Browser
126
+ * runtimes.
127
+ *
128
+ * This matches the platform sender's `buildWebhookSignature`
129
+ * (`packages/server-core/events/workspace-webhook-delivery.ts`).
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { verifySignature } from "@reopt-ai/brandapp-sdk/webhooks";
134
+ *
135
+ * const timestamp = request.headers.get("x-reopt-timestamp")!;
136
+ * const signature = request.headers.get("x-reopt-signature")!;
137
+ * const body = await request.text();
138
+ * const ok = await verifySignature(timestamp, body, signature, secret);
139
+ * ```
140
+ */
108
141
  async function verifySignature(timestamp, body, signature, secret) {
109
- try {
110
- const encoder = new TextEncoder();
111
- const key = await crypto.subtle.importKey(
112
- "raw",
113
- encoder.encode(secret),
114
- { name: "HMAC", hash: "SHA-256" },
115
- false,
116
- ["sign"]
117
- );
118
- const sig = await crypto.subtle.sign(
119
- "HMAC",
120
- key,
121
- encoder.encode(`${timestamp}.${body}`)
122
- );
123
- const expected = Array.from(new Uint8Array(sig)).map((b2) => b2.toString(16).padStart(2, "0")).join("");
124
- const provided = stripSignaturePrefix(signature);
125
- const [hmacA, hmacB] = await Promise.all([
126
- crypto.subtle.sign("HMAC", key, encoder.encode(provided)),
127
- crypto.subtle.sign("HMAC", key, encoder.encode(expected))
128
- ]);
129
- const a = new Uint8Array(hmacA);
130
- const b = new Uint8Array(hmacB);
131
- if (a.length !== b.length) return false;
132
- let diff = 0;
133
- for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
134
- return diff === 0;
135
- } catch {
136
- return false;
137
- }
142
+ try {
143
+ const encoder = new TextEncoder();
144
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
145
+ name: "HMAC",
146
+ hash: "SHA-256"
147
+ }, false, ["sign"]);
148
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`));
149
+ const expected = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
150
+ const provided = stripSignaturePrefix(signature);
151
+ const [hmacA, hmacB] = await Promise.all([crypto.subtle.sign("HMAC", key, encoder.encode(provided)), crypto.subtle.sign("HMAC", key, encoder.encode(expected))]);
152
+ const a = new Uint8Array(hmacA);
153
+ const b = new Uint8Array(hmacB);
154
+ if (a.length !== b.length) return false;
155
+ let diff = 0;
156
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
157
+ return diff === 0;
158
+ } catch {
159
+ return false;
160
+ }
138
161
  }
139
162
 
163
+ //#endregion
140
164
  export { DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_WEBHOOK_TOLERANCE_MS, createMemoryIdempotencyStore, createWebhookHandler, verifySignature };
141
- //# sourceMappingURL=index.js.map
142
165
  //# sourceMappingURL=index.js.map
@@ -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,106 @@ 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
+ type CancelSubscriptionResult,
505
+ } from "@reopt-ai/brandapp-sdk/plans";
506
+
507
+ // Catalog — Basic Auth (or pass an accessToken to use Bearer)
508
+ const plans: Plan[] = await sdk.plans.list();
509
+
510
+ // The current customer's plan / entitlement (Bearer). null if none.
511
+ const current: CurrentPlan | null = await sdk.plans.getMyPlan(accessToken);
512
+
513
+ // Hosted checkout (Bearer). In sandbox mode checkoutUrl is an id.reopt.ai
514
+ // virtual-payment page; redirect the browser there.
515
+ try {
516
+ const checkout: CheckoutSession = await sdk.plans.createCheckout(
517
+ { planId: plans[0].id, successUrl, cancelUrl },
518
+ accessToken,
519
+ );
520
+ redirect(checkout.checkoutUrl!); // → pay, then back to successUrl/cancelUrl
521
+ } catch (e) {
522
+ if (isRequiredTermsError(e)) {
523
+ // collect consent for e.missingTermsIds via sdk.terms, then retry
524
+ } else throw e;
525
+ }
526
+
527
+ // On the return page, confirm the checkout / entitlement:
528
+ const session = await sdk.plans.getCheckout(checkout.checkoutId, accessToken);
529
+ if (session.status === "completed") {
530
+ /* granted */
531
+ }
532
+
533
+ // Cancel the current subscription — sandbox and live (Paddle/Toss/IAP) alike.
534
+ // Access is kept until the paid period ends.
535
+ const canceled: CancelSubscriptionResult = await sdk.plans.cancel(accessToken);
536
+ canceled.status; // "canceled"
537
+ canceled.provider; // "sandbox" | "paddle" | "toss" | "apple" | "google" (3.4+)
538
+ canceled.accessUntil; // ISO-8601, or null when the plan has no expiry (3.4+)
539
+ canceled.providerCanceled; // false → local subscription is definitely over (no
540
+ // further billing) but the payment provider still shows a
541
+ // remnant that an operator should check (3.4+)
542
+ ```
543
+
544
+ > The three fields added in 3.4 are optional — an older platform deployment
545
+ > simply omits them. Apple/Google (IAP) subscriptions are canceled in the store,
546
+ > so no remote call is made and `providerCanceled` stays `false`.
547
+
548
+ > Live **Paddle** checkout runs through the same `createCheckout` since 3.4 —
549
+ > `checkoutUrl` is then a Paddle-hosted payment page (zero-price plans keep the
550
+ > sandbox session flow). Live **Toss** stays in the first-party brandfront flow:
551
+ > `createCheckout` returns HTTP 409 `LIVE_MODE_UNSUPPORTED` for a priced plan.
552
+ > usage-model meters are read-only metadata.
553
+
554
+ ## Feedback Client (`sdk.feedback`) — two-way thread (3.4+)
555
+
556
+ ```typescript
557
+ import type {
558
+ Feedback,
559
+ FeedbackDetail,
560
+ FeedbackReply,
561
+ } from "@reopt-ai/brandapp-sdk/feedback";
562
+
563
+ // Server-side collection with app credentials
564
+ await sdk.feedback.create({ content: "배송이 늦어요", rating: 2, customerId });
565
+ const { feedbacks, meta } = await sdk.feedback.list({ status: "reopened" });
566
+ const detail: FeedbackDetail = await sdk.feedback.get(feedbacks[0].id);
567
+
568
+ // ── Signed-in user surface (OAuth access token) ──
569
+ await sdk.feedback.me.create({ content: "좋아요!", rating: 5 }, accessToken);
570
+ const mine = await sdk.feedback.me.list(accessToken);
571
+ const thread = await sdk.feedback.me.get(mine.feedbacks[0].id, accessToken);
572
+
573
+ // The thread mixes both directions in chronological order:
574
+ thread.replies.forEach((reply: FeedbackReply) => {
575
+ reply.author; // "staff" | "customer"
576
+ reply.helpful; // customer's rating of a staff reply (null = not rated)
577
+ });
578
+
579
+ // Rate a staff answer, then follow up — the feedback flips to "reopened"
580
+ // and the workspace is notified.
581
+ const staffReply = thread.replies.find((r) => r.author === "staff")!;
582
+ await sdk.feedback.me.rateReply(thread.id, staffReply.id, false, accessToken);
583
+ const sent = await sdk.feedback.me.reply(
584
+ thread.id,
585
+ "아직 해결이 안 됐어요",
586
+ accessToken,
587
+ );
588
+ sent.feedbackStatus; // "reopened"
589
+ ```
590
+
591
+ > `replyCount` counts **staff replies only**, so `replyCount > 0` keeps meaning
592
+ > "the workspace has answered" even after the customer follows up. Rating alone
593
+ > never reopens a feedback — send a `reply` when the customer still needs
594
+ > something. Ratings are accepted on staff replies only; `null` clears one.
595
+
484
596
  ## Webhooks
485
597
 
486
598
  ```typescript
@@ -506,8 +618,29 @@ export const POST = createWebhookHandler({
506
618
  // Event types (match the platform sender):
507
619
  // "contactCreated" | "contactUpdated" | "contactDeleted"
508
620
  // | "workflowRunCompleted" | "workflowRunFailed"
621
+ // | "subscriptionActivated" | "subscriptionRenewed" // 3.4+
622
+ // | "subscriptionCanceled" | "subscriptionPaymentFailed" // 3.4+
509
623
  // Payload: { id, type, entityType, entityId, createdAt, data }
510
624
 
625
+ // Subscription lifecycle (3.4+) — data is `SubscriptionWebhookData`:
626
+ import type { SubscriptionWebhookData } from "@reopt-ai/brandapp-sdk/webhooks";
627
+
628
+ export const POST = createWebhookHandler({
629
+ secret,
630
+ handlers: {
631
+ subscriptionActivated: async ({ data }) => {
632
+ const sub = data as SubscriptionWebhookData;
633
+ if (sub.brandappId !== process.env.BRANDAPP_ID) return; // see note below
634
+ await grantEntitlement(sub.brandappCustomerId, sub.planId, sub.accessUntil);
635
+ },
636
+ subscriptionRenewed: async ({ data }) => extendAccess(data),
637
+ subscriptionPaymentFailed: async ({ data }) => startDunning(data),
638
+ subscriptionCanceled: async ({ data }) => keepAccessUntil(data), // not immediate
639
+ },
640
+ });
641
+ // SubscriptionWebhookData: { brandappId, brandappCustomerId, customerId,
642
+ // planId, planName, provider, accessUntil }
643
+
511
644
  // Manual signature verification — timestamp first; signs "{timestamp}.{body}",
512
645
  // accepts the sha256=-prefixed header value the platform sends.
513
646
  const timestamp = request.headers.get("x-reopt-timestamp")!;
@@ -515,6 +648,11 @@ const signature = request.headers.get("x-reopt-signature")!;
515
648
  const ok = await verifySignature(timestamp, rawBody, signature, secret);
516
649
  ```
517
650
 
651
+ > Webhooks are registered **per workspace**, so if a workspace runs several
652
+ > Brandapps every subscription event reaches the same endpoint — always filter
653
+ > on `data.brandappId`. `subscriptionCanceled` does not mean "cut access now":
654
+ > honour `accessUntil` (null = no expiry).
655
+
518
656
  ## React Hooks
519
657
 
520
658
  ```typescript
@@ -555,3 +693,42 @@ const { data: tags } = useCmsTags(sdk, { groupId? });
555
693
 
556
694
  > **1.8 변경**: `useCreatePost` / `useUpdatePost` / `useDeletePost`는 cms write
557
695
  > 표면 제거에 따라 함께 제거됐다. authoring은 Reopt Studio가 담당한다.
696
+
697
+ ## Logout — OIDC Single Logout (3.2+)
698
+
699
+ Two directions of session-termination interop with reopt. Full guide:
700
+ [`logout.md`](./logout.md).
701
+
702
+ ```typescript
703
+ import {
704
+ createBackchannelLogoutHandler,
705
+ verifyBackchannelLogoutToken,
706
+ buildEndSessionUrl,
707
+ } from "@reopt-ai/brandapp-sdk/logout";
708
+
709
+ // 1) RECEIVE — reopt POSTs a logout_token when it revokes the IdP session.
710
+ // Mount as a Web-standard Request→Response handler (Next.js/Hono/Fetch).
711
+ // app/api/auth/backchannel-logout/route.ts
712
+ export const POST = createBackchannelLogoutHandler({
713
+ onLogout: async ({ sid, sub }) => {
714
+ await revokeSessionsByReoptSid(sid); // end your derived RP sessions (idempotent)
715
+ },
716
+ });
717
+ // Responses: 200 ok · 400 invalid logout_token · 405 non-POST ·
718
+ // 501 onLogout threw (retry) · 503 verification infra unavailable (retry)
719
+ // Signature: Web Crypto Ed25519 (EdDSA), zero external deps. JWKS is fetched
720
+ // from discovery, cached, and force-refetched (throttled) on key rotation.
721
+
722
+ // verify without the HTTP wrapper (custom transport / tests):
723
+ const { sid, sub } = await verifyBackchannelLogoutToken(logoutToken, {
724
+ clientId, // or BRANDAPP_CLIENT_ID
725
+ });
726
+
727
+ // 2) TRIGGER — send the user to reopt's end_session_endpoint (RP-Initiated).
728
+ const url = buildEndSessionUrl({
729
+ idToken: session.idToken, // id_token_hint
730
+ postLogoutRedirectUri: "https://app.example.com/goodbye", // pre-registered
731
+ state: csrfToken,
732
+ });
733
+ redirect(url);
734
+ ```
@@ -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