@instabrain-sdks/api-client 2.6.0 → 2.8.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 (37) hide show
  1. package/README.md +540 -74
  2. package/dist/client/instabrain-client.d.ts +53 -13
  3. package/dist/client/instabrain-client.js +53 -13
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +5 -1
  6. package/dist/services/adb.service.d.ts +1 -1
  7. package/dist/services/adb.service.js +1 -1
  8. package/dist/services/application.service.d.ts +9 -2
  9. package/dist/services/application.service.js +9 -2
  10. package/dist/services/finalexpense.service.d.ts +1 -1
  11. package/dist/services/finalexpense.service.js +1 -1
  12. package/dist/services/gigdb.service.d.ts +19 -8
  13. package/dist/services/gigdb.service.js +20 -9
  14. package/dist/services/ibterm.service.d.ts +17 -5
  15. package/dist/services/ibterm.service.js +17 -5
  16. package/dist/services/pureterm.service.d.ts +12 -4
  17. package/dist/services/pureterm.service.js +12 -4
  18. package/dist/services/reports.service.d.ts +3 -0
  19. package/dist/services/reports.service.js +3 -0
  20. package/dist/types/application.types.d.ts +27 -5
  21. package/dist/types/constants.d.ts +11 -0
  22. package/dist/types/constants.js +12 -1
  23. package/dist/types/enums.d.ts +17 -4
  24. package/dist/types/enums.js +18 -4
  25. package/dist/types/errors.d.ts +4 -4
  26. package/dist/types/errors.js +3 -2
  27. package/dist/types/gigdb.types.d.ts +34 -7
  28. package/dist/types/ibterm.types.d.ts +9 -0
  29. package/dist/types/index.d.ts +1 -7
  30. package/dist/types/index.js +1 -0
  31. package/dist/types/reports.types.d.ts +78 -18
  32. package/dist/types/reports.types.js +29 -2
  33. package/dist/types/webhook.types.d.ts +55 -0
  34. package/dist/types/webhook.types.js +3 -0
  35. package/dist/utils/webhook-signature.d.ts +72 -0
  36. package/dist/utils/webhook-signature.js +172 -0
  37. package/package.json +19 -13
@@ -1,9 +1,12 @@
1
+ import { WebhookRegistrationDetails } from './webhook.types';
1
2
  /**
2
3
  * Request body for `POST /api/ThirdPartyStartApp/start-application`.
3
4
  *
4
- * Generic start-application endpoint used across products that follow the
5
- * pre-fill link hand-off flow (e.g. Pure Term). Returns `agentLink`,
6
- * `applicantLink`, and `eAppAgentLink` for the InstaBrain frontend.
5
+ * The older, generic start-application endpoint. Returns `opportunityId` plus
6
+ * `agentLink`, `applicantLink`, and `eAppAgentLink` for the InstaBrain frontend.
7
+ * IB Term and Pure Term also have dedicated endpoints with full request
8
+ * contracts (`startIBTermApplication()`, `startPureTermApplication()`), which
9
+ * InstaBrain recommends for those products.
7
10
  *
8
11
  * Source of truth: ThirdPartyStartApplicationReq.cs
9
12
  */
@@ -19,14 +22,33 @@ export interface ThirdPartyStartApplicationReq {
19
22
  * Contact InstaBrain support to obtain the correct code for a specific variant.
20
23
  */
21
24
  proCode?: string | null;
25
+ /**
26
+ * Optional. Opt in to application-status webhooks for the opportunity this
27
+ * call creates. Omit or pass `null` for no callbacks. When sent, both
28
+ * `callbackUrl` (absolute HTTPS) and `secretKey` (16–256 characters) are
29
+ * required. See {@link WebhookRegistrationDetails}.
30
+ */
31
+ webhookRegistrationDetails?: WebhookRegistrationDetails | null;
22
32
  }
23
33
  export interface ThirdPartyStartAppResp {
34
+ /**
35
+ * GUID of the created application. Empty or all-zero on a knockout decline,
36
+ * when no application exists. The same value arrives as `opportunityUid` on
37
+ * webhook deliveries — use it to correlate them.
38
+ */
24
39
  opportunityId: string;
25
40
  agentLink: string | null;
26
41
  eAppAgentLink: string | null;
27
42
  applicantLink: string | null;
28
- /** `true` when the application is declined (knockout or underwriting decision). Applies to GIGDB and IB Term. */
43
+ /**
44
+ * `true` when the application is declined (knockout or underwriting decision).
45
+ * Read it with `opportunityId`. Returned by GIGDB, IB Term, and Pure Term;
46
+ * normally `false` on the generic route.
47
+ */
29
48
  isDeclined: boolean;
30
- /** `true` when re-quote logic updated values during start-application processing. Applies to GIGDB and IB Term. */
49
+ /**
50
+ * `true` when re-quote logic updated values during start-application processing.
51
+ * Returned by GIGDB, IB Term, and Pure Term; normally `false` on the generic route.
52
+ */
31
53
  isQuoteChanged: boolean;
32
54
  }
