@hirefinn/sdk 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -7,7 +7,7 @@ retries, idempotency keys, typed errors, pagination and approval helpers. No run
7
7
  - Node 18+ and modern browsers (anything with `fetch`)
8
8
  - ESM and CommonJS, with `.d.ts` types
9
9
 
10
- > Status: pre-release (0.1.0). MIT licensed (see `LICENSE`).
10
+ > Status: pre-release (0.2.0). MIT licensed (see `LICENSE`).
11
11
 
12
12
  ## Install
13
13
 
@@ -96,12 +96,15 @@ and endpoints newer than the SDK through `finn.rawRequest({ method, path, pathPa
96
96
 
97
97
  ## Retries
98
98
 
99
- Network errors, `408`, `429`, `500`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
99
+ Network errors, `408`, `429`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
100
100
  `maxRetries` times, with exponential backoff (0.5 s, 1 s, 2 s ... up to 8 s, with jitter). A `Retry-After` header
101
- is honoured; one longer than `maxRetryAfterMs` throws instead of waiting.
101
+ is honoured; one longer than `maxRetryAfterMs` throws instead of waiting. A `500` is not retried.
102
102
 
103
- `GET`, `PUT` and `DELETE` are always retried. `POST` and `PATCH` are retried **only when the request carries an
104
- `Idempotency-Key`**, so a retry can never place a call or spend credits twice.
103
+ `GET`, `PUT` and `DELETE` are always retried. A `POST` or `PATCH` is retried **only when it carries an
104
+ `Idempotency-Key` and its route dedupes by that key** (`IDEMPOTENT_WRITE_ROUTES`: calls, phone numbers,
105
+ deployments, chat start/send, agents, case start, `/crm/*` writes, sales play runs and draft skips). Other writes,
106
+ such as `finns.create` or `contacts.create`, are sent once: the API ignores the key there, so a retry after a timeout
107
+ could create a second record. Check with `honoursIdempotencyKey(method, path)`.
105
108
 
106
109
  ## Idempotency keys
107
110
 
@@ -114,10 +117,43 @@ import { idempotencyKey } from '@hirefinn/sdk';
114
117
 
115
118
  const key = idempotencyKey(); // store it with your job
116
119
  await finn.calls.create(body, { idempotencyKey: key }); // same key + same body within 24 h = same answer
117
- await finn.finns.create(body, { idempotencyKey: idempotencyKey() }); // opt in on any other write
118
120
  await finn.calls.create(body, { idempotencyKey: false }); // opt out
119
121
  ```
120
122
 
123
+ The API dedupes by key only on `IDEMPOTENT_WRITE_ROUTES`. Passing a key to another write (for example
124
+ `finns.create`) does not make it safe to retry, and the SDK does not retry it.
125
+
126
+ ## Webhooks
127
+
128
+ Finn signs each delivery with `X-Finn-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`.
129
+ `verifyWebhook` checks it in constant time, refuses timestamps more than 300 s from now, and returns the parsed event.
130
+ Pass the **raw** body, not re-serialised JSON.
131
+
132
+ ```ts
133
+ import express from 'express';
134
+ import { verifyWebhook, FinnWebhookVerificationError } from '@hirefinn/sdk';
135
+
136
+ app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
137
+ try {
138
+ const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
139
+ console.log(event.event, event.data);
140
+ res.sendStatus(200);
141
+ } catch (err) {
142
+ if (err instanceof FinnWebhookVerificationError) return res.sendStatus(400);
143
+ throw err;
144
+ }
145
+ });
146
+ ```
147
+
148
+ Options: `toleranceSeconds` (default 300), and `secret` can be an array while you rotate secrets.
149
+
150
+ ## Approval holds
151
+
152
+ Outward and spending writes from OAuth and MCP callers can answer `202 { status: 'pending_approval', approval_id,
153
+ approve_url, expires_at, action, summary }` instead of doing the work: `calls.create`, `phoneNumbers.rent`,
154
+ `deployments.createOutbound`, `cases.start`, `chat.conversations.start` and `chat.conversations.send`. Their return
155
+ types include `PendingApproval`; narrow with `isPendingApproval(res)` and wait with `finn.waitForApproval(id)`.
156
+
121
157
  ## Errors
122
158
 
123
159
  Every API error throws a `FinnError`, whichever of the API's error shapes it answered with:
@@ -165,7 +201,11 @@ npm run generate -- https://host/openapi.json # from a URL (also copied into
165
201
  BACKEND=../hirefinn-web-app-backend npm run spec:pull # from the backend repo's prod branch
166
202
  ```
167
203
 
168
- Then `npm run typecheck && npm test`. New endpoints are reachable at once through `finn.request(...)`; add a
204
+ Then `npm run typecheck && npm test`.
205
+
206
+ `npm run spec:drift` compares the SDK with the live spec (`https://api.hirefinn.ai/v1/openapi.json`) and fails on
207
+ new or removed endpoints; CI runs it on every PR and daily. Endpoints the SDK knowingly leaves to `rawRequest` are
208
+ listed in `spec/uncovered-ops.json` (`node scripts/check-drift.mjs --write-baseline` rewrites it). New endpoints are reachable at once through `finn.request(...)`; add a
169
209
  resource method in `src/resources.ts` for the ones worth a name.
170
210
 
171
211
  ## Development
@@ -1,6 +1,6 @@
1
1
  import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
2
  export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
- export declare const SDK_VERSION = "0.1.0";
3
+ export declare const SDK_VERSION = "0.2.0";
4
4
  export interface FinnOptions {
5
5
  /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
6
  apiKey?: string;
@@ -10,7 +10,11 @@ export interface FinnOptions {
10
10
  org?: string;
11
11
  /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
12
  version?: string;
13
- /** Retries after the first attempt, on network errors, 408, 429 and 5xx. Default 2. */
13
+ /**
14
+ * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
+ * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
16
+ * that key (IDEMPOTENT_WRITE_ROUTES). Default 2.
17
+ */
14
18
  maxRetries?: number;
15
19
  /** Timeout per attempt in milliseconds. Default 60000. */
16
20
  timeoutMs?: number;
@@ -31,6 +35,14 @@ export interface FinnOptions {
31
35
  }
32
36
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
33
37
  export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
38
+ /**
39
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
40
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
41
+ * after a timeout could create a second resource. `*` matches the rest of the path.
42
+ */
43
+ export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
+ export declare function honoursIdempotencyKey(method: string, path: string): boolean;
34
46
  /** A new random Idempotency-Key (a UUID v4). */
