typizer 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.
- package/CHANGELOG.md +76 -0
- package/README.md +273 -134
- package/dist/client.d.ts +323 -0
- package/dist/client.js +629 -0
- package/dist/core.d.ts +109 -0
- package/dist/core.js +339 -0
- package/dist/errors.d.ts +146 -0
- package/dist/errors.js +281 -0
- package/dist/files.d.ts +42 -0
- package/dist/files.js +159 -0
- package/dist/gen/index.d.ts +2 -2
- package/dist/gen/index.js +1 -1
- package/dist/gen/sdk.gen.d.ts +509 -5
- package/dist/gen/sdk.gen.js +893 -4
- package/dist/gen/types.gen.d.ts +4279 -913
- package/dist/index.d.ts +26 -3
- package/dist/index.js +33 -4
- package/dist/pagination.d.ts +30 -0
- package/dist/pagination.js +49 -0
- package/dist/run.d.ts +50 -0
- package/dist/run.js +45 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/webhooks.d.ts +40 -0
- package/dist/webhooks.js +208 -0
- package/package.json +3 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
export type { Client, ClientOptions, Config } from './gen/client/index.js';
|
|
2
2
|
export * from './gen/index.js';
|
|
3
|
+
import { TypizerClient } from './client.js';
|
|
3
4
|
import type { Client } from './gen/client/index.js';
|
|
4
|
-
|
|
5
|
+
import type { Typizer as GeneratedTypizer } from './gen/types.gen.js';
|
|
6
|
+
export { type BatchCreateParams, Batches, Catalog, type CatalogListParams, type CreateRunParams, DEFAULT_BASE_URL, type ExtractParams, Files, type Format, type ListParams, type Mode, type RunListParams, type RunParams, Runs, TypizerClient, type TypizerCreateParams, type TypizerOptions, Typizers, type TypizerUpdateParams, type WaitParams, WebhookEndpoints, } from './client.js';
|
|
7
|
+
export { APIPromise, type AppInfo, type Logger, type LogLevel, type RequestOptions, type WithResponse, } from './core.js';
|
|
8
|
+
export { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConfigurationError, ConflictError, FileTooLargeError, IdempotencyConflictError, InsufficientBalanceError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, type RateLimitInfo, RunFailedError, ServiceUnavailableError, TypizerError, UnprocessableDocumentError, UnsupportedFileTypeError, WaitTimeoutError, WebhookVerificationError, type WebhookVerificationReason, } from './errors.js';
|
|
9
|
+
export { type FileInput, MAX_FILE_BYTES, type Uploadable } from './files.js';
|
|
10
|
+
export { Page, PagePromise } from './pagination.js';
|
|
11
|
+
export type { FieldResult, FieldSource, FieldToReview, RunHelpers, TypizerRun } from './run.js';
|
|
12
|
+
export { VERSION } from './version.js';
|
|
13
|
+
export { isValidWebhook, type VerifyWebhookOptions, verifyWebhook, type WebhookEvent, type WebhookHeaders, webhooks, } from './webhooks.js';
|
|
14
|
+
/**
|
|
15
|
+
* The client: `new Typizer({ apiKey })` (or `TYPIZER_API_KEY`). The name `Typizer` is both this
|
|
16
|
+
* value and — as a type — the saved-schema model, as in 0.1 (`import type { Typizer }` still means
|
|
17
|
+
* the model); the client's instance type is `TypizerClient`.
|
|
18
|
+
*/
|
|
19
|
+
export declare const Typizer: typeof TypizerClient;
|
|
20
|
+
/** The saved-schema model (`GET /v1/typizers/{id}`), as in 0.1. */
|
|
21
|
+
export type Typizer = GeneratedTypizer;
|
|
22
|
+
/** The saved-schema model under a name that does not clash with the client. */
|
|
23
|
+
export type TypizerModel = GeneratedTypizer;
|
|
24
|
+
export default TypizerClient;
|
|
5
25
|
export interface CreateTypizerClientOptions {
|
|
6
26
|
/** A Typizer API key (`tz_live_…` or `tz_test_…`), sent as `Authorization: Bearer <apiKey>`. */
|
|
7
27
|
apiKey: string;
|
|
@@ -9,12 +29,15 @@ export interface CreateTypizerClientOptions {
|
|
|
9
29
|
baseUrl?: string;
|
|
10
30
|
/** Override the `fetch` implementation (tests, custom runtimes). */
|
|
11
31
|
fetch?: typeof fetch;
|
|
32
|
+
/** Timeout of each request in milliseconds; `0` turns it off. @default 75000 */
|
|
33
|
+
timeout?: number;
|
|
12
34
|
}
|
|
13
35
|
/**
|
|
14
36
|
* Builds a client for the generated SDK functions in `./gen/sdk.gen.ts` (e.g. `getMe`,
|
|
15
37
|
* `createTypizer`), preconfigured with the API key and base URL.
|
|
16
38
|
*
|
|
17
39
|
* Named `createTypizerClient` (not `createTypizer`) because `createTypizer` is already the
|
|
18
|
-
* generated operation for `POST /v1/typizers`.
|
|
40
|
+
* generated operation for `POST /v1/typizers`. For new code prefer `new Typizer({ apiKey })`:
|
|
41
|
+
* retries, idempotency keys, typed errors and `extract` in one call.
|
|
19
42
|
*/
|
|
20
|
-
export declare function createTypizerClient({ apiKey, baseUrl, fetch: fetchImpl, }: CreateTypizerClientOptions): Client;
|
|
43
|
+
export declare function createTypizerClient({ apiKey, baseUrl, fetch: fetchImpl, timeout, }: CreateTypizerClientOptions): Client;
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,46 @@
|
|
|
1
1
|
export * from './gen/index.js';
|
|
2
|
+
// --- The `Typizer` client (SPEC.md) ----------------------------------------------------------
|
|
3
|
+
import { TypizerClient } from './client.js';
|
|
4
|
+
import { anySignal, userAgent } from './core.js';
|
|
2
5
|
import { createClient, createConfig } from './gen/client/index.js';
|
|
3
|
-
export
|
|
6
|
+
export { Batches, Catalog, DEFAULT_BASE_URL, Files, Runs, TypizerClient, Typizers, WebhookEndpoints, } from './client.js';
|
|
7
|
+
export { APIPromise, } from './core.js';
|
|
8
|
+
export { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConfigurationError, ConflictError, FileTooLargeError, IdempotencyConflictError, InsufficientBalanceError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, RunFailedError, ServiceUnavailableError, TypizerError, UnprocessableDocumentError, UnsupportedFileTypeError, WaitTimeoutError, WebhookVerificationError, } from './errors.js';
|
|
9
|
+
export { MAX_FILE_BYTES } from './files.js';
|
|
10
|
+
export { Page, PagePromise } from './pagination.js';
|
|
11
|
+
export { VERSION } from './version.js';
|
|
12
|
+
export { isValidWebhook, verifyWebhook, webhooks, } from './webhooks.js';
|
|
13
|
+
/**
|
|
14
|
+
* The client: `new Typizer({ apiKey })` (or `TYPIZER_API_KEY`). The name `Typizer` is both this
|
|
15
|
+
* value and — as a type — the saved-schema model, as in 0.1 (`import type { Typizer }` still means
|
|
16
|
+
* the model); the client's instance type is `TypizerClient`.
|
|
17
|
+
*/
|
|
18
|
+
export const Typizer = TypizerClient;
|
|
19
|
+
export default TypizerClient;
|
|
4
20
|
/**
|
|
5
21
|
* Builds a client for the generated SDK functions in `./gen/sdk.gen.ts` (e.g. `getMe`,
|
|
6
22
|
* `createTypizer`), preconfigured with the API key and base URL.
|
|
7
23
|
*
|
|
8
24
|
* Named `createTypizerClient` (not `createTypizer`) because `createTypizer` is already the
|
|
9
|
-
* generated operation for `POST /v1/typizers`.
|
|
25
|
+
* generated operation for `POST /v1/typizers`. For new code prefer `new Typizer({ apiKey })`:
|
|
26
|
+
* retries, idempotency keys, typed errors and `extract` in one call.
|
|
10
27
|
*/
|
|
11
|
-
export function createTypizerClient({ apiKey, baseUrl =
|
|
28
|
+
export function createTypizerClient({ apiKey, baseUrl = 'https://api.typizer.ru', fetch: fetchImpl, timeout = 75_000, }) {
|
|
29
|
+
const ua = userAgent();
|
|
30
|
+
const wrapped = (input, init) => {
|
|
31
|
+
const base = fetchImpl ?? globalThis.fetch;
|
|
32
|
+
const request = new Request(input, init);
|
|
33
|
+
const headers = new Headers(request.headers);
|
|
34
|
+
if (!headers.has('User-Agent'))
|
|
35
|
+
headers.set('User-Agent', ua);
|
|
36
|
+
const signal = timeout > 0 && Number.isFinite(timeout)
|
|
37
|
+
? anySignal([request.signal, AbortSignal.timeout(timeout)])
|
|
38
|
+
: request.signal;
|
|
39
|
+
return base(new Request(request, { headers, signal }));
|
|
40
|
+
};
|
|
12
41
|
return createClient(createConfig({
|
|
13
42
|
baseUrl,
|
|
14
43
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
15
|
-
|
|
44
|
+
fetch: wrapped,
|
|
16
45
|
}));
|
|
17
46
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor pagination (SPEC §8): `await client.runs.list()` is one page; `for await (const run of
|
|
3
|
+
* client.runs.list())` walks every item of every page, fetching the next page lazily.
|
|
4
|
+
*/
|
|
5
|
+
import { APIPromise, type WithResponse } from './core.js';
|
|
6
|
+
/** One page of a list. */
|
|
7
|
+
export declare class Page<T> implements AsyncIterable<T> {
|
|
8
|
+
#private;
|
|
9
|
+
readonly object = "list";
|
|
10
|
+
readonly data: T[];
|
|
11
|
+
readonly has_more: boolean;
|
|
12
|
+
readonly next_cursor: string | null;
|
|
13
|
+
constructor(body: {
|
|
14
|
+
data?: T[];
|
|
15
|
+
has_more?: boolean;
|
|
16
|
+
next_cursor?: string | null;
|
|
17
|
+
}, fetchPage: (cursor: string) => PagePromise<T>);
|
|
18
|
+
get hasMore(): boolean;
|
|
19
|
+
get nextCursor(): string | null;
|
|
20
|
+
hasNextPage(): boolean;
|
|
21
|
+
/** The next page (same filter and limit), or `null` after the last one. */
|
|
22
|
+
nextPage(): Promise<Page<T> | null>;
|
|
23
|
+
/** Every item from this page on, fetching later pages as needed. */
|
|
24
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
25
|
+
}
|
|
26
|
+
/** `list()`: awaitable to the first page, and `for await`-iterable over all items. */
|
|
27
|
+
export declare class PagePromise<T> extends APIPromise<Page<T>> implements AsyncIterable<T> {
|
|
28
|
+
constructor(inner: Promise<WithResponse<Page<T>>>);
|
|
29
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cursor pagination (SPEC §8): `await client.runs.list()` is one page; `for await (const run of
|
|
3
|
+
* client.runs.list())` walks every item of every page, fetching the next page lazily.
|
|
4
|
+
*/
|
|
5
|
+
import { APIPromise } from './core.js';
|
|
6
|
+
/** One page of a list. */
|
|
7
|
+
export class Page {
|
|
8
|
+
object = 'list';
|
|
9
|
+
data;
|
|
10
|
+
has_more;
|
|
11
|
+
next_cursor;
|
|
12
|
+
#fetch;
|
|
13
|
+
constructor(body, fetchPage) {
|
|
14
|
+
this.data = body.data ?? [];
|
|
15
|
+
this.has_more = Boolean(body.has_more);
|
|
16
|
+
this.next_cursor = body.next_cursor ?? null;
|
|
17
|
+
this.#fetch = fetchPage;
|
|
18
|
+
}
|
|
19
|
+
get hasMore() {
|
|
20
|
+
return this.has_more;
|
|
21
|
+
}
|
|
22
|
+
get nextCursor() {
|
|
23
|
+
return this.next_cursor;
|
|
24
|
+
}
|
|
25
|
+
hasNextPage() {
|
|
26
|
+
return this.has_more && Boolean(this.next_cursor);
|
|
27
|
+
}
|
|
28
|
+
/** The next page (same filter and limit), or `null` after the last one. */
|
|
29
|
+
async nextPage() {
|
|
30
|
+
return this.hasNextPage() ? await this.#fetch(this.next_cursor) : null;
|
|
31
|
+
}
|
|
32
|
+
/** Every item from this page on, fetching later pages as needed. */
|
|
33
|
+
async *[Symbol.asyncIterator]() {
|
|
34
|
+
let page = this;
|
|
35
|
+
while (page) {
|
|
36
|
+
yield* page.data;
|
|
37
|
+
page = await page.nextPage();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** `list()`: awaitable to the first page, and `for await`-iterable over all items. */
|
|
42
|
+
export class PagePromise extends APIPromise {
|
|
43
|
+
constructor(inner) {
|
|
44
|
+
super(inner);
|
|
45
|
+
}
|
|
46
|
+
async *[Symbol.asyncIterator]() {
|
|
47
|
+
yield* await this;
|
|
48
|
+
}
|
|
49
|
+
}
|
package/dist/run.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A run as the `Typizer` client returns it (SPEC §5.2): the API's JSON object as is, plus
|
|
3
|
+
* non-enumerable helpers that read it without network calls — `JSON.stringify(run)` stays the
|
|
4
|
+
* API's JSON.
|
|
5
|
+
*/
|
|
6
|
+
import type { Run } from './gen/types.gen.js';
|
|
7
|
+
/** Where in the document a value was found. */
|
|
8
|
+
export interface FieldSource {
|
|
9
|
+
/** Page number, from 1. */
|
|
10
|
+
page: number;
|
|
11
|
+
/** `[x0, y0, x1, y1]` in fractions of the page from its top-left corner, or `null`. */
|
|
12
|
+
bbox: [number, number, number, number] | null;
|
|
13
|
+
/** The source text. */
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
/** The check result of one leaf field (`seller.inn`, `items[0].amount`). */
|
|
17
|
+
export interface FieldResult {
|
|
18
|
+
/** `ok`, `warn` (a value that failed a check) or `missing` (no value); an open enum. */
|
|
19
|
+
status: 'ok' | 'warn' | 'missing' | (string & {});
|
|
20
|
+
/** For `warn`: `checksum_mismatch`, `invalid_format`, `sum_mismatch`, `implausible_date`,
|
|
21
|
+
* `no_source`, `code_mismatch` (the value contradicts a barcode or QR code printed on the
|
|
22
|
+
* document), … */
|
|
23
|
+
reason?: string | null;
|
|
24
|
+
sources?: FieldSource[];
|
|
25
|
+
}
|
|
26
|
+
/** A field that needs a human look: `fieldsToReview()`. */
|
|
27
|
+
export interface FieldToReview extends FieldResult {
|
|
28
|
+
/** The field's path in API notation (`seller.inn`, `items[0].amount`). */
|
|
29
|
+
path: string;
|
|
30
|
+
}
|
|
31
|
+
export interface RunHelpers {
|
|
32
|
+
/** `status` is `succeeded` or `failed`. */
|
|
33
|
+
readonly isTerminal: boolean;
|
|
34
|
+
/** The run succeeded and at least one field is not `ok`. */
|
|
35
|
+
readonly needsReview: boolean;
|
|
36
|
+
/** Fields with status `warn` or `missing`, in the order of `fields`. */
|
|
37
|
+
fieldsToReview(): FieldToReview[];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A run with the helpers. `status` is open (a new value from the API is kept as a string), and
|
|
41
|
+
* `output` is typed by `client.extract<Invoice>(…)`; it is `null`/absent until the run succeeds,
|
|
42
|
+
* in list items and once the result has expired (`output_expired`).
|
|
43
|
+
*/
|
|
44
|
+
export type TypizerRun<TOutput = unknown> = Omit<Run, 'status' | 'output' | 'fields'> & {
|
|
45
|
+
status: Run['status'] | (string & {});
|
|
46
|
+
output?: TOutput | null;
|
|
47
|
+
fields: Record<string, FieldResult> | null;
|
|
48
|
+
} & RunHelpers;
|
|
49
|
+
/** Adds the helpers to a run object (in place) and returns it. */
|
|
50
|
+
export declare function withRunHelpers<TOutput = unknown>(run: unknown): TypizerRun<TOutput>;
|
package/dist/run.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const TERMINAL = new Set(['succeeded', 'failed']);
|
|
2
|
+
function toReview(run) {
|
|
3
|
+
const fields = run.fields;
|
|
4
|
+
if (!fields || typeof fields !== 'object')
|
|
5
|
+
return [];
|
|
6
|
+
const out = [];
|
|
7
|
+
for (const [path, f] of Object.entries(fields)) {
|
|
8
|
+
if (f && (f.status === 'warn' || f.status === 'missing'))
|
|
9
|
+
out.push({ path, ...f });
|
|
10
|
+
}
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
const HELPERS = {
|
|
14
|
+
isTerminal: {
|
|
15
|
+
get() {
|
|
16
|
+
return TERMINAL.has(String(this.status));
|
|
17
|
+
},
|
|
18
|
+
enumerable: false,
|
|
19
|
+
configurable: true,
|
|
20
|
+
},
|
|
21
|
+
needsReview: {
|
|
22
|
+
get() {
|
|
23
|
+
if (this.status !== 'succeeded' || !this.fields || typeof this.fields !== 'object')
|
|
24
|
+
return false;
|
|
25
|
+
return Object.values(this.fields).some((f) => f && f.status !== 'ok');
|
|
26
|
+
},
|
|
27
|
+
enumerable: false,
|
|
28
|
+
configurable: true,
|
|
29
|
+
},
|
|
30
|
+
fieldsToReview: {
|
|
31
|
+
value() {
|
|
32
|
+
return toReview(this);
|
|
33
|
+
},
|
|
34
|
+
enumerable: false,
|
|
35
|
+
configurable: true,
|
|
36
|
+
writable: true,
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
/** Adds the helpers to a run object (in place) and returns it. */
|
|
40
|
+
export function withRunHelpers(run) {
|
|
41
|
+
if (run && typeof run === 'object' && !Object.hasOwn(run, 'isTerminal')) {
|
|
42
|
+
Object.defineProperties(run, HELPERS);
|
|
43
|
+
}
|
|
44
|
+
return run;
|
|
45
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Batch, WebhookEventType } from './gen/types.gen.js';
|
|
2
|
+
import { type TypizerRun } from './run.js';
|
|
3
|
+
/** A verified webhook delivery. `type` is open: a new event type is not an error. */
|
|
4
|
+
export interface WebhookEvent<TObject = unknown> {
|
|
5
|
+
/** `evt_…`, the same as `webhook-id`: the deduplication key. */
|
|
6
|
+
id: string;
|
|
7
|
+
type: WebhookEventType | (string & {});
|
|
8
|
+
created_at: string;
|
|
9
|
+
data: {
|
|
10
|
+
object: TObject;
|
|
11
|
+
};
|
|
12
|
+
/** `data.object` for `run.*` events, else `null`. */
|
|
13
|
+
readonly run: TypizerRun | null;
|
|
14
|
+
/** `data.object` for `batch.completed`, else `null`. */
|
|
15
|
+
readonly batch: Batch | null;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Headers as a framework gives them: a plain object (any case, arrays allowed) or `Headers`. */
|
|
19
|
+
export type WebhookHeaders = Headers | Record<string, string | string[] | undefined> | {
|
|
20
|
+
get(name: string): string | null | undefined;
|
|
21
|
+
};
|
|
22
|
+
export interface VerifyWebhookOptions {
|
|
23
|
+
/** Allowed clock skew in seconds (default 300). */
|
|
24
|
+
tolerance?: number;
|
|
25
|
+
/** "Now" in Unix seconds or a `Date` (for tests). */
|
|
26
|
+
now?: number | Date;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Verifies a webhook delivery and returns the event; throws `WebhookVerificationError` (with
|
|
30
|
+
* `reason`) when the signature or the timestamp does not pass. `payload` is the raw body exactly
|
|
31
|
+
* as it came.
|
|
32
|
+
*/
|
|
33
|
+
export declare function verifyWebhook(payload: string | Uint8Array | ArrayBuffer, headers: WebhookHeaders, secret: string, options?: VerifyWebhookOptions): WebhookEvent;
|
|
34
|
+
/** Like `verifyWebhook`, but returns `false` instead of throwing. */
|
|
35
|
+
export declare function isValidWebhook(payload: string | Uint8Array | ArrayBuffer, headers: WebhookHeaders, secret: string, options?: VerifyWebhookOptions): boolean;
|
|
36
|
+
/** `Typizer.webhooks`: the same functions as a namespace. */
|
|
37
|
+
export declare const webhooks: {
|
|
38
|
+
readonly verify: typeof verifyWebhook;
|
|
39
|
+
readonly isValid: typeof isValidWebhook;
|
|
40
|
+
};
|
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webhook signature verification (SPEC §9, Standard Webhooks): no client and no API key needed.
|
|
3
|
+
* Synchronous and dependency-free (HMAC-SHA256 in plain TypeScript), so it runs the same in
|
|
4
|
+
* Node, Bun, Deno and edge runtimes.
|
|
5
|
+
*/
|
|
6
|
+
import { WebhookVerificationError } from './errors.js';
|
|
7
|
+
import { withRunHelpers } from './run.js';
|
|
8
|
+
// --- SHA-256 / HMAC (FIPS 180-4, RFC 2104) -------------------------------------------------
|
|
9
|
+
const K = new Uint32Array([
|
|
10
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
11
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
12
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
13
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
14
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
15
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
16
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
17
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
18
|
+
]);
|
|
19
|
+
function sha256(msg) {
|
|
20
|
+
const len = msg.length;
|
|
21
|
+
const padded = new Uint8Array(((len + 9 + 63) >> 6) << 6);
|
|
22
|
+
padded.set(msg);
|
|
23
|
+
padded[len] = 0x80;
|
|
24
|
+
const view = new DataView(padded.buffer);
|
|
25
|
+
view.setUint32(padded.length - 8, Math.floor(len / 0x20000000));
|
|
26
|
+
view.setUint32(padded.length - 4, (len << 3) >>> 0);
|
|
27
|
+
const h = new Uint32Array([
|
|
28
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
29
|
+
]);
|
|
30
|
+
const w = new Uint32Array(64);
|
|
31
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
32
|
+
for (let i = 0; i < 16; i++)
|
|
33
|
+
w[i] = view.getUint32(off + i * 4);
|
|
34
|
+
for (let i = 16; i < 64; i++) {
|
|
35
|
+
const a = w[i - 15];
|
|
36
|
+
const b = w[i - 2];
|
|
37
|
+
const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);
|
|
38
|
+
const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);
|
|
39
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
40
|
+
}
|
|
41
|
+
let [a, b, c, d, e, f, g, hh] = h;
|
|
42
|
+
for (let i = 0; i < 64; i++) {
|
|
43
|
+
const e_ = e;
|
|
44
|
+
const a_ = a;
|
|
45
|
+
const s1 = ((e_ >>> 6) | (e_ << 26)) ^ ((e_ >>> 11) | (e_ << 21)) ^ ((e_ >>> 25) | (e_ << 7));
|
|
46
|
+
const ch = (e_ & f) ^ (~e_ & g);
|
|
47
|
+
const t1 = (hh + s1 + ch + K[i] + w[i]) >>> 0;
|
|
48
|
+
const s0 = ((a_ >>> 2) | (a_ << 30)) ^ ((a_ >>> 13) | (a_ << 19)) ^ ((a_ >>> 22) | (a_ << 10));
|
|
49
|
+
const maj = (a_ & b) ^ (a_ & c) ^ (b & c);
|
|
50
|
+
const t2 = (s0 + maj) >>> 0;
|
|
51
|
+
hh = g;
|
|
52
|
+
g = f;
|
|
53
|
+
f = e;
|
|
54
|
+
e = (d + t1) >>> 0;
|
|
55
|
+
d = c;
|
|
56
|
+
c = b;
|
|
57
|
+
b = a;
|
|
58
|
+
a = (t1 + t2) >>> 0;
|
|
59
|
+
}
|
|
60
|
+
const add = [a, b, c, d, e, f, g, hh];
|
|
61
|
+
for (let i = 0; i < 8; i++)
|
|
62
|
+
h[i] = (h[i] + add[i]) >>> 0;
|
|
63
|
+
}
|
|
64
|
+
const out = new Uint8Array(32);
|
|
65
|
+
const ov = new DataView(out.buffer);
|
|
66
|
+
for (let i = 0; i < 8; i++)
|
|
67
|
+
ov.setUint32(i * 4, h[i]);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function hmacSha256(key, msg) {
|
|
71
|
+
let k = key.length > 64 ? sha256(key) : key;
|
|
72
|
+
const block = new Uint8Array(64);
|
|
73
|
+
block.set(k);
|
|
74
|
+
k = block;
|
|
75
|
+
const inner = new Uint8Array(64 + msg.length);
|
|
76
|
+
const outer = new Uint8Array(64 + 32);
|
|
77
|
+
for (let i = 0; i < 64; i++) {
|
|
78
|
+
inner[i] = k[i] ^ 0x36;
|
|
79
|
+
outer[i] = k[i] ^ 0x5c;
|
|
80
|
+
}
|
|
81
|
+
inner.set(msg, 64);
|
|
82
|
+
outer.set(sha256(inner), 64);
|
|
83
|
+
return sha256(outer);
|
|
84
|
+
}
|
|
85
|
+
function fromBase64(s) {
|
|
86
|
+
const clean = s.trim();
|
|
87
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1)
|
|
88
|
+
return null;
|
|
89
|
+
try {
|
|
90
|
+
const bin = atob(clean);
|
|
91
|
+
const out = new Uint8Array(bin.length);
|
|
92
|
+
for (let i = 0; i < bin.length; i++)
|
|
93
|
+
out[i] = bin.charCodeAt(i);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function toBase64(bytes) {
|
|
101
|
+
let bin = '';
|
|
102
|
+
for (const b of bytes)
|
|
103
|
+
bin += String.fromCharCode(b);
|
|
104
|
+
return btoa(bin);
|
|
105
|
+
}
|
|
106
|
+
/** Constant-time comparison of two strings of the same alphabet. */
|
|
107
|
+
function safeEqual(a, b) {
|
|
108
|
+
let diff = a.length ^ b.length;
|
|
109
|
+
for (let i = 0; i < a.length; i++)
|
|
110
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i % (b.length || 1));
|
|
111
|
+
return diff === 0;
|
|
112
|
+
}
|
|
113
|
+
function header(headers, name) {
|
|
114
|
+
if (typeof headers.get === 'function') {
|
|
115
|
+
const v = headers.get(name);
|
|
116
|
+
return v ?? undefined;
|
|
117
|
+
}
|
|
118
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
119
|
+
if (k.toLowerCase() === name)
|
|
120
|
+
return Array.isArray(v) ? v[0] : v;
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
const encoder = new TextEncoder();
|
|
125
|
+
const decoder = new TextDecoder();
|
|
126
|
+
function payloadBytes(payload) {
|
|
127
|
+
if (typeof payload === 'string')
|
|
128
|
+
return encoder.encode(payload);
|
|
129
|
+
if (payload instanceof ArrayBuffer)
|
|
130
|
+
return new Uint8Array(payload);
|
|
131
|
+
if (payload instanceof Uint8Array)
|
|
132
|
+
return payload;
|
|
133
|
+
throw new TypeError('typizer: verifyWebhook needs the raw body (a string or bytes), not a parsed object: use express.raw({ type: "application/json" })');
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Verifies a webhook delivery and returns the event; throws `WebhookVerificationError` (with
|
|
137
|
+
* `reason`) when the signature or the timestamp does not pass. `payload` is the raw body exactly
|
|
138
|
+
* as it came.
|
|
139
|
+
*/
|
|
140
|
+
export function verifyWebhook(payload, headers, secret, options = {}) {
|
|
141
|
+
const body = payloadBytes(payload);
|
|
142
|
+
const id = header(headers, 'webhook-id');
|
|
143
|
+
const ts = header(headers, 'webhook-timestamp');
|
|
144
|
+
const signature = header(headers, 'webhook-signature');
|
|
145
|
+
if (!id || !ts || !signature) {
|
|
146
|
+
throw new WebhookVerificationError('missing_header', 'Webhook verification failed: webhook-id, webhook-timestamp or webhook-signature is missing');
|
|
147
|
+
}
|
|
148
|
+
if (!/^\d{1,15}$/.test(ts)) {
|
|
149
|
+
throw new WebhookVerificationError('invalid_timestamp', 'Webhook verification failed: invalid webhook-timestamp');
|
|
150
|
+
}
|
|
151
|
+
const tolerance = options.tolerance ?? 300;
|
|
152
|
+
const now = options.now instanceof Date
|
|
153
|
+
? Math.floor(options.now.getTime() / 1000)
|
|
154
|
+
: (options.now ?? Math.floor(Date.now() / 1000));
|
|
155
|
+
if (Math.abs(now - Number(ts)) > tolerance) {
|
|
156
|
+
throw new WebhookVerificationError('timestamp_out_of_tolerance', `Webhook verification failed: the timestamp is more than ${tolerance}s away from now`);
|
|
157
|
+
}
|
|
158
|
+
const key = fromBase64(secret.startsWith('whsec_') ? secret.slice(6) : secret);
|
|
159
|
+
if (!key || key.length < 24) {
|
|
160
|
+
throw new WebhookVerificationError('invalid_secret', 'Webhook verification failed: the secret is not a whsec_… secret');
|
|
161
|
+
}
|
|
162
|
+
const prefix = encoder.encode(`${id}.${ts}.`);
|
|
163
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
164
|
+
signed.set(prefix);
|
|
165
|
+
signed.set(body, prefix.length);
|
|
166
|
+
const expected = toBase64(hmacSha256(key, signed));
|
|
167
|
+
let matched = false;
|
|
168
|
+
for (const entry of signature.split(' ')) {
|
|
169
|
+
const comma = entry.indexOf(',');
|
|
170
|
+
if (comma < 0 || entry.slice(0, comma) !== 'v1')
|
|
171
|
+
continue;
|
|
172
|
+
// Every entry is compared (no early exit): the time does not tell which one matched.
|
|
173
|
+
if (safeEqual(entry.slice(comma + 1), expected))
|
|
174
|
+
matched = true;
|
|
175
|
+
}
|
|
176
|
+
if (!matched) {
|
|
177
|
+
throw new WebhookVerificationError('signature_mismatch', 'Webhook verification failed: the signature does not match');
|
|
178
|
+
}
|
|
179
|
+
return toEvent(JSON.parse(decoder.decode(body)));
|
|
180
|
+
}
|
|
181
|
+
/** Like `verifyWebhook`, but returns `false` instead of throwing. */
|
|
182
|
+
export function isValidWebhook(payload, headers, secret, options = {}) {
|
|
183
|
+
try {
|
|
184
|
+
verifyWebhook(payload, headers, secret, options);
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function toEvent(value) {
|
|
192
|
+
const event = (value && typeof value === 'object' ? value : {});
|
|
193
|
+
const type = String(event.type ?? '');
|
|
194
|
+
const object = event.data?.object;
|
|
195
|
+
const isRun = type.startsWith('run.') && object && typeof object === 'object';
|
|
196
|
+
if (isRun)
|
|
197
|
+
withRunHelpers(object);
|
|
198
|
+
Object.defineProperties(event, {
|
|
199
|
+
run: { value: isRun ? object : null, enumerable: false },
|
|
200
|
+
batch: {
|
|
201
|
+
value: type === 'batch.completed' && object && typeof object === 'object' ? object : null,
|
|
202
|
+
enumerable: false,
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
return event;
|
|
206
|
+
}
|
|
207
|
+
/** `Typizer.webhooks`: the same functions as a namespace. */
|
|
208
|
+
export const webhooks = { verify: verifyWebhook, isValid: isValidWebhook };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typizer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Официальный TypeScript SDK для Typizer API — извлечение данных из документов в JSON по вашей схеме",
|
|
@@ -39,11 +39,13 @@
|
|
|
39
39
|
"files": [
|
|
40
40
|
"dist",
|
|
41
41
|
"README.md",
|
|
42
|
+
"CHANGELOG.md",
|
|
42
43
|
"LICENSE"
|
|
43
44
|
],
|
|
44
45
|
"devDependencies": {
|
|
45
46
|
"@hey-api/openapi-ts": "^0.99.0",
|
|
46
47
|
"typescript": "6.0.3",
|
|
48
|
+
"@typizer/sdk-spec": "0.0.0",
|
|
47
49
|
"@typizer/config": "0.0.0"
|
|
48
50
|
},
|
|
49
51
|
"scripts": {
|