@@ -63,3 +63,14 @@ export declare const BENEFIT_PERIOD_AVAILABILITY: {
63
63
  readonly AGE_45_50_TOBACCO: readonly [10, 20];
64
64
  readonly AGE_51_60: readonly [10, 20];
65
65
  };
66
+ /**
67
+ * `webhookRegistrationDetails` limits on start-application (IB Term, Pure Term,
68
+ * and generic). Reference only — the API validates them and returns HTTP 400
69
+ * `InvalidRequestFormat` when they are not met. `callbackUrl` must also be an
70
+ * absolute HTTPS URL in both sandbox and production.
71
+ */
72
+ export declare const WEBHOOK_REGISTRATION_LIMITS: {
73
+ readonly CALLBACK_URL_MAX_LENGTH: 2048;
74
+ readonly SECRET_KEY_MIN_LENGTH: 16;
75
+ readonly SECRET_KEY_MAX_LENGTH: 256;
76
+ };
@@ -5,7 +5,7 @@
5
5
  * All validation is handled by the API.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.BENEFIT_PERIOD_AVAILABILITY = exports.FACE_AMOUNT_LIMITS_BY_AGE = exports.AGE_LIMITS = exports.RIDER_LIMITS = exports.NO_RIDERS_AVAILABLE_STATES = exports.CHILD_RIDER_UNAVAILABLE_STATES = exports.CHILD_RIDER_AVAILABLE_STATES = exports.ADB_RIDER_AVAILABLE_STATES = exports.UNAVAILABLE_STATES = void 0;
8
+ exports.WEBHOOK_REGISTRATION_LIMITS = exports.BENEFIT_PERIOD_AVAILABILITY = exports.FACE_AMOUNT_LIMITS_BY_AGE = exports.AGE_LIMITS = exports.RIDER_LIMITS = exports.NO_RIDERS_AVAILABLE_STATES = exports.CHILD_RIDER_UNAVAILABLE_STATES = exports.CHILD_RIDER_AVAILABLE_STATES = exports.ADB_RIDER_AVAILABLE_STATES = exports.UNAVAILABLE_STATES = void 0;
9
9
  /** States where the product is not available */
10
10
  exports.UNAVAILABLE_STATES = ['WY', 'NY'];
11
11
  /** States where ADB Rider is available */
@@ -52,3 +52,14 @@ exports.BENEFIT_PERIOD_AVAILABILITY = {
52
52
  AGE_45_50_TOBACCO: [10, 20],
53
53
  AGE_51_60: [10, 20]
54
54
  };
