@instabrain-sdks/api-client 2.6.0 → 2.7.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.
@@ -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
  */
@@ -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);
@@ -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;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WEBHOOK_HEADERS = void 0;
4
+ exports.verifyWebhookSignature = verifyWebhookSignature;
5
+ const crypto_1 = require("crypto");
6
+ /**
7
+ * Header names InstaBrain sends on every webhook delivery, in the lowercase form
8
+ * Node.js uses for `req.headers`.
9
+ */
10
+ exports.WEBHOOK_HEADERS = {
11
+ /** Unix time in seconds (UTC) the signature was computed at. Fresh on every attempt. */
12
+ TIMESTAMP: 'x-instabrain-timestamp',
13
+ /** Lowercase hex HMAC-SHA256 of `{timestamp}.{rawBody}`. */
14
+ SIGNATURE: 'x-instabrain-signature',
15
+ /**
16
+ * Same value as the envelope `eventId`. **Not covered by the signature** — after
17
+ * verifying, deduplicate on the `eventId` inside the body, not on this header.
18
+ */
19
+ EVENT_ID: 'x-instabrain-event-id',
20
+ };
21
+ const DEFAULT_TOLERANCE_SECONDS = 300;
22
+ /** Plain ASCII digits only, as InstaBrain sends them. Bounded to stay a safe integer. */
23
+ const TIMESTAMP_PATTERN = /^[0-9]{1,15}$/;
24
+ /** 32-byte HMAC-SHA256 digest as lowercase hex (the header is lowercased first). */
25
+ const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/;
26
+ /** A "seconds" value this large is almost certainly `Date.now()` milliseconds. */
27
+ const MILLISECONDS_THRESHOLD = 1e11;
28
+ /**
29
+ * Verify that a webhook delivery really came from InstaBrain.
30
+ *
31
+ * Computes HMAC-SHA256 of `{timestamp}.{rawBody}` with the `secretKey` you sent
32
+ * in `webhookRegistrationDetails`, and compares it to `X-InstaBrain-Signature` in
33
+ * constant time. It also rejects a timestamp more than 5 minutes from now
34
+ * (configurable via `options.toleranceSeconds`).
35
+ *
36
+ * Pass the body **exactly as received** — never `JSON.stringify(JSON.parse(body))`,
37
+ * which can change spacing or escaping and break the signature. Parse the JSON
38
+ * only after this returns `true`, then deduplicate on the body's `eventId`.
39
+ *
40
+ * Returns `false` for a missing, malformed, stale, or wrong signature or
41
+ * timestamp. Throws `TypeError` for programming mistakes — an empty secret, a
42
+ * body that is not a string or bytes (e.g. an already-parsed object), or invalid
43
+ * options — so a misconfigured endpoint fails loudly instead of silently
44
+ * rejecting every event. Note that a stray request with a non-JSON
45
+ * `Content-Type` or no body can also reach the body check, because body parsers
46
+ * then leave `req.body` as `{}` or `undefined`. A single `TypeError` is
47
+ * therefore not proof of misconfiguration; one on every InstaBrain delivery is.
48
+ *
49
+ * @param rawBody - Raw request body: a string, or the raw bytes (`Buffer`,
50
+ * `Uint8Array`, or `ArrayBuffer`).
51
+ * @param timestampHeader - Value of the `X-InstaBrain-Timestamp` header.
52
+ * @param signatureHeader - Value of the `X-InstaBrain-Signature` header.
53
+ * @param secretKey - The `secretKey` registered on start-application.
54
+ * @param options - Optional timestamp tolerance and clock override.
55
+ * @returns `true` only when the signature matches and the timestamp is within tolerance.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * import express from 'express';
60
+ * import { verifyWebhookSignature, WEBHOOK_HEADERS } from '@instabrain-sdks/api-client';
61
+ *
62
+ * // express.raw() on this route, ahead of any app-wide express.json(), keeps
63
+ * // req.body as the raw Buffer. If that is ever misconfigured, the helper throws,
64
+ * // Express answers 500, and InstaBrain retries (5 times, over ~31 minutes) —
65
+ * // a 4xx would drop the event.
66
+ * app.post('/webhooks/instabrain', express.raw({ type: 'application/json' }), (req, res) => {
67
+ * const ok = verifyWebhookSignature(
68
+ * req.body,
69
+ * req.headers[WEBHOOK_HEADERS.TIMESTAMP],
70
+ * req.headers[WEBHOOK_HEADERS.SIGNATURE],
71
+ * process.env.INSTABRAIN_WEBHOOK_SECRET!
72
+ * );
73
+ * if (!ok) {
74
+ * res.sendStatus(401);
75
+ * return;
76
+ * }
77
+ * const event = JSON.parse(req.body.toString('utf8'));
78
+ * // Store event.eventId, then respond 2xx quickly and process asynchronously.
79
+ * res.sendStatus(200);
80
+ * });
81
+ * ```
82
+ */
83
+ function verifyWebhookSignature(rawBody, timestampHeader, signatureHeader, secretKey, options) {
84
+ if (typeof secretKey !== 'string' || secretKey.length === 0) {
85
+ throw new TypeError('verifyWebhookSignature: secretKey must be the non-empty string registered on start-application.');
86
+ }
87
+ const body = toBytes(rawBody);
88
+ const toleranceSeconds = resolveTolerance(options);
89
+ const nowSeconds = resolveNow(options);
90
+ const timestamp = singleHeaderValue(timestampHeader);
91
+ if (timestamp === null || !TIMESTAMP_PATTERN.test(timestamp)) {
92
+ return false;
93
+ }
94
+ const rawSignature = singleHeaderValue(signatureHeader);
95
+ if (rawSignature === null) {
96
+ return false;
97
+ }
98
+ const signature = rawSignature.toLowerCase();
99
+ if (!SIGNATURE_PATTERN.test(signature)) {
100
+ return false;
101
+ }
102
+ if (Math.abs(nowSeconds - Number(timestamp)) > toleranceSeconds) {
103
+ return false;
104
+ }
105
+ const expected = (0, crypto_1.createHmac)('sha256', secretKey)
106
+ .update(`${timestamp}.`, 'utf8')
107
+ .update(body)
108
+ .digest();
109
+ return (0, crypto_1.timingSafeEqual)(expected, Buffer.from(signature, 'hex'));
110
+ }
111
+ /**
112
+ * Accept exactly one header value. Node's `req.headers` joins a repeated header
113
+ * into one `"a, b"` string, which the patterns then reject; `req.headersDistinct`
114
+ * and some frameworks give an array instead, so accept a one-element array too.
115
+ */
116
+ function singleHeaderValue(value) {
117
+ if (typeof value === 'string') {
118
+ return value;
119
+ }
120
+ if (Array.isArray(value) && value.length === 1 && typeof value[0] === 'string') {
121
+ return value[0];
122
+ }
123
+ return null;
124
+ }
125
+ function toBytes(rawBody) {
126
+ if (typeof rawBody === 'string') {
127
+ return Buffer.from(rawBody, 'utf8');
128
+ }
129
+ if (ArrayBuffer.isView(rawBody)) {
130
+ return Buffer.from(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength);
131
+ }
132
+ if (Object.prototype.toString.call(rawBody) === '[object ArrayBuffer]') {
133
+ return Buffer.from(rawBody);
134
+ }
135
+ throw new TypeError('verifyWebhookSignature: rawBody must be the raw request body as a string, Buffer, Uint8Array, or ArrayBuffer — ' +
136
+ 'not a parsed JSON object. Read the body raw (for example express.raw({ type: "application/json" })) before verifying.');
137
+ }
138
+ function resolveTolerance(options) {
139
+ const toleranceSeconds = readOptions(options).toleranceSeconds;
140
+ if (toleranceSeconds === undefined) {
141
+ return DEFAULT_TOLERANCE_SECONDS;
142
+ }
143
+ if (toleranceSeconds === Infinity) {
144
+ return Infinity;
145
+ }
146
+ if (typeof toleranceSeconds !== 'number' || !Number.isFinite(toleranceSeconds) || toleranceSeconds <= 0) {
147
+ throw new TypeError('verifyWebhookSignature: options.toleranceSeconds must be a positive number of seconds, or Infinity to disable the check.');
148
+ }
149
+ return toleranceSeconds;
150
+ }
151
+ function resolveNow(options) {
152
+ const nowSeconds = readOptions(options).nowSeconds;
153
+ if (nowSeconds === undefined) {
154
+ return Math.floor(Date.now() / 1000);
155
+ }
156
+ if (typeof nowSeconds !== 'number' || !Number.isFinite(nowSeconds) || nowSeconds < 0) {
157
+ throw new TypeError('verifyWebhookSignature: options.nowSeconds must be a non-negative Unix time in seconds.');
158
+ }
159
+ if (nowSeconds >= MILLISECONDS_THRESHOLD) {
160
+ throw new TypeError('verifyWebhookSignature: options.nowSeconds looks like milliseconds. Pass seconds, e.g. Math.floor(Date.now() / 1000).');
161
+ }
162
+ return nowSeconds;
163
+ }
164
+ function readOptions(options) {
165
+ if (options === undefined) {
166
+ return {};
167
+ }
168
+ if (options === null || typeof options !== 'object') {
169
+ throw new TypeError('verifyWebhookSignature: options must be an object when provided.');
170
+ }
171
+ return options;
172
+ }