@reopt-ai/brandapp-sdk 3.0.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 (76) hide show
  1. package/CHANGELOG.md +574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +468 -0
  4. package/dist/ai/index.d.ts +314 -0
  5. package/dist/ai/index.js +7 -0
  6. package/dist/ai-provider/index.d.ts +196 -0
  7. package/dist/ai-provider/index.js +703 -0
  8. package/dist/auth/index.d.ts +76 -0
  9. package/dist/auth/index.js +40 -0
  10. package/dist/better-auth/client.d.ts +29 -0
  11. package/dist/better-auth/client.js +10 -0
  12. package/dist/better-auth/index.d.ts +82 -0
  13. package/dist/better-auth/index.js +145 -0
  14. package/dist/chunk-6FLYVNZI.js +32 -0
  15. package/dist/chunk-6KPKZ7ZB.js +49 -0
  16. package/dist/chunk-DI6QJPTQ.js +449 -0
  17. package/dist/chunk-E457LO5A.js +599 -0
  18. package/dist/chunk-F7BXBTZI.js +54 -0
  19. package/dist/chunk-J5Y2GSJF.js +443 -0
  20. package/dist/chunk-K3YVJE6E.js +96 -0
  21. package/dist/chunk-KU2LN5SE.js +350 -0
  22. package/dist/chunk-L4DHB36G.js +75 -0
  23. package/dist/chunk-PJZB4VP7.js +63 -0
  24. package/dist/chunk-REIKXSMY.js +7 -0
  25. package/dist/chunk-T2WXHAAC.js +54 -0
  26. package/dist/chunk-TUKIYH4Q.js +112 -0
  27. package/dist/chunk-WSEROZVO.js +81 -0
  28. package/dist/chunk-YRGLBM6V.js +157 -0
  29. package/dist/client-BkcO-0C2.d.ts +216 -0
  30. package/dist/client-CN5_tNOC.d.ts +147 -0
  31. package/dist/client-DttyeM_h.d.ts +102 -0
  32. package/dist/cms/index.d.ts +137 -0
  33. package/dist/cms/index.js +101 -0
  34. package/dist/config-CtxyJsDR.d.ts +397 -0
  35. package/dist/dev/index.d.ts +509 -0
  36. package/dist/dev/index.js +3071 -0
  37. package/dist/eav/coerce.d.ts +42 -0
  38. package/dist/eav/coerce.js +65 -0
  39. package/dist/eav/index.d.ts +214 -0
  40. package/dist/eav/index.js +147 -0
  41. package/dist/eav/migrate.d.ts +236 -0
  42. package/dist/eav/migrate.js +219 -0
  43. package/dist/eav/schema.d.ts +260 -0
  44. package/dist/eav/schema.js +656 -0
  45. package/dist/errors-5hd5ZR-M.d.ts +158 -0
  46. package/dist/feedback/index.d.ts +132 -0
  47. package/dist/feedback/index.js +5 -0
  48. package/dist/files/index.d.ts +54 -0
  49. package/dist/files/index.js +31 -0
  50. package/dist/index.d.ts +221 -0
  51. package/dist/index.js +84 -0
  52. package/dist/plans/index.d.ts +140 -0
  53. package/dist/plans/index.js +5 -0
  54. package/dist/push/index.d.ts +79 -0
  55. package/dist/push/index.js +5 -0
  56. package/dist/react/hooks.d.ts +376 -0
  57. package/dist/react/hooks.js +421 -0
  58. package/dist/terms/index.d.ts +79 -0
  59. package/dist/terms/index.js +5 -0
  60. package/dist/testing/index.d.ts +154 -0
  61. package/dist/testing/index.js +81 -0
  62. package/dist/typed-client-BxOVIiMU.d.ts +40 -0
  63. package/dist/types-6E3ZLL9X.d.ts +24 -0
  64. package/dist/types-DskYLVb8.d.ts +104 -0
  65. package/dist/types-ckmDDW3N.d.ts +129 -0
  66. package/dist/webhooks/index.d.ts +140 -0
  67. package/dist/webhooks/index.js +142 -0
  68. package/docs/api-reference.md +557 -0
  69. package/docs/cms.md +318 -0
  70. package/docs/dev-server.md +164 -0
  71. package/docs/environment.md +211 -0
  72. package/docs/errors.md +290 -0
  73. package/docs/files.md +272 -0
  74. package/docs/migration.md +315 -0
  75. package/docs/testing.md +163 -0
  76. package/package.json +173 -0