55
+ /**
56
+ * `webhookRegistrationDetails` limits on start-application (IB Term, Pure Term,
57
+ * and generic). Reference only — the API validates them and returns HTTP 400
58
+ * `InvalidRequestFormat` when they are not met. `callbackUrl` must also be an
59
+ * absolute HTTPS URL in both sandbox and production.
60
+ */
61
+ exports.WEBHOOK_REGISTRATION_LIMITS = {
62
+ CALLBACK_URL_MAX_LENGTH: 2048,
63
+ SECRET_KEY_MIN_LENGTH: 16,
64
+ SECRET_KEY_MAX_LENGTH: 256
65
+ };
@@ -537,6 +537,23 @@ export declare enum APIErrorCode {
537
537
  * credit card as mutually exclusive per `opportunityId`.
538
538
  */
539
539
  PaymentAlreadyMade = "PaymentAlreadyMade",
540
+ /**
541
+ * `saveEftPayment()` — `payLaterDate` was sent, but Pay Later is switched off
542
+ * on the platform. The switch is environment-wide, not specific to the
543
+ * opportunity, despite the message wording. Retry without `payLaterDate` to
544
+ * draft immediately. HTTP 400 with the message under `value.fields.PayLaterDate`.
545
+ */
546
+ PayLaterNotAvailable = "PayLaterNotAvailable",
547
+ /**
548
+ * `saveEftPayment()` — `payLaterDate` is outside the allowed range: today
549
+ * (UTC) or earlier, beyond the platform's pay later window (30 days by
550
+ * default), after the applicant's next birthday, or sent on the applicant's
551
+ * birthday (UTC date). HTTP 400 with the message under
552
+ * `value.fields.PayLaterDate`.
553
+ */
554
+ InvalidPaymentScheduledDate = "InvalidPaymentScheduledDate",
555
+ /** `saveEftPayment()` — the EFT details could not be saved. */
556
+ ErrorInSaveEftPaymentDetails = "ErrorInSaveEftPaymentDetails",
540
557
  /** `getCcPaymentIframeUrl()` — a link already exists and the latest attempt has not failed (capture is `pending` or already `approved`). Reuse the URL you already have; a new one is only issued after a `failed` attempt. */
541
558
  TcIframeLinkAlreadyGenerated = "TcIframeLinkAlreadyGenerated",
542
559
  /** `getCcPaymentIframeUrl()` — the product does not support the credit card iframe. Returned for IB Term / Pure Term, which use shared EFT or their hand-off links instead. */
@@ -628,10 +645,6 @@ export declare enum APIErrorCode {
628
645
  InvalidResidenceState = "InvalidResidenceState",
629
646
  /** @deprecated No longer returned as a top-level code. */
630
647
  OneOfTheExistingCoveragesQuestionsNotFound = "OneOfTheExistingCoveragesQuestionsNotFound",
631
- /** @deprecated Prefer `InvalidRequestFormat` on EFT fields. */
632
- ErrorInSaveEftPaymentDetails = "ErrorInSaveEftPaymentDetails",
633
- /** @deprecated Prefer `InvalidRequestFormat` on EFT fields. */
634
- InvalidPaymentScheduledDate = "InvalidPaymentScheduledDate",
635
648
  /** @deprecated Legacy get-existing-quote code; prefer `InvalidRequestFormat`. */
636
649
  ThirdPartyQuoteError = "ThirdPartyQuoteError",
637
650
  /** @deprecated No longer returned as a top-level code. */
@@ -585,6 +585,24 @@ var APIErrorCode;
585
585
  * credit card as mutually exclusive per `opportunityId`.
586
586
  */
587
587
  APIErrorCode["PaymentAlreadyMade"] = "PaymentAlreadyMade";
588
+ // ─── Save EFT payment — business errors (all products) ────────────────────
589
+ /**
590
+ * `saveEftPayment()` — `payLaterDate` was sent, but Pay Later is switched off
591
+ * on the platform. The switch is environment-wide, not specific to the
592
+ * opportunity, despite the message wording. Retry without `payLaterDate` to
593
+ * draft immediately. HTTP 400 with the message under `value.fields.PayLaterDate`.
594
+ */
595
+ APIErrorCode["PayLaterNotAvailable"] = "PayLaterNotAvailable";
596
+ /**
597
+ * `saveEftPayment()` — `payLaterDate` is outside the allowed range: today
598
+ * (UTC) or earlier, beyond the platform's pay later window (30 days by
599
+ * default), after the applicant's next birthday, or sent on the applicant's
600
+ * birthday (UTC date). HTTP 400 with the message under
601
+ * `value.fields.PayLaterDate`.
602
+ */
603
+ APIErrorCode["InvalidPaymentScheduledDate"] = "InvalidPaymentScheduledDate";
604
+ /** `saveEftPayment()` — the EFT details could not be saved. */
605
+ APIErrorCode["ErrorInSaveEftPaymentDetails"] = "ErrorInSaveEftPaymentDetails";
588
606
  // ─── Credit card payment — iframe gates (ADB / GIGDB / Final Expense) ─────
589
607
  /** `getCcPaymentIframeUrl()` — a link already exists and the latest attempt has not failed (capture is `pending` or already `approved`). Reuse the URL you already have; a new one is only issued after a `failed` attempt. */
590
608
  APIErrorCode["TcIframeLinkAlreadyGenerated"] = "TcIframeLinkAlreadyGenerated";
@@ -694,10 +712,6 @@ var APIErrorCode;
694
712
  APIErrorCode["InvalidResidenceState"] = "InvalidResidenceState";
695
713
  /** @deprecated No longer returned as a top-level code. */
696
714
  APIErrorCode["OneOfTheExistingCoveragesQuestionsNotFound"] = "OneOfTheExistingCoveragesQuestionsNotFound";
697
- /** @deprecated Prefer `InvalidRequestFormat` on EFT fields. */
698
- APIErrorCode["ErrorInSaveEftPaymentDetails"] = "ErrorInSaveEftPaymentDetails";
699
- /** @deprecated Prefer `InvalidRequestFormat` on EFT fields. */
700
- APIErrorCode["InvalidPaymentScheduledDate"] = "InvalidPaymentScheduledDate";
701
715
  /** @deprecated Legacy get-existing-quote code; prefer `InvalidRequestFormat`. */
702
716
  APIErrorCode["ThirdPartyQuoteError"] = "ThirdPartyQuoteError";
703
717
  /** @deprecated No longer returned as a top-level code. */
@@ -1,8 +1,8 @@
1
1
  export declare class InstaBrainError extends Error {
2
2
  statusCode?: number | undefined;
3
- response?: any;
3
+ response?: any | undefined;
4
4
  errorCode?: string | undefined;
5
- constructor(message: string, statusCode?: number | undefined, response?: any, errorCode?: string | undefined);
5
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined, errorCode?: string | undefined);
6
6
  }
7
7
  export declare class AuthenticationError extends InstaBrainError {
8
8
  constructor(message?: string);
@@ -16,8 +16,8 @@ export declare class ValidationError extends InstaBrainError {
16
16
  */
17
17
  export declare class APIValidationError extends InstaBrainError {
18
18
  errorCode: string;
19
- response?: any;
20
- constructor(message: string, errorCode: string, response?: any);
19
+ response?: any | undefined;
20
+ constructor(message: string, errorCode: string, response?: any | undefined);
21
21
  /**
22
22
  * Check if this is a specific type of API error
23
23
  */
@@ -116,8 +116,9 @@ class APIValidationError extends InstaBrainError {
116
116
  'InvalidResidenceState': 'The residence state provided is not valid.',
117
117
  'OneOfTheExistingCoveragesQuestionsNotFound': 'One or more existing coverage questions were not answered.',
118
118
  'PaymentAlreadyMade': 'A successful payment already exists for this application. EFT and credit card are mutually exclusive per opportunity.',
119
- 'ErrorInSaveEftPaymentDetails': 'Failed to save EFT payment details. Please verify account information.',
120
- 'InvalidPaymentScheduledDate': 'The scheduled payment date is not valid.',
119
+ 'ErrorInSaveEftPaymentDetails': 'The EFT payment details could not be saved. Please retry; if the issue persists, contact InstaBrain support.',
120
+ 'InvalidPaymentScheduledDate': 'The pay later date must be after today (UTC) and within the pay later window for this application.',
121
+ 'PayLaterNotAvailable': 'Pay later is not available right now. Save the EFT payment without a pay later date to draft it immediately.',
121
122
  'ThirdPartyQuoteError': 'An error occurred while retrieving the quote.',
122
123
  'InvalidQuoteParameters': 'The quote parameters provided are not valid.',
123
124
  'InvalidStateCode': 'State not supported for ADB (MA, NH, AK unavailable; CA coming next release).',
@@ -128,12 +128,13 @@ export interface ThirdPartyGigdbAppReq {
128
128
  /**
129
129
  * Request body for `POST /api/ThirdPartyPayment/save-eft-payment`.
130
130
  *
131
- * Shared across all full-flow products (GIGDB, ADB, Final Expense). Call after
132
- * Start Application and before Prepare Signing Docs. Once EFT is saved, quote
133
- * updates for the same `opportunityId` are blocked.
131
+ * Shared across all products. Call after Start Application and, for full-flow
132
+ * products, before Prepare Signing Docs. Once EFT is saved, quote updates for
133
+ * the same `opportunityId` are blocked.
134
134
  *
135
- * Every field is required server-side. Format failures return
136
- * `InvalidRequestFormat` with the offending PascalCase key under `value.fields`.
135
+ * Every field except `payLaterDate` is required server-side. Format failures
136
+ * return `InvalidRequestFormat` with the offending PascalCase key under
137
+ * `value.fields`.
137
138
  */
138
139
  export interface ThirdPartyEftPaymentReq {
139
140
  /**
@@ -150,16 +151,42 @@ export interface ThirdPartyEftPaymentReq {
150
151
  */
151
152
  opportunityId: string;
152
153
  /**
153
- * Name on the bank account. **Max 100 characters**, and may contain only
154
- * **letters, spaces, hyphens, and apostrophes**.
154
+ * Name on the bank account. Must be at most 100 characters **and** pass the
155
+ * name format rules, which in practice cap it at about **35** characters:
156
+ * letters, spaces, hyphens, apostrophes, and `*`; no consecutive special
157
+ * characters; must end with a letter.
155
158
  *
156
159
  * Errors: `Account holder name is required.` /
157
160
  * `Account holder name must be 100 characters or fewer.` /
158
161
  * `Account holder name may only contain letters, spaces, hyphens, and apostrophes.`
162
+ * (the last one is also returned when the name fails the format rules,
163
+ * including a length over about 35).
159
164
  */
160
165
  accountHolderName: string | null;
161
166
  /** 9-digit US bank routing number. Error: `Routing number must be 9 digits.` */
162
167
  routingNumber: string | null;
163
168
  /** Bank account number, 4–17 digits. Error: `Account number must be 4 to 17 digits.` */
164
169
  accountNumber: string | null;
170
+ /**
171
+ * Optional — schedule the bank draft for a future date (Pay Later). Omit it to
172
+ * draft immediately. There is no separate flag: sending the date is the opt-in.
173
+ *
174
+ * Format: `yyyy-MM-dd`, date only. If a time is included only the date part is
175
+ * used, and a UTC offset can shift the value to a different day first — so
176
+ * never send one.
177
+ *
178
+ * Allowed range, evaluated against the current **UTC** date:
179
+ * - Earliest: tomorrow (UTC). Today (UTC) or earlier is rejected.
180
+ * - Latest: whichever comes first of the platform's pay later window
181
+ * (30 days after today, UTC, by default) and the applicant's next
182
+ * birthday. The birthday itself is allowed.
183
+ * - On the applicant's birthday (UTC date) no `payLaterDate` is accepted.
184
+ * Omit it to draft immediately, or retry the next day (UTC).
185
+ * - A `Time-Zone` request header cannot widen the range.
186
+ *
187
+ * Errors (HTTP 400, message under `value.fields.PayLaterDate`):
188
+ * `PayLaterNotAvailable` when Pay Later is switched off on the platform, or
189
+ * `InvalidPaymentScheduledDate` when the date is outside the range.
190
+ */
191
+ payLaterDate?: string;
165
192
  }
@@ -1,5 +1,6 @@
1
1
  import { Gender, TobaccoNicotineLastUsedPeriod, TobaccoNicotineProductType } from './enums';
2
2
  import { BeneficiaryDetails } from './beneficiary.types';
3
+ import { WebhookRegistrationDetails } from './webhook.types';
3
4
  /** A single IB Term rider option returned for a state/age/nicotine combination. */
4
5
  export interface IBTermRider {
5
6
  /**
@@ -366,4 +367,12 @@ export interface IBTermStartApplicationReq {
366
367
  * the application.
367
368
  */
368
369
  childRiderInfo?: IBTermChildRiderInfo;
370
+ /**
371
+ * Optional. Opt in to application-status webhooks for the opportunity this
372
+ * call creates. Omit or pass `null` for no callbacks. When sent, both
373
+ * `callbackUrl` (absolute HTTPS) and `secretKey` (16–256 characters) are
374
+ * required. Also applies to Pure Term, whose request type is an alias of this
375
+ * one. See {@link WebhookRegistrationDetails}.
376
+ */
377
+ webhookRegistrationDetails?: WebhookRegistrationDetails | null;
369
378
  }
@@ -14,6 +14,7 @@ export * from './finalexpense.types';
14
14
  export * from './payment.types';
15
15
  export * from './pivot.types';
16
16
  export * from './secure-sign.types';
17
+ export * from './webhook.types';
17
18
  /**
18
19
  * Base configuration for the InstaBrain SDK
19
20
  */
@@ -38,13 +39,6 @@ export interface BaseResponse<T> {
38
39
  error: string | null;
39
40
  errorCode?: string;
40
41
  }
41
- export interface AgentPortalReq {
42
- startDate?: string;
43
- endDate?: string;
44
- dayCount?: number;
45
- pageSize: number;
46
- pageIndex: number;
47
- }
48
42
  export interface ThirdPartyQuoterCategory {
49
43
  categoryId: string;
50
44
  categoryType: string | null;
@@ -31,3 +31,4 @@ __exportStar(require("./finalexpense.types"), exports);
31
31
  __exportStar(require("./payment.types"), exports);
32
32
  __exportStar(require("./pivot.types"), exports);
33
33
  __exportStar(require("./secure-sign.types"), exports);
34
+ __exportStar(require("./webhook.types"), exports);
@@ -1,4 +1,34 @@
1
1
  import { RidersList, QuoteParts } from './quote.types';
2
+ /**
3
+ * Filter operators accepted by the reporting APIs (`filters[].operator`), as strings.
4
+ * Use a member (`ReportFilterOperator.In`) or the literal (`'IN'`).
5
+ *
6
+ * | Member | Value | Value format in `filters[].value` |
7
+ * |---|---|---|
8
+ * | `Equal` | `'eq'` | a single value |
9
+ * | `GreaterThan` / `GreaterThanOrEqual` / `LessThan` / `LessThanOrEqual` | `'gt'` / `'gte'` / `'lt'` / `'lte'` | a single number |
10
+ * | `Like` | `'like'` | text the field contains |
11
+ * | `In` | `'IN'` | comma-separated values, e.g. `"Preferred, Standard"` |
12
+ * | `Between` | `'between'` | two comma-separated dates, e.g. `"2026-11-01, 2026-11-03"` |
13
+ */
14
+ export declare const ReportFilterOperator: {
15
+ readonly Equal: "eq";
16
+ readonly GreaterThan: "gt";
17
+ readonly GreaterThanOrEqual: "gte";
18
+ readonly LessThan: "lt";
19
+ readonly LessThanOrEqual: "lte";
20
+ readonly Like: "like";
21
+ readonly In: "IN";
22
+ readonly Between: "between";
23
+ };
24
+ /** One of the string filter operators listed on {@link ReportFilterOperator}. */
25
+ export type ReportFilterOperator = typeof ReportFilterOperator[keyof typeof ReportFilterOperator];
26
+ /**
27
+ * @deprecated The reporting APIs take **string** operators — use {@link ReportFilterOperator}
28
+ * (`ReportFilterOperator.In` / `'IN'`). These numeric values do not match the API: a filter
29
+ * sent with `SQLOperator.In` (`9`) is answered with HTTP 500. Kept only so existing code
30
+ * still compiles; it will be removed in the next major version.
31
+ */
2
32
  export declare enum SQLOperator {
3
33
  Equal = 0,
4
34
  NotEqual = 1,
@@ -13,37 +43,42 @@ export declare enum SQLOperator {
13
43
  NotIn = 10
14
44
  }
15
45
  export interface AgentPortalReqSorting {
16
- /** Field name to sort by */
46
+ /** Field name to sort by (not case sensitive); see each endpoint's supported sort fields */
17
47
  value: string | null;
18
48
  /** Whether to sort in descending order */
19
49
  sortDescending: boolean;
20
50
  }
21
51
  export interface AgentPortalReqFilters {
22
- /** Filter value */
52
+ /** Value to compare with, always a string; its format depends on the operator */
23
53
  value: string | null;
24
- /** SQL operator for the filter */
25
- operator: SQLOperator;
26
- /** Field name to filter on */
54
+ /**
55
+ * Filter operator. The API takes and returns strings ({@link ReportFilterOperator}).
56
+ * The numeric {@link SQLOperator} is still accepted by the type for backward
57
+ * compatibility only — the API rejects it.
58
+ */
59
+ operator: ReportFilterOperator | SQLOperator;
60
+ /** Field name to filter on, written exactly as documented for the endpoint */
27
61
  field: string | null;
28
62
  }
63
+ /** Request body shared by getProspects(), getSales() and getApplications() */
29
64
  export interface AgentPortalReq {
30
- /** Start date for date range filtering */
31
- startDate?: string | null;
32
- /** End date for date range filtering */
33
- endDate?: string | null;
34
- /** User's timezone for date calculations */
65
+ /** Start of the date range, ISO 8601; send together with endDate */
66
+ startDate?: string;
67
+ /** End of the date range, ISO 8601; send together with startDate */
68
+ endDate?: string;
69
+ /** Number of days before today to fetch (alternative to startDate/endDate) */
70
+ dayCount?: number;
71
+ /** Number of items per page; must be greater than 0 */
72
+ pageSize: number;
73
+ /** Page to retrieve; the first page is 1 (0 is rejected) */
74
+ pageIndex: number;
75
+ /** IANA time zone the dates are read in, e.g. `"America/New_York"`; defaults to UTC */
35
76
  userTimeZone?: string | null;
36
- /** Number of days to fetch (alternative to start/end date) */
37
- dayCount?: number | null;
38
- /** Number of items per page */
39
- pageSize?: number | null;
40
- /** Page index (0-based) */
41
- pageIndex?: number | null;
42
77
  /** Sorting configuration */
43
78
  sort?: AgentPortalReqSorting | null;
44
- /** Array of filters to apply */
79
+ /** Filters to apply, combined with AND */
45
80
  filters?: AgentPortalReqFilters[] | null;
46
- /** Search parameter for text search */
81
+ /** Text search to refine results */
47
82
  searchParam?: string | null;
48
83
  }
49
84
  export interface HierarchyData {
@@ -118,8 +153,33 @@ export interface ThirdPartySalesReport {
118
153
  targetPremium?: number | null;
119
154
  riders?: RidersList[] | null;
120
155
  agentHierarchy?: HierarchyData[] | null;
156
+ /**
157
+ * The single current status of the policy: `{Status}`, followed by ` : {Assessment Factor}`
158
+ * only when an assessment factor applies, e.g. `"Approved : Drug Use"` or `"Placed (Inforce)"`.
159
+ * Does NOT contain the rate class (read {@link ThirdPartySalesReport.rateClass}).
160
+ * When an After-Sale status has been received it is one of `Submitted`, `Approved`, `Issued`,
161
+ * `Placed (Inforce)`, `Not Taken (Inforce)`, `Declined`, `Closed`, `Terminated`, `Lapsed`;
162
+ * otherwise it is the normal application status (e.g. `Approved`, `Scheduled`).
163
+ */
121
164
  applicationStatus?: string | null;
165
+ /**
166
+ * Rate class of the policy, returned on its own: `Preferred Plus`, `Preferred`, `Standard`,
167
+ * `Standard Extra`, `Guaranteed`, `Rated C` or `Rated D`. `null` when no rate class applies.
168
+ * Response-only; filter on it with the `rateClass` filter field.
169
+ */
170
+ rateClass?: string | null;
122
171
  paymentMethod?: string | null;
172
+ /**
173
+ * Opportunity UID of the first application in a Pivot chain (e.g. Term => Pure Term => ADB:
174
+ * the ADB sale carries the Term application's UID). `null` when the sale was not pivoted.
175
+ */
176
+ pivotSourceOpportunityUid?: string | null;
177
+ /** Title of the product this application was pivoted from, e.g. `InstaBrain Final Expense`. `null` when not pivoted. */
178
+ pivotedFrom?: string | null;
179
+ /** Why the source application was declined, which started the Pivot flow. `null` when not pivoted. */
180
+ pivotReason?: string | null;
181
+ /** Effective date of the policy, date only (`yyyy-MM-dd`). `null` when not available. */
182
+ paymentEffectiveDate?: string | null;
123
183
  }
124
184
  export interface ThirdPartySalesReportRes {
125
185
  applicationCount: number;
@@ -1,7 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SQLOperator = void 0;
4
- // SQL Operator enum for filters
3
+ exports.SQLOperator = exports.ReportFilterOperator = void 0;
4
+ /**
5
+ * Filter operators accepted by the reporting APIs (`filters[].operator`), as strings.
6
+ * Use a member (`ReportFilterOperator.In`) or the literal (`'IN'`).
7
+ *
8
+ * | Member | Value | Value format in `filters[].value` |
9
+ * |---|---|---|
10
+ * | `Equal` | `'eq'` | a single value |
11
+ * | `GreaterThan` / `GreaterThanOrEqual` / `LessThan` / `LessThanOrEqual` | `'gt'` / `'gte'` / `'lt'` / `'lte'` | a single number |
12
+ * | `Like` | `'like'` | text the field contains |
13
+ * | `In` | `'IN'` | comma-separated values, e.g. `"Preferred, Standard"` |
14
+ * | `Between` | `'between'` | two comma-separated dates, e.g. `"2026-11-01, 2026-11-03"` |
15
+ */
16
+ exports.ReportFilterOperator = {
17
+ Equal: 'eq',
18
+ GreaterThan: 'gt',
19
+ GreaterThanOrEqual: 'gte',
20
+ LessThan: 'lt',
21
+ LessThanOrEqual: 'lte',
22
+ Like: 'like',
23
+ In: 'IN',
24
+ Between: 'between',
25
+ };
26
+ /**
27
+ * @deprecated The reporting APIs take **string** operators — use {@link ReportFilterOperator}
28
+ * (`ReportFilterOperator.In` / `'IN'`). These numeric values do not match the API: a filter
29
+ * sent with `SQLOperator.In` (`9`) is answered with HTTP 500. Kept only so existing code
30
+ * still compiles; it will be removed in the next major version.
31
+ */
5
32
  var SQLOperator;
6
33
  (function (SQLOperator) {
7
34
  SQLOperator[SQLOperator["Equal"] = 0] = "Equal";
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Opt-in details for application-status webhooks, sent on start-application.
3
+ *
4
+ * Accepted by `startIBTermApplication()`, `startPureTermApplication()`, and the
5
+ * generic `startApplication()`. ADB, GIGDB, and Final Expense start-application
6
+ * **silently ignore** it — no error is returned, and no callbacks are registered.
7
+ *
8
+ * - Omit the field or pass `null` for no callbacks — both are treated the same.
9
+ * - When the object is sent, both fields are required. `{}` fails validation.
10
+ * - One callback per opportunity, set at start-application only. There is no API
11
+ * to change the URL or secret afterwards.
12
+ * - Invalid details fail the whole request with HTTP 400 `InvalidRequestFormat`
13
+ * (messages under `value.fields['WebhookRegistrationDetails.CallbackUrl']` /
14
+ * `['WebhookRegistrationDetails.SecretKey']`), and no application is created.
15
+ * - A knockout decline (all-zero `opportunityId`) registers nothing.
16
+ * - Delivery is best-effort. A successful start-application does not guarantee
17
+ * that events will be delivered.
18
+ *
19
+ * On the receiving side, verify every delivery with `verifyWebhookSignature()`.
20
+ */
21
+ export interface WebhookRegistrationDetails {
22
+ /**
23
+ * Absolute HTTPS URL that InstaBrain POSTs events to. Max 2048 characters.
24
+ *
25
+ * HTTPS is required in **both sandbox and production** — `http://` and
26
+ * relative URLs are rejected with `callbackUrl must be an absolute HTTPS URL.`
27
+ * For local testing, use a public HTTPS tunnel.
28
+ */
29
+ callbackUrl: string;
30
+ /**
31
+ * Shared secret, 16–256 characters, used to sign every delivery (HMAC-SHA256).
32
+ *
33
+ * Treat it like an API key: keep it server-side, never log it, and never build
34
+ * start-application requests in a browser. Keep a copy — it cannot be rotated
35
+ * for an existing opportunity, and it is copied to the new opportunity on pivot.
36
+ */
37
+ secretKey: string;
38
+ }
39
+ /** Options for `verifyWebhookSignature()`. */
40
+ export interface VerifyWebhookSignatureOptions {
41
+ /**
42
+ * Maximum allowed difference, in seconds, between `X-InstaBrain-Timestamp` and
43
+ * the current time, in either direction. Defaults to `300` (5 minutes).
44
+ *
45
+ * InstaBrain signs every delivery attempt — retries included — with a fresh
46
+ * timestamp, so a legitimate retry is never older than this window. Must be a
47
+ * positive number. Pass `Infinity` to disable the check.
48
+ */
49
+ toleranceSeconds?: number;
50
+ /**
51
+ * Current Unix time in **seconds** (not milliseconds). Defaults to the system
52
+ * clock. Mainly useful in tests.
53
+ */
54
+ nowSeconds?: number;
55
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ // ── Application-status webhooks (Push API) ───────────────────────────────────
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,72 @@
1
+ import { VerifyWebhookSignatureOptions } from '../types/webhook.types';
2
+ /**
3
+ * Header names InstaBrain sends on every webhook delivery, in the lowercase form
4
+ * Node.js uses for `req.headers`.
5
+ */
6
+ export declare const WEBHOOK_HEADERS: {
7
+ /** Unix time in seconds (UTC) the signature was computed at. Fresh on every attempt. */
8
+ readonly TIMESTAMP: "x-instabrain-timestamp";
9
+ /** Lowercase hex HMAC-SHA256 of `{timestamp}.{rawBody}`. */
10
+ readonly SIGNATURE: "x-instabrain-signature";
11
+ /**
12
+ * Same value as the envelope `eventId`. **Not covered by the signature** — after
13
+ * verifying, deduplicate on the `eventId` inside the body, not on this header.
14
+ */
15
+ readonly EVENT_ID: "x-instabrain-event-id";
16
+ };
17
+ /**
18
+ * Verify that a webhook delivery really came from InstaBrain.
19
+ *
20
+ * Computes HMAC-SHA256 of `{timestamp}.{rawBody}` with the `secretKey` you sent
21
+ * in `webhookRegistrationDetails`, and compares it to `X-InstaBrain-Signature` in
22
+ * constant time. It also rejects a timestamp more than 5 minutes from now
23
+ * (configurable via `options.toleranceSeconds`).
24
+ *
25
+ * Pass the body **exactly as received** — never `JSON.stringify(JSON.parse(body))`,
26
+ * which can change spacing or escaping and break the signature. Parse the JSON
27
+ * only after this returns `true`, then deduplicate on the body's `eventId`.
28
+ *
29
+ * Returns `false` for a missing, malformed, stale, or wrong signature or
30
+ * timestamp. Throws `TypeError` for programming mistakes — an empty secret, a
31
+ * body that is not a string or bytes (e.g. an already-parsed object), or invalid
32
+ * options — so a misconfigured endpoint fails loudly instead of silently
33
+ * rejecting every event. Note that a stray request with a non-JSON
34
+ * `Content-Type` or no body can also reach the body check, because body parsers
35
+ * then leave `req.body` as `{}` or `undefined`. A single `TypeError` is
36
+ * therefore not proof of misconfiguration; one on every InstaBrain delivery is.
37
+ *
38
+ * @param rawBody - Raw request body: a string, or the raw bytes (`Buffer`,
39
+ * `Uint8Array`, or `ArrayBuffer`).
40
+ * @param timestampHeader - Value of the `X-InstaBrain-Timestamp` header.
41
+ * @param signatureHeader - Value of the `X-InstaBrain-Signature` header.
42
+ * @param secretKey - The `secretKey` registered on start-application.
43
+ * @param options - Optional timestamp tolerance and clock override.
44
+ * @returns `true` only when the signature matches and the timestamp is within tolerance.
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * import express from 'express';
49
+ * import { verifyWebhookSignature, WEBHOOK_HEADERS } from '@instabrain-sdks/api-client';
50
+ *
51
+ * // express.raw() on this route, ahead of any app-wide express.json(), keeps
52
+ * // req.body as the raw Buffer. If that is ever misconfigured, the helper throws,
53
+ * // Express answers 500, and InstaBrain retries (5 times, over ~31 minutes) —
54
+ * // a 4xx would drop the event.
55
+ * app.post('/webhooks/instabrain', express.raw({ type: 'application/json' }), (req, res) => {
56
+ * const ok = verifyWebhookSignature(
57
+ * req.body,
58
+ * req.headers[WEBHOOK_HEADERS.TIMESTAMP],
59
+ * req.headers[WEBHOOK_HEADERS.SIGNATURE],
60
+ * process.env.INSTABRAIN_WEBHOOK_SECRET!
61
+ * );
62
+ * if (!ok) {
63
+ * res.sendStatus(401);
64
+ * return;
65
+ * }
66
+ * const event = JSON.parse(req.body.toString('utf8'));
67
+ * // Store event.eventId, then respond 2xx quickly and process asynchronously.
68
+ * res.sendStatus(200);
69
+ * });
70
+ * ```
71
+ */
72
+ export declare function verifyWebhookSignature(rawBody: string | Uint8Array | ArrayBuffer, timestampHeader: string | string[] | null | undefined, signatureHeader: string | string[] | null | undefined, secretKey: string, options?: VerifyWebhookSignatureOptions): boolean;