@hirefinn/sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +79 -9
  2. package/dist/cjs/client.d.ts +13 -1
  3. package/dist/cjs/client.js +5 -0
  4. package/dist/cjs/core.d.ts +14 -2
  5. package/dist/cjs/core.js +41 -4
  6. package/dist/cjs/generated/openapi.d.ts +17426 -5875
  7. package/dist/cjs/generated/operations.d.ts +26 -0
  8. package/dist/cjs/generated/operations.js +165 -0
  9. package/dist/cjs/generated/resources.d.ts +887 -0
  10. package/dist/cjs/generated/resources.js +737 -0
  11. package/dist/cjs/index.d.ts +4 -2
  12. package/dist/cjs/index.js +12 -1
  13. package/dist/cjs/resource.d.ts +30 -0
  14. package/dist/cjs/resource.js +23 -0
  15. package/dist/cjs/resources.d.ts +52 -59
  16. package/dist/cjs/resources.js +27 -37
  17. package/dist/cjs/types.d.ts +17 -5
  18. package/dist/cjs/webhooks.d.ts +57 -0
  19. package/dist/cjs/webhooks.js +181 -0
  20. package/dist/esm/client.d.ts +13 -1
  21. package/dist/esm/client.js +6 -1
  22. package/dist/esm/core.d.ts +14 -2
  23. package/dist/esm/core.js +39 -3
  24. package/dist/esm/generated/openapi.d.ts +17426 -5875
  25. package/dist/esm/generated/operations.d.ts +26 -0
  26. package/dist/esm/generated/operations.js +162 -0
  27. package/dist/esm/generated/resources.d.ts +887 -0
  28. package/dist/esm/generated/resources.js +716 -0
  29. package/dist/esm/index.d.ts +4 -2
  30. package/dist/esm/index.js +2 -1
  31. package/dist/esm/resource.d.ts +30 -0
  32. package/dist/esm/resource.js +19 -0
  33. package/dist/esm/resources.d.ts +52 -59
  34. package/dist/esm/resources.js +20 -35
  35. package/dist/esm/types.d.ts +17 -5
  36. package/dist/esm/webhooks.d.ts +57 -0
  37. package/dist/esm/webhooks.js +140 -0
  38. package/package.json +4 -1
@@ -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.3.0",
4
4
  "description": "Typed TypeScript client for the Finn public API (hirefinn.ai).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,13 +39,16 @@
39
39
  "homepage": "https://hirefinn.ai",
40
40
  "scripts": {
41
41
  "generate": "node scripts/generate.mjs",
42
+ "generate:check": "node scripts/generate.mjs --check",
42
43
  "spec:pull": "sh scripts/pull-spec.sh",
43
44
  "build": "node scripts/build.mjs",
44
45
  "typecheck": "tsc -p tsconfig.json --noEmit",
45
46
  "test": "vitest run",
47
+ "spec:drift": "node scripts/check-drift.mjs",
46
48
  "prepack": "npm run build"
47
49
  },
48
50
  "devDependencies": {
51
+ "@types/node": "20.19.43",
49
52
  "openapi-typescript": "7.13.0",
50
53
  "typescript": "5.9.3",
51
54
  "vitest": "4.1.12"