@@ -0,0 +1,81 @@
1
+ // src/testing/index.ts
2
+ async function createTestSDK(options = {}) {
3
+ const {
4
+ schema,
5
+ brandappId = "test-brandapp",
6
+ seed: initialSeed,
7
+ seedAll,
8
+ postGroups,
9
+ posts,
10
+ terms
11
+ } = options;
12
+ const { createDevServer } = await import('../dev/index.js');
13
+ const { createReoptSDK } = await import('../index.js');
14
+ const devServer = await createDevServer({
15
+ port: 0,
16
+ // Auto-assign port
17
+ brandappId,
18
+ schema
19
+ });
20
+ if (initialSeed) {
21
+ await devServer.seed(initialSeed);
22
+ }
23
+ const merged = {
24
+ postGroups: [...seedAll?.postGroups ?? [], ...postGroups ?? []],
25
+ posts: [...seedAll?.posts ?? [], ...posts ?? []],
26
+ entities: seedAll?.entities,
27
+ terms: [...seedAll?.terms ?? [], ...terms ?? []]
28
+ };
29
+ if (merged.postGroups?.length || merged.posts?.length || merged.entities || merged.terms?.length) {
30
+ await devServer.seedAll(merged);
31
+ }
32
+ const sdkConfig = {
33
+ clientId: "test",
34
+ clientSecret: "test",
35
+ brandappId,
36
+ baseUrl: devServer.url
37
+ };
38
+ let sdk = createReoptSDK(sdkConfig);
39
+ const result = {
40
+ get sdk() {
41
+ return sdk;
42
+ },
43
+ devServer,
44
+ url: devServer.url,
45
+ async resetAll() {
46
+ await devServer.reset();
47
+ sdk = createReoptSDK(sdkConfig);
48
+ }
49
+ };
50
+ return result;
51
+ }
52
+ async function createTestServer(options = {}) {
53
+ const { schema, brandappId = "test-brandapp", seed: initialSeed } = options;
54
+ const { createDevServer } = await import('../dev/index.js');
55
+ const devServer = await createDevServer({
56
+ port: 0,
57
+ brandappId,
58
+ schema
59
+ });
60
+ if (initialSeed) {
61
+ await devServer.seed(initialSeed);
62
+ }
63
+ return {
64
+ devServer,
65
+ url: devServer.url,
66
+ port: devServer.port,
67
+ sdkConfig: {
68
+ clientId: "test",
69
+ clientSecret: "test",
70
+ brandappId,
71
+ baseUrl: devServer.url
72
+ }
73
+ };
74
+ }
75
+ function createFixture(factories) {
76
+ return factories;
77
+ }
78
+
79
+ export { createFixture, createTestSDK, createTestServer };
80
+ //# sourceMappingURL=index.js.map
81
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,40 @@
1
+ import { p as EntityDef, L as ListRecordsQuery, P as PaginatedResponse, m as EavRecord, I as InferValues, a as AttributeFilter, u as UpsertRecordResult, C as CountRecordsQuery, d as BulkUpdateItem, i as DeleteWhereInput, B as BackfillOptions, c as BackfillResult } from './config-CtxyJsDR.js';
2
+
3
+ /** EavRecord with typed values instead of Record<string, unknown> */
4
+ type TypedEavRecord<V> = Omit<EavRecord, "values"> & {
5
+ values: V;
6
+ };
7
+ /** Entity-scoped client with typed records API */
8
+ type EntityClient<E extends EntityDef> = {
9
+ readonly entityName: string;
10
+ records: {
11
+ list(query?: ListRecordsQuery): Promise<PaginatedResponse<TypedEavRecord<InferValues<E>>>>;
12
+ findOne(query?: Omit<ListRecordsQuery, "page">): Promise<TypedEavRecord<InferValues<E>> | null>;
13
+ create(input: {
14
+ authUserId?: string;
15
+ values: InferValues<E>;
16
+ }): Promise<TypedEavRecord<InferValues<E>>>;
17
+ upsert(input: {
18
+ authUserId?: string;
19
+ filters: AttributeFilter[];
20
+ values: InferValues<E>;
21
+ }): Promise<UpsertRecordResult<TypedEavRecord<InferValues<E>>>>;
22
+ get(recordId: string): Promise<TypedEavRecord<InferValues<E>>>;
23
+ update(recordId: string, input: {
24
+ values: Partial<InferValues<E>>;
25
+ }): Promise<TypedEavRecord<InferValues<E>>>;
26
+ delete(recordId: string): Promise<void>;
27
+ count(query?: CountRecordsQuery): Promise<number>;
28
+ bulkCreate(records: Array<{
29
+ authUserId?: string;
30
+ values: InferValues<E>;
31
+ }>): Promise<TypedEavRecord<InferValues<E>>[]>;
32
+ bulkDelete(ids: string[]): Promise<number>;
33
+ bulkUpdate(updates: BulkUpdateItem[]): Promise<TypedEavRecord<InferValues<E>>[]>;
34
+ deleteWhere(input: DeleteWhereInput): Promise<number>;
35
+ listAll(query?: Omit<ListRecordsQuery, "page">): AsyncGenerator<TypedEavRecord<InferValues<E>>>;
36
+ backfill(opts: BackfillOptions): Promise<BackfillResult>;
37
+ };
38
+ };
39
+
40
+ export type { EntityClient as E, TypedEavRecord as T };
@@ -0,0 +1,24 @@
1
+ declare const REOPT_PROVIDER_ID: "reopt";
2
+ declare const REOPT_DEFAULT_SCOPES: readonly ["openid", "profile", "email"];
3
+ type AdapterOperation = "create" | "findOne" | "findMany" | "update" | "updateMany" | "delete" | "deleteMany" | "count";
4
+ type AdapterRequestBody = {
5
+ operation: AdapterOperation;
6
+ model: "user" | "session" | "account" | "verification";
7
+ data?: Record<string, unknown>;
8
+ where?: Array<{
9
+ field: string;
10
+ value: unknown;
11
+ operator?: string;
12
+ connector?: "AND" | "OR";
13
+ }>;
14
+ update?: Record<string, unknown>;
15
+ select?: string[];
16
+ limit?: number;
17
+ offset?: number;
18
+ sortBy?: {
19
+ field: string;
20
+ direction: "asc" | "desc";
21
+ };
22
+ };
23
+
24
+ export { type AdapterOperation as A, REOPT_DEFAULT_SCOPES as R, type AdapterRequestBody as a, REOPT_PROVIDER_ID as b };
@@ -0,0 +1,104 @@
1
+ import { E as EditorSpec } from './types-ckmDDW3N.js';
2
+
3
+ /**
4
+ * Brandapp Terms types.
5
+ *
6
+ * Mirrors the response shape of `/api/v1/brandapp/{brandappId}/terms/*`.
7
+ */
8
+ type TermsType = "termsOfService" | "privacyPolicy" | "marketingConsent" | "custom";
9
+ /** Mirrors the Prisma `BrandappTermsJurisdiction` enum. */
10
+ type TermsJurisdiction = "global" | "KR" | "US" | "EU" | "GB" | "JP" | "CN" | "BR" | "CA" | "AU";
11
+ type TermsVersion = {
12
+ id: string;
13
+ version: number;
14
+ /** 본문 언어 (BCP 47, "ko-KR", "en-US"). */
15
+ locale: string;
16
+ /** Plain-text 본문 — 검색/법적 보존용. */
17
+ content: string;
18
+ /**
19
+ * Rich 본문 — opt-editor `EditorSpec`과 호환되는 minimal shape.
20
+ * 마이그레이션 이전에 작성된 약관은 plain text가 paragraph 1개로 자동 wrap되어 들어있다.
21
+ * `null`은 백엔드 응답에 contentRich 필드가 빠진 구버전 호환을 위해 허용.
22
+ */
23
+ contentRich: EditorSpec | null;
24
+ publishedAt: string;
25
+ changeSummary: string | null;
26
+ reConsentDeadline: string | null;
27
+ };
28
+ type TermsItem = {
29
+ id: string;
30
+ title: string;
31
+ type: TermsType;
32
+ /** 법적 관할권 */
33
+ jurisdiction: TermsJurisdiction;
34
+ isRequired: boolean;
35
+ sortOrder: number;
36
+ /** Null when no matching version exists for the requested locale. */
37
+ currentVersion: TermsVersion | null;
38
+ };
39
+ /** Wrapper response with jurisdiction/locale matching metadata. */
40
+ type TermsListResponse = {
41
+ /** 매칭된 jurisdiction (사용자가 받은 약관 셋의 법적 관할권) */
42
+ jurisdiction: TermsJurisdiction;
43
+ /** 매칭 결정 출처 — geo / user_locale / accept_language / explicit / brandapp_default */
44
+ jurisdictionSource: string;
45
+ /** 매칭에 사용된 country (ISO 3166-1 alpha-2). null이면 brandapp default만 사용. */
46
+ country: string | null;
47
+ /** 매칭에 사용된 locale (BCP 47). */
48
+ locale: string | null;
49
+ /** 매칭된 약관 목록 */
50
+ terms: TermsItem[];
51
+ };
52
+ type ConsentStatus = "granted" | "withdrawn" | "pendingReConsent";
53
+ type ConsentRecord = {
54
+ id: string;
55
+ status: ConsentStatus;
56
+ consentedAt: string;
57
+ withdrawnAt: string | null;
58
+ source: string | null;
59
+ versionId: string;
60
+ termsId: string;
61
+ /** 동의 시점의 국가 (법적 증거) */
62
+ consentCountry: string | null;
63
+ /** 동의 시점의 locale (법적 증거) */
64
+ consentLocale: string | null;
65
+ };
66
+ type ConsentInput = {
67
+ versionId: string;
68
+ consented: boolean;
69
+ };
70
+ type CreateConsentsRequest = {
71
+ consents: ConsentInput[];
72
+ /** Origin tag stored alongside each consent (e.g. "web", "mobile-app"). Defaults to "sdk". */
73
+ source?: string;
74
+ /** Optional caller IP, kept for legal evidence. Server falls back to undefined when omitted. */
75
+ ipAddress?: string;
76
+ /** 동의 시점의 사용자 국가 (ISO 3166-1 alpha-2). 미제공 시 서버가 헤더에서 추정. */
77
+ country?: string;
78
+ /** 동의 시점에 사용자가 본 locale (BCP 47). 미제공 시 서버가 헤더에서 추정. */
79
+ locale?: string;
80
+ /** User-Agent. 미제공 시 서버가 요청 헤더에서 추정. */
81
+ userAgent?: string;
82
+ };
83
+ type CreateConsentsResult = {
84
+ count: number;
85
+ };
86
+ type WithdrawConsentResult = {
87
+ id: string;
88
+ };
89
+ /**
90
+ * `list()` 호출 옵션. country/locale을 지정하면 백엔드가 매칭 약관 셋을 반환한다.
91
+ * 미지정 시 백엔드가 요청 헤더 (`x-vercel-ip-country`, `Accept-Language`)에서 추정한다.
92
+ */
93
+ type ListTermsOptions = {
94
+ /** ISO 3166-1 alpha-2 ("KR", "DE", "US"). */
95
+ country?: string;
96
+ /** BCP 47 ("ko-KR", "en-US"). */
97
+ locale?: string;
98
+ /** Explicit jurisdiction override. */
99
+ jurisdiction?: TermsJurisdiction;
100
+ /** Bearer token. 없으면 Basic Auth. */
101
+ accessToken?: string;
102
+ };
103
+
104
+ export type { ConsentInput as C, ListTermsOptions as L, TermsItem as T, WithdrawConsentResult as W, ConsentRecord as a, ConsentStatus as b, CreateConsentsRequest as c, CreateConsentsResult as d, TermsJurisdiction as e, TermsListResponse as f, TermsType as g, TermsVersion as h };
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Reopt Editor 본문 형식 (post/document `contentRich`).
3
+ *
4
+ * `@reopt-ai/opt-editor`의 `EditorSpec`과 구조적으로 호환되는 minimal 타입.
5
+ * SDK는 opt-editor에 직접 의존하지 않으므로(외부 GitHub Packages 의존을 피하기 위함),
6
+ * 외부 앱은 이 값을 그대로 `<StaticRenderer spec={post.document.contentRich} ... />`에
7
+ * 넘길 수 있다.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * import { StaticRenderer } from "@reopt-ai/opt-editor";
12
+ * import type { EditorSpec } from "@reopt-ai/brandapp-sdk/cms";
13
+ *
14
+ * const post = await sdk.cms.posts.getBySlug(slug);
15
+ * return <StaticRenderer spec={post.document.contentRich} />;
16
+ * ```
17
+ */
18
+ type EditorSpec = {
19
+ /** Top-level element IDs in display order. */
20
+ root: string[];
21
+ /** Flat map of all elements by ID. */
22
+ elements: Record<string, unknown>;
23
+ /** Optimistic concurrency version. Incremented on every mutation. */
24
+ version: number;
25
+ };
26
+ type PostStatus = "draft" | "scheduled" | "published" | "archived";
27
+ type PostSeo = {
28
+ metaTitle: string | null;
29
+ metaDescription: string | null;
30
+ metaKeywords: string | null;
31
+ };
32
+ type Post = {
33
+ id: string;
34
+ slug: string;
35
+ title: string;
36
+ status: PostStatus;
37
+ publishedAt: string | null;
38
+ createdAt: string;
39
+ updatedAt: string;
40
+ author: {
41
+ id: string;
42
+ name: string;
43
+ image: string | null;
44
+ };
45
+ icon: string | null;
46
+ coverImage: {
47
+ id: string;
48
+ url: string | null;
49
+ } | null;
50
+ group: {
51
+ id: string;
52
+ name: string;
53
+ };
54
+ tags: {
55
+ id: string;
56
+ text: string;
57
+ }[];
58
+ seo: PostSeo;
59
+ };
60
+ type PostDetail = Post & {
61
+ document: {
62
+ id: string;
63
+ /** Plain-text 본문 (검색용). */
64
+ content: string;
65
+ /** Rich 본문 — opt-editor `EditorSpec`과 구조적으로 호환. */
66
+ contentRich: EditorSpec;
67
+ };
68
+ };
69
+ type ListPostsQuery = {
70
+ page?: number;
71
+ limit?: number;
72
+ sortBy?: "createdAt" | "updatedAt" | "title" | "publishedAt";
73
+ sortOrder?: "asc" | "desc";
74
+ status?: PostStatus;
75
+ groupId?: string;
76
+ /**
77
+ * 브랜드 범위 내 안정적 그룹 식별자. 신규 코드는 env 기반 groupId 대신 slug 사용 권장.
78
+ * `groupId`와 동시에 지정되면 둘 다 AND 필터로 적용됨.
79
+ */
80
+ groupSlug?: string;
81
+ search?: string;
82
+ tags?: string[];
83
+ };
84
+ type PostGroup = {
85
+ id: string;
86
+ name: string;
87
+ /**
88
+ * 브랜드 범위 내 안정적 식별자. legacy row 또는 미설정 시 null.
89
+ * SDK consumer는 slug 기반 조회를 권장하나, null 가능성을 고려해야 한다.
90
+ */
91
+ slug: string | null;
92
+ color: string;
93
+ createdAt: string;
94
+ updatedAt: string;
95
+ brand: {
96
+ id: string;
97
+ name: string;
98
+ } | null;
99
+ postCount: number;
100
+ };
101
+ type ListPostGroupsQuery = {
102
+ page?: number;
103
+ limit?: number;
104
+ sortBy?: "createdAt" | "name";
105
+ sortOrder?: "asc" | "desc";
106
+ brandId?: string;
107
+ search?: string;
108
+ };
109
+ type Tag = {
110
+ id: string;
111
+ text: string;
112
+ /** Brand 범위 내에서 이 태그가 붙은 포스트 수. */
113
+ postCount: number;
114
+ };
115
+ type ListTagsQuery = {
116
+ /** 특정 그룹으로 필터 (id 기반). 미지정 시 brand 내 전체. */
117
+ groupId?: string;
118
+ /** 특정 그룹으로 필터 (slug 기반). `groupId`와 동시 지정 가능. */
119
+ groupSlug?: string;
120
+ };
121
+ type CmsPaginatedResponse<T> = {
122
+ records: T[];
123
+ page: number;
124
+ limit: number;
125
+ total: number;
126
+ totalPages: number;
127
+ };
128
+
129
+ export type { CmsPaginatedResponse as C, EditorSpec as E, ListPostGroupsQuery as L, Post as P, Tag as T, ListPostsQuery as a, ListTagsQuery as b, PostDetail as c, PostGroup as d, PostSeo as e, PostStatus as f };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Reopt 발신 웹훅 수신 헬퍼.
3
+ *
4
+ * 플랫폼 송신부(`packages/server-core/events/workspace-webhook-delivery.ts`)와
5
+ * **동일한 와이어 포맷**을 검증한다:
6
+ *
7
+ * - 서명 헤더: `x-reopt-signature: sha256=<hex HMAC-SHA256(secret, "{timestamp}.{body}")>`
8
+ * - 타임스탬프 헤더: `x-reopt-timestamp: <epoch millis>` (서명 preimage에 포함 → 위조 불가)
9
+ * - 이벤트 헤더: `x-reopt-event: <trigger>`
10
+ * - envelope: `{ id, type, entityType, entityId, createdAt, data }`
11
+ * - 이벤트 타입: `contactCreated|Updated|Deleted`, `workflowRunCompleted|Failed`
12
+ *
13
+ * (보안 리뷰 F-2 — 과거 SDK 계약은 raw-body hex 서명 + body 내 timestamp를 썼고
14
+ * 실제 플랫폼 송신부와 불일치해 모든 프로덕션 웹훅을 401 거부했다. 이 모듈은 송신부에
15
+ * 정렬되어 있다.)
16
+ */
17
+ type WebhookEventType = "contactCreated" | "contactUpdated" | "contactDeleted" | "workflowRunCompleted" | "workflowRunFailed";
18
+ /**
19
+ * 플랫폼이 전달하는 웹훅 envelope. 모든 이벤트 타입이 같은 형태를 공유한다.
20
+ */
21
+ type WebhookPayload<T = unknown> = {
22
+ /** 멱등 처리용 고유 이벤트 ID (재시도 시 동일) */
23
+ id: string;
24
+ type: WebhookEventType;
25
+ /** 이벤트가 가리키는 엔티티 종류 (예: "contact", "workflowRun") */
26
+ entityType: string;
27
+ /** 엔티티 ID (없을 수 있음) */
28
+ entityId: string | null;
29
+ /** 발신 시각 (ISO 8601) */
30
+ createdAt: string;
31
+ data: T;
32
+ };
33
+ type WebhookHandlers = Partial<Record<WebhookEventType, (payload: WebhookPayload) => void | Promise<void>>>;
34
+ /**
35
+ * Default replay-protection window (5 minutes). Webhooks whose
36
+ * `x-reopt-timestamp` is older than this are rejected with HTTP 410. Set
37
+ * `toleranceMs: 0` to disable.
38
+ */
39
+ declare const DEFAULT_WEBHOOK_TOLERANCE_MS: number;
40
+ /** Default idempotency cache window — events processed within this window are
41
+ * deduplicated by `payload.id`. */
42
+ declare const DEFAULT_IDEMPOTENCY_TTL_MS: number;
43
+ /**
44
+ * Pluggable idempotency store. The handler calls `markProcessed` only after
45
+ * the user-supplied handler runs successfully, so retries triggered by 5xx
46
+ * responses still re-execute the handler — only successful deliveries are
47
+ * deduplicated.
48
+ *
49
+ * Implementations must be safe to call concurrently. Use `createMemoryStore`
50
+ * for single-process apps, or supply your own backed by Redis/Postgres for
51
+ * multi-instance deployments.
52
+ */
53
+ type IdempotencyStore = {
54
+ /** Returns true if `id` has already been marked processed. */
55
+ has(id: string): Promise<boolean> | boolean;
56
+ /** Persist `id` for at least `ttlMs` so subsequent deliveries no-op. */
57
+ markProcessed(id: string, ttlMs: number): Promise<void> | void;
58
+ };
59
+ /**
60
+ * In-memory idempotency store with a soft cap to avoid unbounded growth.
61
+ * Suitable for single-instance dev/preview deployments. For production with
62
+ * multiple replicas, supply a Redis/Postgres-backed store instead.
63
+ */
64
+ declare function createMemoryIdempotencyStore(options?: {
65
+ /** Max number of ids to keep before evicting the oldest. Default 10_000. */
66
+ maxEntries?: number;
67
+ }): IdempotencyStore;
68
+ /**
69
+ * Create a webhook handler for Web-standard `Request` → `Response` runtimes
70
+ * (Next.js App Router route handlers, Edge runtime, Hono, …).
71
+ *
72
+ * Usage:
73
+ * ```ts
74
+ * // app/api/webhooks/reopt/route.ts
75
+ * import { createWebhookHandler } from "@reopt-ai/brandapp-sdk/webhooks";
76
+ *
77
+ * export const POST = createWebhookHandler({
78
+ * secret: process.env.BRANDAPP_WEBHOOK_SECRET!,
79
+ * handlers: {
80
+ * contactCreated: async (payload) => { ... },
81
+ * workflowRunCompleted: async (payload) => { ... },
82
+ * },
83
+ * });
84
+ * ```
85
+ */
86
+ declare function createWebhookHandler(config: {
87
+ secret: string;
88
+ handlers: WebhookHandlers;
89
+ /**
90
+ * Called when a handler throws. Receives `attempt` so you can decide
91
+ * whether to forward to a DLQ vs. let the sender retry. The handler still
92
+ * returns 500 to the caller, ensuring the sender retries by default.
93
+ */
94
+ onError?: (error: Error, payload: WebhookPayload, meta: {
95
+ attempt: number;
96
+ }) => void | Promise<void>;
97
+ /**
98
+ * Max allowed age (ms) of the `x-reopt-timestamp` header before the webhook
99
+ * is rejected as a replay. Defaults to {@link DEFAULT_WEBHOOK_TOLERANCE_MS}.
100
+ * Pass `0` to disable (not recommended in production).
101
+ */
102
+ toleranceMs?: number;
103
+ /**
104
+ * Idempotency: when set, the handler stores `payload.id` after a successful
105
+ * delivery and short-circuits future deliveries of the same id with HTTP
106
+ * 200. Pair with `idempotencyTtlMs` to control the dedupe window.
107
+ *
108
+ * Pass `true` to use an in-memory store (single-instance only) or an
109
+ * {@link IdempotencyStore} backed by Redis/Postgres for multi-instance
110
+ * deployments.
111
+ */
112
+ idempotency?: boolean | IdempotencyStore;
113
+ /** Idempotency cache window. Defaults to {@link DEFAULT_IDEMPOTENCY_TTL_MS}. */
114
+ idempotencyTtlMs?: number;
115
+ }): (request: Request) => Promise<Response>;
116
+ /**
117
+ * Verify a Reopt webhook signature.
118
+ *
119
+ * Recomputes `HMAC-SHA256(secret, "{timestamp}.{body}")` and compares it against
120
+ * the hex digest carried in the `x-reopt-signature` header (the `sha256=` prefix
121
+ * is accepted and stripped). Uses a double-HMAC constant-time comparison so it
122
+ * is safe against timing side-channels and works in Node, Edge, and Browser
123
+ * runtimes.
124
+ *
125
+ * This matches the platform sender's `buildWebhookSignature`
126
+ * (`packages/server-core/events/workspace-webhook-delivery.ts`).
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { verifySignature } from "@reopt-ai/brandapp-sdk/webhooks";
131
+ *
132
+ * const timestamp = request.headers.get("x-reopt-timestamp")!;
133
+ * const signature = request.headers.get("x-reopt-signature")!;
134
+ * const body = await request.text();
135
+ * const ok = await verifySignature(timestamp, body, signature, secret);
136
+ * ```
137
+ */
138
+ declare function verifySignature(timestamp: string, body: string, signature: string, secret: string): Promise<boolean>;
139
+
140
+ export { DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_WEBHOOK_TOLERANCE_MS, type IdempotencyStore, type WebhookEventType, type WebhookHandlers, type WebhookPayload, createMemoryIdempotencyStore, createWebhookHandler, verifySignature };
@@ -0,0 +1,142 @@
1
+ // src/webhooks/index.ts
2
+ var DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1e3;
3
+ var DEFAULT_IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1e3;
4
+ 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
+ };
37
+ }
38
+ 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
+ };
93
+ }
94
+ function jsonResponse(body, status) {
95
+ return new Response(JSON.stringify(body), {
96
+ status,
97
+ headers: { "Content-Type": "application/json" }
98
+ });
99
+ }
100
+ function parseAttemptHeader(value) {
101
+ if (!value) return 1;
102
+ const n = Number(value);
103
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
104
+ }
105
+ function stripSignaturePrefix(signature) {
106
+ return signature.startsWith("sha256=") ? signature.slice("sha256=".length) : signature;
107
+ }
108
+ 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
+ }
138
+ }
139
+
140
+ export { DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_WEBHOOK_TOLERANCE_MS, createMemoryIdempotencyStore, createWebhookHandler, verifySignature };
141
+ //# sourceMappingURL=index.js.map
142
+ //# sourceMappingURL=index.js.map