35
47
  export declare function idempotencyKey(): string;
36
48
  /** Untyped request input, for paths the spec does not have yet. */
package/dist/cjs/core.js CHANGED
@@ -12,11 +12,12 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  };
13
13
  var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.FinnCore = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
15
+ exports.FinnCore = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
16
+ exports.honoursIdempotencyKey = honoursIdempotencyKey;
16
17
  exports.idempotencyKey = idempotencyKey;
17
18
  const errors_js_1 = require("./errors.js");
18
19
  exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
19
- exports.SDK_VERSION = '0.1.0';
20
+ exports.SDK_VERSION = '0.2.0';
20
21
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
21
22
  exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
22
23
  'post /calls',
@@ -28,6 +29,39 @@ exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
28
29
  'post /agents',
29
30
  'post /agents/{id}/cases',
30
31
  ]);
32
+ /**
33
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
34
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
35
+ * after a timeout could create a second resource. `*` matches the rest of the path.
36
+ */
37
+ exports.IDEMPOTENT_WRITE_ROUTES = [
38
+ 'post /calls',
39
+ 'post /phone_numbers',
40
+ 'post /deployments',
41
+ 'post /deployments/inbound',
42
+ 'post /chat/conversations',
43
+ 'post /chat/conversations/{id}/messages',
44
+ 'post /agents',
45
+ 'post /agents/{id}/cases',
46
+ 'post /crm/*',
47
+ 'patch /crm/*',
48
+ 'post /sales/plays/{slug}/run',
49
+ 'post /sales/drafts/{id}/skip',
50
+ ];
51
+ const IDEMPOTENT_WRITE_MATCHERS = exports.IDEMPOTENT_WRITE_ROUTES.map((route) => {
52
+ const [method, path] = route.split(' ');
53
+ const body = path
54
+ .split('/')
55
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
56
+ .join('/');
57
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
58
+ });
59
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
60
+ function honoursIdempotencyKey(method, path) {
61
+ const m = method.toUpperCase();
62
+ const p = path.split('?')[0];
63
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
64
+ }
31
65
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
32
66
  const RETRY_BASE_DELAY_MS = 500;
33
67
  const RETRY_MAX_DELAY_MS = 8000;
@@ -141,7 +175,8 @@ class FinnCore {
141
175
  for (const [k, v] of Object.entries(options.headers ?? {}))
142
176
  headers.set(k, v);
143
177
  headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
144
- const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
178
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
179
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
145
180
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
146
181
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
147
182
  for (let attempt = 0;; attempt += 1) {
@@ -240,7 +275,7 @@ function isRetryable(error) {
240
275
  return true;
241
276
  if (error.status === 409)
242
277
  return error.code === 'idempotency_in_progress';
243
- return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
278
+ return error.status === 502 || error.status === 503 || error.status === 504;
244
279
  }
245
280
  function backoffMs(attempt) {
246
281
  const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
@@ -1,6 +1,8 @@
1
1
  export { Finn } from './client.js';
2
2
  export { Finn as default } from './client.js';
3
- export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, idempotencyKey } from './core.js';
3
+ export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, IDEMPOTENT_WRITE_ROUTES, honoursIdempotencyKey, idempotencyKey, } from './core.js';
4
+ export { verifyWebhook, signWebhookPayload, parseSignatureHeader, timingSafeEqual, FinnWebhookVerificationError, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from './webhooks.js';
5
+ export type { VerifyWebhookOptions, WebhookEvent } from './webhooks.js';
4
6
  export type { FinnOptions, RawRequest } from './core.js';
5
7
  export { FinnSdkError, FinnError, FinnConnectionError, FinnTimeoutError, FinnApprovalTimeoutError, codeForStatus, parseRetryAfterSeconds, } from './errors.js';
6
8
  export type { FinnErrorCode, FinnFieldError } from './errors.js';
@@ -8,4 +10,4 @@ export { isPendingApproval } from './approval.js';
8
10
  export { Paginator, cursorStrategy, offsetStrategy, pageStrategy, beforeStrategy } from './pagination.js';
9
11
  export type { PageStrategy } from './pagination.js';
10
12
  export * from './resources.js';
11
- export type { ApprovalHold, BodyOf, FinnResponse, HoldStatus, HttpMethod, Operation, PathParamsOf, PathsFor, PendingApproval, QueryOf, RequestOptions, RequestParams, ResponseOf, ResultOf, Schemas, components, operations, paths, } from './types.js';
13
+ export type { ApprovalHold, BodyOf, FinnResponse, HoldAction, HoldStatus, HoldableRoute, HttpMethod, Operation, PathParamsOf, PathsFor, PendingApproval, QueryOf, RequestOptions, RequestParams, ResponseOf, ResultOf, Schemas, components, operations, paths, } from './types.js';
package/dist/cjs/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.beforeStrategy = exports.pageStrategy = exports.offsetStrategy = exports.cursorStrategy = exports.Paginator = exports.isPendingApproval = exports.parseRetryAfterSeconds = exports.codeForStatus = exports.FinnApprovalTimeoutError = exports.FinnTimeoutError = exports.FinnConnectionError = exports.FinnError = exports.FinnSdkError = exports.idempotencyKey = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = exports.FinnCore = exports.default = exports.Finn = void 0;
17
+ exports.beforeStrategy = exports.pageStrategy = exports.offsetStrategy = exports.cursorStrategy = exports.Paginator = exports.isPendingApproval = exports.parseRetryAfterSeconds = exports.codeForStatus = exports.FinnApprovalTimeoutError = exports.FinnTimeoutError = exports.FinnConnectionError = exports.FinnError = exports.FinnSdkError = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_EVENT_HEADER = exports.WEBHOOK_SIGNATURE_HEADER = exports.FinnWebhookVerificationError = exports.timingSafeEqual = exports.parseSignatureHeader = exports.signWebhookPayload = exports.verifyWebhook = exports.idempotencyKey = exports.honoursIdempotencyKey = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = exports.FinnCore = exports.default = exports.Finn = void 0;
18
18
  var client_js_1 = require("./client.js");
19
19
  Object.defineProperty(exports, "Finn", { enumerable: true, get: function () { return client_js_1.Finn; } });
20
20
  var client_js_2 = require("./client.js");
@@ -24,7 +24,18 @@ Object.defineProperty(exports, "FinnCore", { enumerable: true, get: function ()
24
24
  Object.defineProperty(exports, "DEFAULT_BASE_URL", { enumerable: true, get: function () { return core_js_1.DEFAULT_BASE_URL; } });
25
25
  Object.defineProperty(exports, "SDK_VERSION", { enumerable: true, get: function () { return core_js_1.SDK_VERSION; } });
26
26
  Object.defineProperty(exports, "AUTO_IDEMPOTENCY_ROUTES", { enumerable: true, get: function () { return core_js_1.AUTO_IDEMPOTENCY_ROUTES; } });
27
+ Object.defineProperty(exports, "IDEMPOTENT_WRITE_ROUTES", { enumerable: true, get: function () { return core_js_1.IDEMPOTENT_WRITE_ROUTES; } });
28
+ Object.defineProperty(exports, "honoursIdempotencyKey", { enumerable: true, get: function () { return core_js_1.honoursIdempotencyKey; } });
27
29
  Object.defineProperty(exports, "idempotencyKey", { enumerable: true, get: function () { return core_js_1.idempotencyKey; } });
30
+ var webhooks_js_1 = require("./webhooks.js");
31
+ Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_js_1.verifyWebhook; } });
32
+ Object.defineProperty(exports, "signWebhookPayload", { enumerable: true, get: function () { return webhooks_js_1.signWebhookPayload; } });
33
+ Object.defineProperty(exports, "parseSignatureHeader", { enumerable: true, get: function () { return webhooks_js_1.parseSignatureHeader; } });
34
+ Object.defineProperty(exports, "timingSafeEqual", { enumerable: true, get: function () { return webhooks_js_1.timingSafeEqual; } });
35
+ Object.defineProperty(exports, "FinnWebhookVerificationError", { enumerable: true, get: function () { return webhooks_js_1.FinnWebhookVerificationError; } });
36
+ Object.defineProperty(exports, "WEBHOOK_SIGNATURE_HEADER", { enumerable: true, get: function () { return webhooks_js_1.WEBHOOK_SIGNATURE_HEADER; } });
37
+ Object.defineProperty(exports, "WEBHOOK_EVENT_HEADER", { enumerable: true, get: function () { return webhooks_js_1.WEBHOOK_EVENT_HEADER; } });
38
+ Object.defineProperty(exports, "DEFAULT_WEBHOOK_TOLERANCE_SECONDS", { enumerable: true, get: function () { return webhooks_js_1.DEFAULT_WEBHOOK_TOLERANCE_SECONDS; } });
28
39
  var errors_js_1 = require("./errors.js");
29
40
  Object.defineProperty(exports, "FinnSdkError", { enumerable: true, get: function () { return errors_js_1.FinnSdkError; } });
30
41
  Object.defineProperty(exports, "FinnError", { enumerable: true, get: function () { return errors_js_1.FinnError; } });
@@ -491,13 +491,13 @@ export declare class Cases extends Resource {
491
491
  events: import("./types.js").components["schemas"]["CaseEvent"][];
492
492
  next_after: number;
493
493
  }>;
494
- /** Start a case on an agent. Gets an automatic Idempotency-Key. */
494
+ /** Start a case on an agent. Gets an automatic Idempotency-Key. May answer `pending_approval` (see isPendingApproval). */
495
495
  start(agentId: Id, body?: B<'/agents/{id}/cases', 'post'>, options?: RequestOptions): Promise<{
496
496
  case_id: string;
497
497
  trigger_event_id: string;
498
498
  result: "opened" | "matched" | "reopened";
499
499
  replayed: boolean;
500
- }>;
500
+ } | import("./types.js").PendingApproval>;
501
501
  }
502
502
  export interface WaitForApprovalOptions {
503
503
  /** Time between polls. Default 3000 ms. */
@@ -786,10 +786,10 @@ export declare class ChatConversations extends Resource {
786
786
  has_more: boolean;
787
787
  }>;
788
788
  listAll(query?: Q<'/chat/conversations', 'get'>, options?: RequestOptions): Paginator<ChatItem, unknown>;
789
- /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). */
789
+ /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
790
790
  start(body: B<'/chat/conversations', 'post'>, options?: RequestOptions): Promise<{
791
791
  [key: string]: unknown;
792
- }>;
792
+ } | import("./types.js").PendingApproval>;
793
793
  retrieve(id: Id, options?: RequestOptions): Promise<{
794
794
  conversation: {
795
795
  [key: string]: unknown;
@@ -807,10 +807,10 @@ export declare class ChatConversations extends Resource {
807
807
  has_more: boolean;
808
808
  }>;
809
809
  listAllMessages(id: Id, query?: Q<'/chat/conversations/{id}/messages', 'get'>, options?: RequestOptions): Paginator<ChatItem, unknown>;
810
- /** Send a message. Gets an automatic Idempotency-Key (the API requires one). */
810
+ /** Send a message. Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
811
811
  send(id: Id, body: B<'/chat/conversations/{id}/messages', 'post'>, options?: RequestOptions): Promise<{
812
812
  [key: string]: unknown;
813
- }>;
813
+ } | import("./types.js").PendingApproval>;
814
814
  }
815
815
  export declare class ChatContacts extends Resource {
816
816
  list(query?: Q<'/chat/contacts', 'get'>, options?: RequestOptions): Promise<{
@@ -240,7 +240,7 @@ class Cases extends Resource {
240
240
  listEvents(id, options) {
241
241
  return this.do('get', '/cases/{id}/events', { path: { id } }, options);
242
242
  }
243
- /** Start a case on an agent. Gets an automatic Idempotency-Key. */
243
+ /** Start a case on an agent. Gets an automatic Idempotency-Key. May answer `pending_approval` (see isPendingApproval). */
244
244
  start(agentId, body, options) {
245
245
  return this.do('post', '/agents/{id}/cases', { path: { id: agentId }, body }, options);
246
246
  }
@@ -348,7 +348,7 @@ class ChatConversations extends Resource {
348
348
  listAll(query, options) {
349
349
  return this.pager('/chat/conversations', (0, pagination_js_1.cursorStrategy)('data'), query, undefined, options);
350
350
  }
351
- /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). */
351
+ /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
352
352
  start(body, options) {
353
353
  return this.do('post', '/chat/conversations', { body }, options);
354
354
  }
@@ -361,7 +361,7 @@ class ChatConversations extends Resource {
361
361
  listAllMessages(id, query, options) {
362
362
  return this.pager('/chat/conversations/{id}/messages', (0, pagination_js_1.cursorStrategy)('data'), query, { id }, options);
363
363
  }
364
- /** Send a message. Gets an automatic Idempotency-Key (the API requires one). */
364
+ /** Send a message. Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
365
365
  send(id, body, options) {
366
366
  return this.do('post', '/chat/conversations/{id}/messages', { path: { id }, body }, options);
367
367
  }
@@ -101,9 +101,13 @@ export interface PendingApproval {
101
101
  /** The page in Finn where a person approves it. */
102
102
  approve_url: string;
103
103
  expires_at: string | null;
104
- action?: string;
105
- summary?: unknown;
104
+ /** What was held. */
105
+ action: HoldAction;
106
+ /** A short description of the held request, for showing to the person. */
107
+ summary: unknown;
106
108
  }
109
+ /** The actions the API can hold for approval. */
110
+ export type HoldAction = 'call.create' | 'phone_number.rent' | 'deployment.create' | 'case.start' | 'chat.start' | 'chat.send' | 'contact.stage_move' | 'contact.import' | 'contact.form_link' | 'contact.form_submit' | 'contact.upload_link' | (string & {});
107
111
  /** Status of a held API request as `GET /approvals/{id}` reports it. */
108
112
  export type HoldStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'declined' | 'expired';
109
113
  /** A held API request as `GET /approvals/{id}` returns it to the caller that made it. */
@@ -139,6 +143,6 @@ export interface FinnResponse<T> {
139
143
  idempotentReplayed: boolean;
140
144
  }
141
145
  /** Routes whose writes the API may hold for approval (HTTP 202 `pending_approval`). */
142
- export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers';
146
+ export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers' | 'post /agents/{id}/cases' | 'post /chat/conversations' | 'post /chat/conversations/{id}/messages';
143
147
  /** What `request()` resolves to: the spec's success body, or PendingApproval on holdable routes. */
144
148
  export type ResultOf<P extends string, M extends HttpMethod, O> = `${M} ${P}` extends HoldableRoute ? ResponseOf<O> | PendingApproval : ResponseOf<O>;
@@ -0,0 +1,57 @@
1
+ import { FinnSdkError } from './errors.js';
2
+ /**
3
+ * Webhook signature checks.
4
+ *
5
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
6
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
7
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
8
+ */
9
+ /** Header that carries the signature. */
10
+ export declare const WEBHOOK_SIGNATURE_HEADER = "X-Finn-Signature";
11
+ /** Header that carries the event name. */
12
+ export declare const WEBHOOK_EVENT_HEADER = "X-Finn-Event";
13
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
14
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
15
+ /** The body of every webhook delivery. */
16
+ export interface WebhookEvent<T = Record<string, unknown>> {
17
+ /** e.g. `call.completed`, `contact.created`, `case.completed`. */
18
+ event: string;
19
+ created_at: string;
20
+ data: T;
21
+ }
22
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
23
+ export declare class FinnWebhookVerificationError extends FinnSdkError {
24
+ constructor(message: string);
25
+ }
26
+ export interface VerifyWebhookOptions {
27
+ /** The raw request body, exactly as received (not re-serialised JSON). */
28
+ payload: string | Uint8Array;
29
+ /** The `X-Finn-Signature` value, or the request's headers to read it from. */
30
+ header?: string | null;
31
+ headers?: Headers | Record<string, string | string[] | undefined>;
32
+ /** The endpoint's signing secret (`whsec_...`). Pass several while you rotate secrets. */
33
+ secret: string | readonly string[];
34
+ /** Largest gap between the signed timestamp and now, in seconds. Default 300. */
35
+ toleranceSeconds?: number;
36
+ /** Current time in unix seconds (for tests). */
37
+ now?: number;
38
+ }
39
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
40
+ export declare function parseSignatureHeader(header: string): {
41
+ timestamp: number;
42
+ signatures: string[];
43
+ };
44
+ /** Compares two byte arrays in time that depends only on their length. */
45
+ export declare function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
46
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
47
+ export declare function signWebhookPayload(secret: string, timestamp: number | string, payload: string | Uint8Array): Promise<string>;
48
+ /**
49
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
50
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
51
+ *
52
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
53
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
54
+ * ...
55
+ * });
56
+ */
57
+ export declare function verifyWebhook<T = Record<string, unknown>>(options: VerifyWebhookOptions): Promise<WebhookEvent<T>>;
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FinnWebhookVerificationError = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_EVENT_HEADER = exports.WEBHOOK_SIGNATURE_HEADER = void 0;
37
+ exports.parseSignatureHeader = parseSignatureHeader;
38
+ exports.timingSafeEqual = timingSafeEqual;
39
+ exports.signWebhookPayload = signWebhookPayload;
40
+ exports.verifyWebhook = verifyWebhook;
41
+ const errors_js_1 = require("./errors.js");
42
+ /**
43
+ * Webhook signature checks.
44
+ *
45
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
46
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
47
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
48
+ */
49
+ /** Header that carries the signature. */
50
+ exports.WEBHOOK_SIGNATURE_HEADER = 'X-Finn-Signature';
51
+ /** Header that carries the event name. */
52
+ exports.WEBHOOK_EVENT_HEADER = 'X-Finn-Event';
53
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
54
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
55
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
56
+ class FinnWebhookVerificationError extends errors_js_1.FinnSdkError {
57
+ constructor(message) {
58
+ super(message);
59
+ this.name = 'FinnWebhookVerificationError';
60
+ }
61
+ }
62
+ exports.FinnWebhookVerificationError = FinnWebhookVerificationError;
63
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
64
+ function parseSignatureHeader(header) {
65
+ let timestamp = NaN;
66
+ const signatures = [];
67
+ for (const part of header.split(',')) {
68
+ const i = part.indexOf('=');
69
+ if (i <= 0)
70
+ continue;
71
+ const k = part.slice(0, i).trim();
72
+ const v = part.slice(i + 1).trim();
73
+ if (k === 't' && /^\d+$/.test(v))
74
+ timestamp = Number(v);
75
+ else if (k === 'v1' && v)
76
+ signatures.push(v.toLowerCase());
77
+ }
78
+ return { timestamp, signatures };
79
+ }
80
+ function readHeader(headers) {
81
+ if (!headers)
82
+ return null;
83
+ if (typeof headers.get === 'function')
84
+ return headers.get(exports.WEBHOOK_SIGNATURE_HEADER);
85
+ const want = exports.WEBHOOK_SIGNATURE_HEADER.toLowerCase();
86
+ for (const [k, v] of Object.entries(headers)) {
87
+ if (k.toLowerCase() === want)
88
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
89
+ }
90
+ return null;
91
+ }
92
+ async function subtleCrypto() {
93
+ const c = globalThis.crypto;
94
+ if (c?.subtle)
95
+ return c.subtle;
96
+ // Node 18 without the global: fall back to node:crypto. The specifier is a variable so bundlers leave it alone.
97
+ const name = 'node:crypto';
98
+ const mod = (await Promise.resolve(`${name}`).then(s => __importStar(require(s))));
99
+ return mod.webcrypto.subtle;
100
+ }
101
+ const encoder = new TextEncoder();
102
+ function hexToBytes(hex) {
103
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/.test(hex))
104
+ return null;
105
+ const out = new Uint8Array(hex.length / 2);
106
+ for (let i = 0; i < out.length; i += 1)
107
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
108
+ return out;
109
+ }
110
+ /** Compares two byte arrays in time that depends only on their length. */
111
+ function timingSafeEqual(a, b) {
112
+ if (a.length !== b.length)
113
+ return false;
114
+ let diff = 0;
115
+ for (let i = 0; i < a.length; i += 1)
116
+ diff |= a[i] ^ b[i];
117
+ return diff === 0;
118
+ }
119
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
120
+ async function signWebhookPayload(secret, timestamp, payload) {
121
+ const mac = await hmac(secret, timestamp, payload);
122
+ return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
123
+ }
124
+ async function hmac(secret, timestamp, payload) {
125
+ const subtle = await subtleCrypto();
126
+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
127
+ const body = typeof payload === 'string' ? encoder.encode(payload) : payload;
128
+ const prefix = encoder.encode(`${timestamp}.`);
129
+ const data = new Uint8Array(prefix.length + body.length);
130
+ data.set(prefix, 0);
131
+ data.set(body, prefix.length);
132
+ return new Uint8Array(await subtle.sign('HMAC', key, data));
133
+ }
134
+ /**
135
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
136
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
137
+ *
138
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
139
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
140
+ * ...
141
+ * });
142
+ */
143
+ async function verifyWebhook(options) {
144
+ const { payload } = options;
145
+ if (typeof payload !== 'string' && !(payload instanceof Uint8Array)) {
146
+ throw new FinnWebhookVerificationError('payload must be the raw request body (a string or bytes), not parsed JSON: re-serialising changes the bytes that were signed.');
147
+ }
148
+ const secrets = (typeof options.secret === 'string' ? [options.secret] : [...options.secret]).filter((s) => !!s);
149
+ if (secrets.length === 0)
150
+ throw new FinnWebhookVerificationError('Missing webhook signing secret.');
151
+ const header = options.header ?? readHeader(options.headers);
152
+ if (!header)
153
+ throw new FinnWebhookVerificationError(`Missing ${exports.WEBHOOK_SIGNATURE_HEADER} header.`);
154
+ const { timestamp, signatures } = parseSignatureHeader(header);
155
+ if (!Number.isFinite(timestamp) || signatures.length === 0) {
156
+ throw new FinnWebhookVerificationError(`Malformed ${exports.WEBHOOK_SIGNATURE_HEADER} header: expected t=<unix>,v1=<hex>.`);
157
+ }
158
+ const tolerance = options.toleranceSeconds ?? exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
159
+ const now = options.now ?? Math.floor(Date.now() / 1000);
160
+ if (Math.abs(now - timestamp) > tolerance) {
161
+ throw new FinnWebhookVerificationError('Webhook timestamp is outside the tolerance window.');
162
+ }
163
+ const given = signatures.map(hexToBytes).filter((b) => b !== null);
164
+ let ok = false;
165
+ for (const secret of secrets) {
166
+ const expected = await hmac(secret, timestamp, payload);
167
+ // Check every pair, so the time taken does not reveal which one matched.
168
+ for (const sig of given)
169
+ if (timingSafeEqual(expected, sig))
170
+ ok = true;
171
+ }
172
+ if (!ok)
173
+ throw new FinnWebhookVerificationError('Webhook signature does not match.');
174
+ const text = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);
175
+ try {
176
+ return JSON.parse(text);
177
+ }
178
+ catch {
179
+ throw new FinnWebhookVerificationError('Webhook body is not valid JSON.');
180
+ }
181
+ }
@@ -1,6 +1,6 @@
1
1
  import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
2
  export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
- export declare const SDK_VERSION = "0.1.0";
3
+ export declare const SDK_VERSION = "0.2.0";
4
4
  export interface FinnOptions {
5
5
  /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
6
  apiKey?: string;
@@ -10,7 +10,11 @@ export interface FinnOptions {
10
10
  org?: string;
11
11
  /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
12
  version?: string;
13
- /** Retries after the first attempt, on network errors, 408, 429 and 5xx. Default 2. */
13
+ /**
14
+ * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
+ * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
16
+ * that key (IDEMPOTENT_WRITE_ROUTES). Default 2.
17
+ */
14
18
  maxRetries?: number;
15
19
  /** Timeout per attempt in milliseconds. Default 60000. */
16
20
  timeoutMs?: number;
@@ -31,6 +35,14 @@ export interface FinnOptions {
31
35
  }
32
36
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
33
37
  export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
38
+ /**
39
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
40
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
41
+ * after a timeout could create a second resource. `*` matches the rest of the path.
42
+ */
43
+ export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
+ export declare function honoursIdempotencyKey(method: string, path: string): boolean;
34
46
  /** A new random Idempotency-Key (a UUID v4). */
35
47
  export declare function idempotencyKey(): string;
36
48
  /** Untyped request input, for paths the spec does not have yet. */
package/dist/esm/core.js CHANGED
@@ -12,7 +12,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
13
13
  import { FinnConnectionError, FinnError, FinnSdkError, FinnTimeoutError } from './errors.js';
14
14
  export const DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
15
- export const SDK_VERSION = '0.1.0';
15
+ export const SDK_VERSION = '0.2.0';
16
16
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
17
17
  export const AUTO_IDEMPOTENCY_ROUTES = new Set([
18
18
  'post /calls',
@@ -24,6 +24,39 @@ export const AUTO_IDEMPOTENCY_ROUTES = new Set([
24
24
  'post /agents',
25
25
  'post /agents/{id}/cases',
26
26
  ]);
27
+ /**
28
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
29
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
30
+ * after a timeout could create a second resource. `*` matches the rest of the path.
31
+ */
32
+ export const IDEMPOTENT_WRITE_ROUTES = [
33
+ 'post /calls',
34
+ 'post /phone_numbers',
35
+ 'post /deployments',
36
+ 'post /deployments/inbound',
37
+ 'post /chat/conversations',
38
+ 'post /chat/conversations/{id}/messages',
39
+ 'post /agents',
40
+ 'post /agents/{id}/cases',
41
+ 'post /crm/*',
42
+ 'patch /crm/*',
43
+ 'post /sales/plays/{slug}/run',
44
+ 'post /sales/drafts/{id}/skip',
45
+ ];
46
+ const IDEMPOTENT_WRITE_MATCHERS = IDEMPOTENT_WRITE_ROUTES.map((route) => {
47
+ const [method, path] = route.split(' ');
48
+ const body = path
49
+ .split('/')
50
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
51
+ .join('/');
52
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
53
+ });
54
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
55
+ export function honoursIdempotencyKey(method, path) {
56
+ const m = method.toUpperCase();
57
+ const p = path.split('?')[0];
58
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
59
+ }
27
60
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
28
61
  const RETRY_BASE_DELAY_MS = 500;
29
62
  const RETRY_MAX_DELAY_MS = 8000;
@@ -137,7 +170,8 @@ export class FinnCore {
137
170
  for (const [k, v] of Object.entries(options.headers ?? {}))
138
171
  headers.set(k, v);
139
172
  headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
140
- const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
173
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
174
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
141
175
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
142
176
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
143
177
  for (let attempt = 0;; attempt += 1) {
@@ -235,7 +269,7 @@ function isRetryable(error) {
235
269
  return true;
236
270
  if (error.status === 409)
237
271
  return error.code === 'idempotency_in_progress';
238
- return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
272
+ return error.status === 502 || error.status === 503 || error.status === 504;
239
273
  }
240
274
  function backoffMs(attempt) {
241
275
  const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
@@ -1,6 +1,8 @@
1
1
  export { Finn } from './client.js';
2
2
  export { Finn as default } from './client.js';
3
- export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, idempotencyKey } from './core.js';
3
+ export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, IDEMPOTENT_WRITE_ROUTES, honoursIdempotencyKey, idempotencyKey, } from './core.js';
4
+ export { verifyWebhook, signWebhookPayload, parseSignatureHeader, timingSafeEqual, FinnWebhookVerificationError, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from './webhooks.js';
5
+ export type { VerifyWebhookOptions, WebhookEvent } from './webhooks.js';
4
6
  export type { FinnOptions, RawRequest } from './core.js';
5
7
  export { FinnSdkError, FinnError, FinnConnectionError, FinnTimeoutError, FinnApprovalTimeoutError, codeForStatus, parseRetryAfterSeconds, } from './errors.js';
6
8
  export type { FinnErrorCode, FinnFieldError } from './errors.js';
@@ -8,4 +10,4 @@ export { isPendingApproval } from './approval.js';
8
10
  export { Paginator, cursorStrategy, offsetStrategy, pageStrategy, beforeStrategy } from './pagination.js';
9
11
  export type { PageStrategy } from './pagination.js';
10
12
  export * from './resources.js';
11
- export type { ApprovalHold, BodyOf, FinnResponse, HoldStatus, HttpMethod, Operation, PathParamsOf, PathsFor, PendingApproval, QueryOf, RequestOptions, RequestParams, ResponseOf, ResultOf, Schemas, components, operations, paths, } from './types.js';
13
+ export type { ApprovalHold, BodyOf, FinnResponse, HoldAction, HoldStatus, HoldableRoute, HttpMethod, Operation, PathParamsOf, PathsFor, PendingApproval, QueryOf, RequestOptions, RequestParams, ResponseOf, ResultOf, Schemas, components, operations, paths, } from './types.js';
package/dist/esm/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { Finn } from './client.js';
2
2
  export { Finn as default } from './client.js';
3
- export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, idempotencyKey } from './core.js';
3
+ export { FinnCore, DEFAULT_BASE_URL, SDK_VERSION, AUTO_IDEMPOTENCY_ROUTES, IDEMPOTENT_WRITE_ROUTES, honoursIdempotencyKey, idempotencyKey, } from './core.js';
4
+ export { verifyWebhook, signWebhookPayload, parseSignatureHeader, timingSafeEqual, FinnWebhookVerificationError, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from './webhooks.js';
4
5
  export { FinnSdkError, FinnError, FinnConnectionError, FinnTimeoutError, FinnApprovalTimeoutError, codeForStatus, parseRetryAfterSeconds, } from './errors.js';
5
6
  export { isPendingApproval } from './approval.js';
6
7
  export { Paginator, cursorStrategy, offsetStrategy, pageStrategy, beforeStrategy } from './pagination.js';
@@ -491,13 +491,13 @@ export declare class Cases extends Resource {
491
491
  events: import("./types.js").components["schemas"]["CaseEvent"][];
492
492
  next_after: number;
493
493
  }>;
494
- /** Start a case on an agent. Gets an automatic Idempotency-Key. */
494
+ /** Start a case on an agent. Gets an automatic Idempotency-Key. May answer `pending_approval` (see isPendingApproval). */
495
495
  start(agentId: Id, body?: B<'/agents/{id}/cases', 'post'>, options?: RequestOptions): Promise<{
496
496
  case_id: string;
497
497
  trigger_event_id: string;
498
498
  result: "opened" | "matched" | "reopened";
499
499
  replayed: boolean;
500
- }>;
500
+ } | import("./types.js").PendingApproval>;
501
501
  }
502
502
  export interface WaitForApprovalOptions {
503
503
  /** Time between polls. Default 3000 ms. */
@@ -786,10 +786,10 @@ export declare class ChatConversations extends Resource {
786
786
  has_more: boolean;
787
787
  }>;
788
788
  listAll(query?: Q<'/chat/conversations', 'get'>, options?: RequestOptions): Paginator<ChatItem, unknown>;
789
- /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). */
789
+ /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
790
790
  start(body: B<'/chat/conversations', 'post'>, options?: RequestOptions): Promise<{
791
791
  [key: string]: unknown;
792
- }>;
792
+ } | import("./types.js").PendingApproval>;
793
793
  retrieve(id: Id, options?: RequestOptions): Promise<{
794
794
  conversation: {
795
795
  [key: string]: unknown;
@@ -807,10 +807,10 @@ export declare class ChatConversations extends Resource {
807
807
  has_more: boolean;
808
808
  }>;
809
809
  listAllMessages(id: Id, query?: Q<'/chat/conversations/{id}/messages', 'get'>, options?: RequestOptions): Paginator<ChatItem, unknown>;
810
- /** Send a message. Gets an automatic Idempotency-Key (the API requires one). */
810
+ /** Send a message. Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
811
811
  send(id: Id, body: B<'/chat/conversations/{id}/messages', 'post'>, options?: RequestOptions): Promise<{
812
812
  [key: string]: unknown;
813
- }>;
813
+ } | import("./types.js").PendingApproval>;
814
814
  }
815
815
  export declare class ChatContacts extends Resource {
816
816
  list(query?: Q<'/chat/contacts', 'get'>, options?: RequestOptions): Promise<{
@@ -228,7 +228,7 @@ export class Cases extends Resource {
228
228
  listEvents(id, options) {
229
229
  return this.do('get', '/cases/{id}/events', { path: { id } }, options);
230
230
  }
231
- /** Start a case on an agent. Gets an automatic Idempotency-Key. */
231
+ /** Start a case on an agent. Gets an automatic Idempotency-Key. May answer `pending_approval` (see isPendingApproval). */
232
232
  start(agentId, body, options) {
233
233
  return this.do('post', '/agents/{id}/cases', { path: { id: agentId }, body }, options);
234
234
  }
@@ -333,7 +333,7 @@ export class ChatConversations extends Resource {
333
333
  listAll(query, options) {
334
334
  return this.pager('/chat/conversations', cursorStrategy('data'), query, undefined, options);
335
335
  }
336
- /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). */
336
+ /** Start a conversation (sends the first message). Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
337
337
  start(body, options) {
338
338
  return this.do('post', '/chat/conversations', { body }, options);
339
339
  }
@@ -346,7 +346,7 @@ export class ChatConversations extends Resource {
346
346
  listAllMessages(id, query, options) {
347
347
  return this.pager('/chat/conversations/{id}/messages', cursorStrategy('data'), query, { id }, options);
348
348
  }
349
- /** Send a message. Gets an automatic Idempotency-Key (the API requires one). */
349
+ /** Send a message. Gets an automatic Idempotency-Key (the API requires one). May answer `pending_approval`. */
350
350
  send(id, body, options) {
351
351
  return this.do('post', '/chat/conversations/{id}/messages', { path: { id }, body }, options);
352
352
  }
@@ -101,9 +101,13 @@ export interface PendingApproval {
101
101
  /** The page in Finn where a person approves it. */
102
102
  approve_url: string;
103
103
  expires_at: string | null;
104
- action?: string;
105
- summary?: unknown;
104
+ /** What was held. */
105
+ action: HoldAction;
106
+ /** A short description of the held request, for showing to the person. */
107
+ summary: unknown;
106
108
  }
109
+ /** The actions the API can hold for approval. */
110
+ export type HoldAction = 'call.create' | 'phone_number.rent' | 'deployment.create' | 'case.start' | 'chat.start' | 'chat.send' | 'contact.stage_move' | 'contact.import' | 'contact.form_link' | 'contact.form_submit' | 'contact.upload_link' | (string & {});
107
111
  /** Status of a held API request as `GET /approvals/{id}` reports it. */
108
112
  export type HoldStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'declined' | 'expired';
109
113
  /** A held API request as `GET /approvals/{id}` returns it to the caller that made it. */
@@ -139,6 +143,6 @@ export interface FinnResponse<T> {
139
143
  idempotentReplayed: boolean;
140
144
  }
141
145
  /** Routes whose writes the API may hold for approval (HTTP 202 `pending_approval`). */
142
- export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers';
146
+ export type HoldableRoute = 'post /calls' | 'post /deployments' | 'post /phone_numbers' | 'post /agents/{id}/cases' | 'post /chat/conversations' | 'post /chat/conversations/{id}/messages';
143
147
  /** What `request()` resolves to: the spec's success body, or PendingApproval on holdable routes. */
144
148
  export type ResultOf<P extends string, M extends HttpMethod, O> = `${M} ${P}` extends HoldableRoute ? ResponseOf<O> | PendingApproval : ResponseOf<O>;
@@ -0,0 +1,57 @@
1
+ import { FinnSdkError } from './errors.js';
2
+ /**
3
+ * Webhook signature checks.
4
+ *
5
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
6
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
7
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
8
+ */
9
+ /** Header that carries the signature. */
10
+ export declare const WEBHOOK_SIGNATURE_HEADER = "X-Finn-Signature";
11
+ /** Header that carries the event name. */
12
+ export declare const WEBHOOK_EVENT_HEADER = "X-Finn-Event";
13
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
14
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
15
+ /** The body of every webhook delivery. */
16
+ export interface WebhookEvent<T = Record<string, unknown>> {
17
+ /** e.g. `call.completed`, `contact.created`, `case.completed`. */
18
+ event: string;
19
+ created_at: string;
20
+ data: T;
21
+ }
22
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
23
+ export declare class FinnWebhookVerificationError extends FinnSdkError {
24
+ constructor(message: string);
25
+ }
26
+ export interface VerifyWebhookOptions {
27
+ /** The raw request body, exactly as received (not re-serialised JSON). */
28
+ payload: string | Uint8Array;
29
+ /** The `X-Finn-Signature` value, or the request's headers to read it from. */
30
+ header?: string | null;
31
+ headers?: Headers | Record<string, string | string[] | undefined>;
32
+ /** The endpoint's signing secret (`whsec_...`). Pass several while you rotate secrets. */
33
+ secret: string | readonly string[];
34
+ /** Largest gap between the signed timestamp and now, in seconds. Default 300. */
35
+ toleranceSeconds?: number;
36
+ /** Current time in unix seconds (for tests). */
37
+ now?: number;
38
+ }
39
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
40
+ export declare function parseSignatureHeader(header: string): {
41
+ timestamp: number;
42
+ signatures: string[];
43
+ };
44
+ /** Compares two byte arrays in time that depends only on their length. */
45
+ export declare function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
46
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
47
+ export declare function signWebhookPayload(secret: string, timestamp: number | string, payload: string | Uint8Array): Promise<string>;
48
+ /**
49
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
50
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
51
+ *
52
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
53
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
54
+ * ...
55
+ * });
56
+ */
57
+ export declare function verifyWebhook<T = Record<string, unknown>>(options: VerifyWebhookOptions): Promise<WebhookEvent<T>>;
@@ -0,0 +1,140 @@
1
+ import { FinnSdkError } from './errors.js';
2
+ /**
3
+ * Webhook signature checks.
4
+ *
5
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
6
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
7
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
8
+ */
9
+ /** Header that carries the signature. */
10
+ export const WEBHOOK_SIGNATURE_HEADER = 'X-Finn-Signature';
11
+ /** Header that carries the event name. */
12
+ export const WEBHOOK_EVENT_HEADER = 'X-Finn-Event';
13
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
14
+ export const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
15
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
16
+ export class FinnWebhookVerificationError extends FinnSdkError {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = 'FinnWebhookVerificationError';
20
+ }
21
+ }
22
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
23
+ export function parseSignatureHeader(header) {
24
+ let timestamp = NaN;
25
+ const signatures = [];
26
+ for (const part of header.split(',')) {
27
+ const i = part.indexOf('=');
28
+ if (i <= 0)
29
+ continue;
30
+ const k = part.slice(0, i).trim();
31
+ const v = part.slice(i + 1).trim();
32
+ if (k === 't' && /^\d+$/.test(v))
33
+ timestamp = Number(v);
34
+ else if (k === 'v1' && v)
35
+ signatures.push(v.toLowerCase());
36
+ }
37
+ return { timestamp, signatures };
38
+ }
39
+ function readHeader(headers) {
40
+ if (!headers)
41
+ return null;
42
+ if (typeof headers.get === 'function')
43
+ return headers.get(WEBHOOK_SIGNATURE_HEADER);
44
+ const want = WEBHOOK_SIGNATURE_HEADER.toLowerCase();
45
+ for (const [k, v] of Object.entries(headers)) {
46
+ if (k.toLowerCase() === want)
47
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
48
+ }
49
+ return null;
50
+ }
51
+ async function subtleCrypto() {
52
+ const c = globalThis.crypto;
53
+ if (c?.subtle)
54
+ return c.subtle;
55
+ // Node 18 without the global: fall back to node:crypto. The specifier is a variable so bundlers leave it alone.
56
+ const name = 'node:crypto';
57
+ const mod = (await import(/* @vite-ignore */ /* webpackIgnore: true */ name));
58
+ return mod.webcrypto.subtle;
59
+ }
60
+ const encoder = new TextEncoder();
61
+ function hexToBytes(hex) {
62
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/.test(hex))
63
+ return null;
64
+ const out = new Uint8Array(hex.length / 2);
65
+ for (let i = 0; i < out.length; i += 1)
66
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
67
+ return out;
68
+ }
69
+ /** Compares two byte arrays in time that depends only on their length. */
70
+ export function timingSafeEqual(a, b) {
71
+ if (a.length !== b.length)
72
+ return false;
73
+ let diff = 0;
74
+ for (let i = 0; i < a.length; i += 1)
75
+ diff |= a[i] ^ b[i];
76
+ return diff === 0;
77
+ }
78
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
79
+ export async function signWebhookPayload(secret, timestamp, payload) {
80
+ const mac = await hmac(secret, timestamp, payload);
81
+ return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
82
+ }
83
+ async function hmac(secret, timestamp, payload) {
84
+ const subtle = await subtleCrypto();
85
+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
86
+ const body = typeof payload === 'string' ? encoder.encode(payload) : payload;
87
+ const prefix = encoder.encode(`${timestamp}.`);
88
+ const data = new Uint8Array(prefix.length + body.length);
89
+ data.set(prefix, 0);
90
+ data.set(body, prefix.length);
91
+ return new Uint8Array(await subtle.sign('HMAC', key, data));
92
+ }
93
+ /**
94
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
95
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
96
+ *
97
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
98
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
99
+ * ...
100
+ * });
101
+ */
102
+ export async function verifyWebhook(options) {
103
+ const { payload } = options;
104
+ if (typeof payload !== 'string' && !(payload instanceof Uint8Array)) {
105
+ throw new FinnWebhookVerificationError('payload must be the raw request body (a string or bytes), not parsed JSON: re-serialising changes the bytes that were signed.');
106
+ }
107
+ const secrets = (typeof options.secret === 'string' ? [options.secret] : [...options.secret]).filter((s) => !!s);
108
+ if (secrets.length === 0)
109
+ throw new FinnWebhookVerificationError('Missing webhook signing secret.');
110
+ const header = options.header ?? readHeader(options.headers);
111
+ if (!header)
112
+ throw new FinnWebhookVerificationError(`Missing ${WEBHOOK_SIGNATURE_HEADER} header.`);
113
+ const { timestamp, signatures } = parseSignatureHeader(header);
114
+ if (!Number.isFinite(timestamp) || signatures.length === 0) {
115
+ throw new FinnWebhookVerificationError(`Malformed ${WEBHOOK_SIGNATURE_HEADER} header: expected t=<unix>,v1=<hex>.`);
116
+ }
117
+ const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
118
+ const now = options.now ?? Math.floor(Date.now() / 1000);
119
+ if (Math.abs(now - timestamp) > tolerance) {
120
+ throw new FinnWebhookVerificationError('Webhook timestamp is outside the tolerance window.');
121
+ }
122
+ const given = signatures.map(hexToBytes).filter((b) => b !== null);
123
+ let ok = false;
124
+ for (const secret of secrets) {
125
+ const expected = await hmac(secret, timestamp, payload);
126
+ // Check every pair, so the time taken does not reveal which one matched.
127
+ for (const sig of given)
128
+ if (timingSafeEqual(expected, sig))
129
+ ok = true;
130
+ }
131
+ if (!ok)
132
+ throw new FinnWebhookVerificationError('Webhook signature does not match.');
133
+ const text = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);
134
+ try {
135
+ return JSON.parse(text);
136
+ }
137
+ catch {
138
+ throw new FinnWebhookVerificationError('Webhook body is not valid JSON.');
139
+ }
140
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hirefinn/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Typed TypeScript client for the Finn public API (hirefinn.ai).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,9 +43,11 @@
43
43
  "build": "node scripts/build.mjs",
44
44
  "typecheck": "tsc -p tsconfig.json --noEmit",
45
45
  "test": "vitest run",
46
+ "spec:drift": "node scripts/check-drift.mjs",
46
47
  "prepack": "npm run build"
47
48
  },
48
49
  "devDependencies": {
50
+ "@types/node": "20.19.43",
49
51
  "openapi-typescript": "7.13.0",
50
52
  "typescript": "5.9.3",
51
53
  "vitest": "4.1.12"