@timbereye/sdk 0.0.0-stage → 0.1.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 +68 -0
- package/LICENSE +202 -0
- package/README.md +330 -2
- package/dist/cjs/case.d.ts +23 -0
- package/dist/cjs/case.js +46 -0
- package/dist/cjs/client.d.ts +89 -0
- package/dist/cjs/client.js +122 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +107 -0
- package/dist/cjs/generated/schema.d.ts +13436 -0
- package/dist/cjs/generated/schema.js +6 -0
- package/dist/cjs/http.d.ts +92 -0
- package/dist/cjs/http.js +238 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +28 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +31 -0
- package/dist/cjs/pagination.js +52 -0
- package/dist/cjs/resources.d.ts +7879 -0
- package/dist/cjs/resources.js +456 -0
- package/dist/cjs/runtime.d.ts +20 -0
- package/dist/cjs/runtime.js +74 -0
- package/dist/cjs/types.d.ts +525 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/units.d.ts +26 -0
- package/dist/cjs/units.js +45 -0
- package/dist/cjs/webhooks.d.ts +44 -0
- package/dist/cjs/webhooks.js +149 -0
- package/dist/esm/case.d.ts +23 -0
- package/dist/esm/case.js +39 -0
- package/dist/esm/client.d.ts +89 -0
- package/dist/esm/client.js +118 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +93 -0
- package/dist/esm/generated/schema.d.ts +13436 -0
- package/dist/esm/generated/schema.js +5 -0
- package/dist/esm/http.d.ts +92 -0
- package/dist/esm/http.js +232 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/pagination.d.ts +31 -0
- package/dist/esm/pagination.js +49 -0
- package/dist/esm/resources.d.ts +7879 -0
- package/dist/esm/resources.js +453 -0
- package/dist/esm/runtime.d.ts +20 -0
- package/dist/esm/runtime.js +46 -0
- package/dist/esm/types.d.ts +525 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/units.d.ts +26 -0
- package/dist/esm/units.js +38 -0
- package/dist/esm/webhooks.d.ts +44 -0
- package/dist/esm/webhooks.js +145 -0
- package/package.json +51 -5
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readWebhookRequest = readWebhookRequest;
|
|
4
|
+
exports.verifyWebhook = verifyWebhook;
|
|
5
|
+
const case_js_1 = require("./case.js");
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
const runtime_js_1 = require("./runtime.js");
|
|
8
|
+
function header(headers, name) {
|
|
9
|
+
if (typeof headers.get === "function") {
|
|
10
|
+
return headers.get(name) ?? undefined;
|
|
11
|
+
}
|
|
12
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
13
|
+
if (k.toLowerCase() === name)
|
|
14
|
+
return Array.isArray(v) ? v.join(" ") : v;
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
function b64decode(s) {
|
|
19
|
+
const bin = atob(s);
|
|
20
|
+
const out = new Uint8Array(bin.length);
|
|
21
|
+
for (let i = 0; i < bin.length; i++)
|
|
22
|
+
out[i] = bin.charCodeAt(i);
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
const RAW_BODY_HELP = "Webhook signatures are computed over the exact bytes Timbereye sent, so verify needs the raw body. " +
|
|
26
|
+
"In Express, give the webhook route the raw parser instead of express.json(): " +
|
|
27
|
+
'app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), handler). ' +
|
|
28
|
+
"Or call verify(rawBody, headers, secret) with the body as received.";
|
|
29
|
+
function isBytes(value) {
|
|
30
|
+
return value instanceof Uint8Array || value instanceof ArrayBuffer;
|
|
31
|
+
}
|
|
32
|
+
function isFetchRequest(req) {
|
|
33
|
+
return (typeof req.arrayBuffer === "function" &&
|
|
34
|
+
typeof req.headers.get === "function");
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The raw body and headers of a webhook request, or a {@link WebhookSignatureError} (`raw_body_required`)
|
|
38
|
+
* that says how to get the raw body when the request's body was already parsed or consumed.
|
|
39
|
+
*/
|
|
40
|
+
async function readWebhookRequest(req) {
|
|
41
|
+
if (req === null || typeof req !== "object" || req.headers === undefined) {
|
|
42
|
+
throw new errors_js_1.WebhookSignatureError("invalid_request", "verify(req) needs a Fetch Request or a Node request with headers.");
|
|
43
|
+
}
|
|
44
|
+
if (isFetchRequest(req)) {
|
|
45
|
+
if (req.bodyUsed === true) {
|
|
46
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `The request's body was already read. ${RAW_BODY_HELP}`);
|
|
47
|
+
}
|
|
48
|
+
return { body: new Uint8Array(await req.arrayBuffer()), headers: req.headers };
|
|
49
|
+
}
|
|
50
|
+
const node = req;
|
|
51
|
+
const body = node.body;
|
|
52
|
+
if (typeof body === "string" || isBytes(body)) {
|
|
53
|
+
return { body: body instanceof ArrayBuffer ? new Uint8Array(body) : body, headers: node.headers };
|
|
54
|
+
}
|
|
55
|
+
if (body !== undefined && body !== null && typeof body === "object" && Object.keys(body).length === 0) {
|
|
56
|
+
// express.raw and express.json leave {} when the content type did not match them.
|
|
57
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `req.body is an empty object: no raw parser read this request (check its type option). ${RAW_BODY_HELP}`);
|
|
58
|
+
}
|
|
59
|
+
if (body !== undefined && body !== null) {
|
|
60
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `The request's body was already parsed (req.body is ${Array.isArray(body) ? "an array" : typeof body}). ${RAW_BODY_HELP}`);
|
|
61
|
+
}
|
|
62
|
+
if (typeof node.on === "function" && node.readableEnded !== true) {
|
|
63
|
+
const bytes = await new Promise((resolve, reject) => {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
node.on("data", (chunk) => chunks.push(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk));
|
|
66
|
+
node.on("end", () => {
|
|
67
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
68
|
+
let offset = 0;
|
|
69
|
+
for (const c of chunks) {
|
|
70
|
+
out.set(c, offset);
|
|
71
|
+
offset += c.length;
|
|
72
|
+
}
|
|
73
|
+
resolve(out);
|
|
74
|
+
});
|
|
75
|
+
node.on("error", reject);
|
|
76
|
+
});
|
|
77
|
+
return { body: bytes, headers: node.headers };
|
|
78
|
+
}
|
|
79
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `The request has no body to verify. ${RAW_BODY_HELP}`);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Verify a Standard Webhooks delivery and return the event. Pass the raw body exactly as received
|
|
83
|
+
* (string, Uint8Array, a Node buffer or ArrayBuffer), never a re-serialised parse.
|
|
84
|
+
*
|
|
85
|
+
* It is async because Web Crypto is: `await te.webhooks.verify(...)`.
|
|
86
|
+
*/
|
|
87
|
+
async function verifyWebhook(rawBody, headers, secret, options = {}) {
|
|
88
|
+
const id = header(headers, "webhook-id");
|
|
89
|
+
const timestamp = header(headers, "webhook-timestamp");
|
|
90
|
+
const signature = header(headers, "webhook-signature");
|
|
91
|
+
if (!id || !timestamp || !signature) {
|
|
92
|
+
throw new errors_js_1.WebhookSignatureError("missing_headers", "Missing webhook-id, webhook-timestamp or webhook-signature header");
|
|
93
|
+
}
|
|
94
|
+
if (!/^\d+$/.test(timestamp))
|
|
95
|
+
throw new errors_js_1.WebhookSignatureError("invalid_timestamp", "webhook-timestamp is not an integer");
|
|
96
|
+
const tolerance = options.toleranceSeconds ?? 300;
|
|
97
|
+
const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000);
|
|
98
|
+
if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) {
|
|
99
|
+
throw new errors_js_1.WebhookSignatureError("timestamp_out_of_tolerance", "webhook-timestamp is outside the tolerance window");
|
|
100
|
+
}
|
|
101
|
+
const bodyBytes = typeof rawBody === "string"
|
|
102
|
+
? new TextEncoder().encode(rawBody)
|
|
103
|
+
: rawBody instanceof Uint8Array
|
|
104
|
+
? rawBody
|
|
105
|
+
: new Uint8Array(rawBody);
|
|
106
|
+
const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
|
|
107
|
+
const signed = new Uint8Array(prefix.length + bodyBytes.length);
|
|
108
|
+
signed.set(prefix);
|
|
109
|
+
signed.set(bodyBytes, prefix.length);
|
|
110
|
+
// Candidate signatures: "v1,<base64>" entries separated by spaces; other versions are ignored.
|
|
111
|
+
const candidates = [];
|
|
112
|
+
for (const part of signature.split(" ")) {
|
|
113
|
+
const [version, value] = part.split(",", 2);
|
|
114
|
+
if (version !== "v1" || !value)
|
|
115
|
+
continue;
|
|
116
|
+
try {
|
|
117
|
+
candidates.push(b64decode(value));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// malformed base64: cannot match
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const crypto = await (0, runtime_js_1.getWebCrypto)();
|
|
124
|
+
const secrets = Array.isArray(secret) ? secret : [secret];
|
|
125
|
+
let valid = false;
|
|
126
|
+
for (const s of secrets) {
|
|
127
|
+
let keyBytes;
|
|
128
|
+
try {
|
|
129
|
+
keyBytes = b64decode(s.startsWith("whsec_") ? s.slice(6) : s);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
throw new errors_js_1.WebhookSignatureError("invalid_secret", "Webhook secret is not whsec_<base64>");
|
|
133
|
+
}
|
|
134
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
135
|
+
for (const sig of candidates) {
|
|
136
|
+
// subtle.verify compares in constant time.
|
|
137
|
+
if (await crypto.subtle.verify("HMAC", key, sig, signed))
|
|
138
|
+
valid = true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (!valid)
|
|
142
|
+
throw new errors_js_1.WebhookSignatureError("signature_mismatch", "No matching signature found for the payload");
|
|
143
|
+
try {
|
|
144
|
+
return (0, case_js_1.toCamel)(JSON.parse(new TextDecoder().decode(bodyBytes)));
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw new errors_js_1.WebhookSignatureError("invalid_payload", "Webhook body is not valid JSON");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Case mapping between the API (snake_case JSON) and the SDK (camelCase).
|
|
3
|
+
*
|
|
4
|
+
* The mapping is purely mechanical: it is applied to object keys only, never to values, and the
|
|
5
|
+
* contents of free-form maps are left exactly as the caller or server wrote them. Opaque keys are
|
|
6
|
+
* listed once here; a test derives the same list from the OpenAPI document so they cannot drift.
|
|
7
|
+
*/
|
|
8
|
+
/** Property names (snake_case, as on the wire) whose value is a free-form map that must not be converted. */
|
|
9
|
+
export declare const OPAQUE_KEYS: readonly string[];
|
|
10
|
+
export declare function snakeToCamel(key: string): string;
|
|
11
|
+
export declare function camelToSnake(key: string): string;
|
|
12
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
13
|
+
export declare function toSnake<T = unknown>(value: unknown): T;
|
|
14
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
15
|
+
export declare function toCamel<T = unknown>(value: unknown): T;
|
|
16
|
+
/** Type-level twin of `snakeToCamel`. */
|
|
17
|
+
export type CamelKey<S extends string> = S extends `${infer H}_${infer R}` ? `${H}${Capitalize<CamelKey<R>>}` : S;
|
|
18
|
+
type OpaqueKey = "headers" | "metadata" | "rejection_gates";
|
|
19
|
+
/** Type-level twin of `toCamel`: every object key camelCased except the contents of opaque maps. */
|
|
20
|
+
export type Camel<T> = T extends readonly (infer U)[] ? Camel<U>[] : T extends object ? {
|
|
21
|
+
[K in keyof T as K extends string ? CamelKey<K> : K]: K extends OpaqueKey ? T[K] : Camel<T[K]>;
|
|
22
|
+
} : T;
|
|
23
|
+
export {};
|
package/dist/esm/case.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Case mapping between the API (snake_case JSON) and the SDK (camelCase).
|
|
3
|
+
*
|
|
4
|
+
* The mapping is purely mechanical: it is applied to object keys only, never to values, and the
|
|
5
|
+
* contents of free-form maps are left exactly as the caller or server wrote them. Opaque keys are
|
|
6
|
+
* listed once here; a test derives the same list from the OpenAPI document so they cannot drift.
|
|
7
|
+
*/
|
|
8
|
+
/** Property names (snake_case, as on the wire) whose value is a free-form map that must not be converted. */
|
|
9
|
+
export const OPAQUE_KEYS = ["details", "headers", "metadata", "rejection_gates"];
|
|
10
|
+
const OPAQUE_SNAKE = new Set(OPAQUE_KEYS);
|
|
11
|
+
const OPAQUE_CAMEL = new Set(OPAQUE_KEYS.map(snakeToCamel));
|
|
12
|
+
export function snakeToCamel(key) {
|
|
13
|
+
return key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
14
|
+
}
|
|
15
|
+
export function camelToSnake(key) {
|
|
16
|
+
return key.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
17
|
+
}
|
|
18
|
+
function isPlainObject(v) {
|
|
19
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
20
|
+
}
|
|
21
|
+
function convert(value, mapKey, opaque) {
|
|
22
|
+
if (Array.isArray(value))
|
|
23
|
+
return value.map((v) => convert(v, mapKey, opaque));
|
|
24
|
+
if (!isPlainObject(value))
|
|
25
|
+
return value;
|
|
26
|
+
const out = {};
|
|
27
|
+
for (const [k, v] of Object.entries(value)) {
|
|
28
|
+
out[mapKey(k)] = opaque.has(k) ? v : convert(v, mapKey, opaque);
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
33
|
+
export function toSnake(value) {
|
|
34
|
+
return convert(value, camelToSnake, OPAQUE_CAMEL);
|
|
35
|
+
}
|
|
36
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
37
|
+
export function toCamel(value) {
|
|
38
|
+
return convert(value, snakeToCamel, OPAQUE_SNAKE);
|
|
39
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type ClientOptions } from "./http.js";
|
|
2
|
+
import { createResources } from "./resources.js";
|
|
3
|
+
import { type HeadersInput, type VerifyOptions, type WebhookRequest } from "./webhooks.js";
|
|
4
|
+
import type { WebhookEvent } from "./types.js";
|
|
5
|
+
/** The client's options: the transport's, plus the webhook signing secret. */
|
|
6
|
+
export interface TimbereyeOptions extends ClientOptions {
|
|
7
|
+
/** The API key; default `TIMBEREYE_SECRET_KEY` from the environment. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The webhook endpoint's signing secret (`whsec_…`) that `webhooks.verify(req)` uses; default
|
|
11
|
+
* `TIMBEREYE_WEBHOOK_SECRET` from the environment, read when `verify` is called.
|
|
12
|
+
*/
|
|
13
|
+
webhookSecret?: string | string[];
|
|
14
|
+
}
|
|
15
|
+
/** The webhook helpers on a client. */
|
|
16
|
+
export interface WebhookHelpers {
|
|
17
|
+
/**
|
|
18
|
+
* Verifies a delivery from the request it arrived on, with the client's webhook secret
|
|
19
|
+
* (`webhookSecret`, else `TIMBEREYE_WEBHOOK_SECRET`). The request must still carry the raw body: a
|
|
20
|
+
* Fetch `Request`, or a Node request behind `express.raw({ type: "application/json" })` (or one no
|
|
21
|
+
* middleware has read). A body that was already parsed is refused with `raw_body_required`.
|
|
22
|
+
*/
|
|
23
|
+
verify(req: WebhookRequest, options?: VerifyOptions): Promise<WebhookEvent>;
|
|
24
|
+
/** Verifies a delivery from its raw body, headers and the secret (or secrets, while rolling one). */
|
|
25
|
+
verify(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersInput, secret: string | string[], options?: VerifyOptions): Promise<WebhookEvent>;
|
|
26
|
+
/**
|
|
27
|
+
* A route handler that verifies each delivery, calls `onEvent` with the event, and answers `200`. A
|
|
28
|
+
* request Timbereye did not sign (bad or missing signature, stale timestamp, not JSON) is answered `400`
|
|
29
|
+
* and `onEvent` is not called. A mistake in your setup (no secret, a body already parsed) and an error
|
|
30
|
+
* thrown by `onEvent` are not hidden: they go to `next` in Express (or are thrown), so Timbereye retries
|
|
31
|
+
* the delivery once you fix it.
|
|
32
|
+
*
|
|
33
|
+
* Express: `app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), te.webhooks.handler(fn))`.
|
|
34
|
+
* Fetch (Next.js, Hono, Workers): `export const POST = te.webhooks.handler(fn)`.
|
|
35
|
+
*/
|
|
36
|
+
handler(onEvent: (event: WebhookEvent) => unknown, options?: VerifyOptions): WebhookRouteHandler;
|
|
37
|
+
}
|
|
38
|
+
/** What `webhooks.handler` returns: a Fetch handler, or a Node/Express one. */
|
|
39
|
+
export interface WebhookRouteHandler {
|
|
40
|
+
(req: Request): Promise<Response>;
|
|
41
|
+
(req: WebhookRequest, res: WebhookResponse, next?: (error?: unknown) => void): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/** The part of a Node `ServerResponse` the handler uses. */
|
|
44
|
+
export interface WebhookResponse {
|
|
45
|
+
statusCode: number;
|
|
46
|
+
headersSent?: boolean;
|
|
47
|
+
setHeader(name: string, value: string): unknown;
|
|
48
|
+
end(body?: string): unknown;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* ```ts
|
|
52
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
53
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
|
|
57
|
+
* key or secret wins over the environment.
|
|
58
|
+
*/
|
|
59
|
+
export declare class Timbereye {
|
|
60
|
+
/** Test mode only: a simulated scan and refinement, so the loop can run with no device and no model. */
|
|
61
|
+
readonly testMode: ReturnType<typeof createResources>["testMode"];
|
|
62
|
+
readonly groups: ReturnType<typeof createResources>["groups"];
|
|
63
|
+
readonly items: ReturnType<typeof createResources>["items"];
|
|
64
|
+
readonly scans: ReturnType<typeof createResources>["scans"];
|
|
65
|
+
readonly images: ReturnType<typeof createResources>["images"];
|
|
66
|
+
readonly places: ReturnType<typeof createResources>["places"];
|
|
67
|
+
/** Tag printing: label designs for the 62 mm QR tags. */
|
|
68
|
+
readonly labelTemplates: ReturnType<typeof createResources>["labelTemplates"];
|
|
69
|
+
/** Tag printing: batches of tags and their ZPL or PDF print files. */
|
|
70
|
+
readonly tagBatches: ReturnType<typeof createResources>["tagBatches"];
|
|
71
|
+
readonly species: ReturnType<typeof createResources>["species"];
|
|
72
|
+
readonly volumeRules: ReturnType<typeof createResources>["volumeRules"];
|
|
73
|
+
readonly events: ReturnType<typeof createResources>["events"];
|
|
74
|
+
readonly webhookEndpoints: ReturnType<typeof createResources>["webhookEndpoints"];
|
|
75
|
+
readonly captureTokens: ReturnType<typeof createResources>["captureTokens"];
|
|
76
|
+
/** Key management: dashboard sessions only (an API key is refused with 403 `session_required`). */
|
|
77
|
+
readonly apiKeys: ReturnType<typeof createResources>["apiKeys"];
|
|
78
|
+
readonly team: ReturnType<typeof createResources>["team"];
|
|
79
|
+
readonly auditLog: ReturnType<typeof createResources>["auditLog"];
|
|
80
|
+
readonly usage: ReturnType<typeof createResources>["usage"];
|
|
81
|
+
/** The organisation's billing (dashboard sessions only). */
|
|
82
|
+
readonly billing: ReturnType<typeof createResources>["billing"];
|
|
83
|
+
readonly models: ReturnType<typeof createResources>["models"];
|
|
84
|
+
readonly account: ReturnType<typeof createResources>["account"];
|
|
85
|
+
/** The developer console's bootstrap and onboarding: dashboard sessions only. */
|
|
86
|
+
readonly console: ReturnType<typeof createResources>["console"];
|
|
87
|
+
readonly webhooks: WebhookHelpers;
|
|
88
|
+
constructor(apiKeyOrOptions?: string | TimbereyeOptions, options?: TimbereyeOptions);
|
|
89
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { TimbereyeError, WebhookSignatureError } from "./errors.js";
|
|
2
|
+
import { Transport } from "./http.js";
|
|
3
|
+
import { createResources } from "./resources.js";
|
|
4
|
+
import { readEnv } from "./runtime.js";
|
|
5
|
+
import { readWebhookRequest, verifyWebhook, } from "./webhooks.js";
|
|
6
|
+
/** Verification failures that mean "not from Timbereye": answered 400. Everything else is a setup mistake. */
|
|
7
|
+
const FORGED_CODES = new Set([
|
|
8
|
+
"missing_headers",
|
|
9
|
+
"invalid_timestamp",
|
|
10
|
+
"timestamp_out_of_tolerance",
|
|
11
|
+
"signature_mismatch",
|
|
12
|
+
"invalid_payload",
|
|
13
|
+
]);
|
|
14
|
+
/**
|
|
15
|
+
* ```ts
|
|
16
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
17
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, ... })` also work; an explicit
|
|
21
|
+
* key or secret wins over the environment.
|
|
22
|
+
*/
|
|
23
|
+
export class Timbereye {
|
|
24
|
+
constructor(apiKeyOrOptions, options = {}) {
|
|
25
|
+
const merged = typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null
|
|
26
|
+
? apiKeyOrOptions
|
|
27
|
+
: { ...options, apiKey: apiKeyOrOptions ?? options.apiKey };
|
|
28
|
+
const { apiKey: explicitKey, webhookSecret, ...transportOptions } = merged;
|
|
29
|
+
const apiKey = explicitKey ?? readEnv("TIMBEREYE_SECRET_KEY");
|
|
30
|
+
if (apiKey === undefined) {
|
|
31
|
+
throw new TimbereyeError({
|
|
32
|
+
message: "No Timbereye API key: set TIMBEREYE_SECRET_KEY in the environment, or pass the key: " +
|
|
33
|
+
'new Timbereye("te_test_sk_…").',
|
|
34
|
+
type: "client_error",
|
|
35
|
+
code: "api_key_missing",
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
this.webhooks = {
|
|
39
|
+
verify: ((first, ...rest) => {
|
|
40
|
+
if (typeof first === "string" ||
|
|
41
|
+
first instanceof Uint8Array ||
|
|
42
|
+
first instanceof ArrayBuffer) {
|
|
43
|
+
const [headers, secret, verifyOptions] = rest;
|
|
44
|
+
return verifyWebhook(first, headers, secret, verifyOptions);
|
|
45
|
+
}
|
|
46
|
+
return verifyRequest(first, webhookSecret, rest[0]);
|
|
47
|
+
}),
|
|
48
|
+
handler: (onEvent, verifyOptions) => webhookHandler(webhookSecret, onEvent, verifyOptions),
|
|
49
|
+
};
|
|
50
|
+
const r = createResources(new Transport(apiKey, transportOptions));
|
|
51
|
+
this.testMode = r.testMode;
|
|
52
|
+
this.groups = r.groups;
|
|
53
|
+
this.items = r.items;
|
|
54
|
+
this.scans = r.scans;
|
|
55
|
+
this.images = r.images;
|
|
56
|
+
this.places = r.places;
|
|
57
|
+
this.labelTemplates = r.labelTemplates;
|
|
58
|
+
this.tagBatches = r.tagBatches;
|
|
59
|
+
this.species = r.species;
|
|
60
|
+
this.volumeRules = r.volumeRules;
|
|
61
|
+
this.events = r.events;
|
|
62
|
+
this.webhookEndpoints = r.webhookEndpoints;
|
|
63
|
+
this.captureTokens = r.captureTokens;
|
|
64
|
+
this.apiKeys = r.apiKeys;
|
|
65
|
+
this.team = r.team;
|
|
66
|
+
this.auditLog = r.auditLog;
|
|
67
|
+
this.usage = r.usage;
|
|
68
|
+
this.billing = r.billing;
|
|
69
|
+
this.models = r.models;
|
|
70
|
+
this.account = r.account;
|
|
71
|
+
this.console = r.console;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function verifyRequest(req, configured, options) {
|
|
75
|
+
const secret = configured ?? readEnv("TIMBEREYE_WEBHOOK_SECRET");
|
|
76
|
+
if (secret === undefined || (Array.isArray(secret) && secret.length === 0)) {
|
|
77
|
+
throw new WebhookSignatureError("webhook_secret_missing", "No webhook secret: set TIMBEREYE_WEBHOOK_SECRET (the endpoint's whsec_… secret) in the environment, " +
|
|
78
|
+
"or pass it: new Timbereye({ webhookSecret }).");
|
|
79
|
+
}
|
|
80
|
+
const { body, headers } = await readWebhookRequest(req);
|
|
81
|
+
return verifyWebhook(body, headers, secret, options);
|
|
82
|
+
}
|
|
83
|
+
function webhookHandler(configured, onEvent, options) {
|
|
84
|
+
return (async (req, res, next) => {
|
|
85
|
+
const answer = (status, body) => {
|
|
86
|
+
if (res === undefined)
|
|
87
|
+
return new Response(body, { status, headers: { "content-type": "application/json" } });
|
|
88
|
+
if (res.headersSent !== true) {
|
|
89
|
+
res.statusCode = status;
|
|
90
|
+
res.setHeader("content-type", "application/json");
|
|
91
|
+
res.end(body);
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
};
|
|
95
|
+
try {
|
|
96
|
+
let event;
|
|
97
|
+
try {
|
|
98
|
+
event = await verifyRequest(req, configured, options);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error instanceof WebhookSignatureError &&
|
|
102
|
+
error.code !== null &&
|
|
103
|
+
FORGED_CODES.has(error.code))
|
|
104
|
+
return answer(400, JSON.stringify({ error: { code: error.code, message: error.message } }));
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
await onEvent(event);
|
|
108
|
+
return answer(200, "{}");
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (res === undefined)
|
|
112
|
+
throw error;
|
|
113
|
+
if (next !== undefined)
|
|
114
|
+
return next(error);
|
|
115
|
+
answer(500, JSON.stringify({ error: { code: "handler_error" } }));
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type ErrorType = "invalid_request_error" | "authentication_error" | "permission_error" | "rate_limit_error" | "api_error";
|
|
2
|
+
export interface ErrorInit {
|
|
3
|
+
message: string;
|
|
4
|
+
type?: string;
|
|
5
|
+
code?: string | null;
|
|
6
|
+
param?: string | null;
|
|
7
|
+
requestId?: string | null;
|
|
8
|
+
status?: number;
|
|
9
|
+
docUrl?: string | null;
|
|
10
|
+
existingId?: string | null;
|
|
11
|
+
}
|
|
12
|
+
/** Base class of everything the SDK throws on purpose. */
|
|
13
|
+
export declare class TimbereyeError extends Error {
|
|
14
|
+
/** The API's error `type`, or a client-side marker for errors raised in the SDK. */
|
|
15
|
+
readonly type: string;
|
|
16
|
+
/** Stable machine-readable code. Unknown codes may appear within v1: treat them as the generic case. */
|
|
17
|
+
readonly code: string | null;
|
|
18
|
+
/** The request field at fault, with dots for nesting (`defaults.length_m`). Wire names, not camelCase. */
|
|
19
|
+
readonly param: string | null;
|
|
20
|
+
/** The `Request-Id` of the failed request. Quote it to support. */
|
|
21
|
+
readonly requestId: string | null;
|
|
22
|
+
/** HTTP status, or undefined when no response was received. */
|
|
23
|
+
readonly status: number | undefined;
|
|
24
|
+
readonly docUrl: string | null;
|
|
25
|
+
/** For `external_ref_in_use`: the open group that already has the reference (`grp_…`). */
|
|
26
|
+
readonly existingId: string | null;
|
|
27
|
+
constructor(init: ErrorInit);
|
|
28
|
+
}
|
|
29
|
+
/** 400, 404, 409, 412, 413, 422. */
|
|
30
|
+
export declare class InvalidRequestError extends TimbereyeError {
|
|
31
|
+
}
|
|
32
|
+
/** 401. */
|
|
33
|
+
export declare class AuthenticationError extends TimbereyeError {
|
|
34
|
+
}
|
|
35
|
+
/** 403. */
|
|
36
|
+
export declare class PermissionError extends TimbereyeError {
|
|
37
|
+
}
|
|
38
|
+
/** 429. `retryAfterSeconds` is the server's `Retry-After`, when sent. */
|
|
39
|
+
export declare class RateLimitError extends TimbereyeError {
|
|
40
|
+
retryAfterSeconds: number | null;
|
|
41
|
+
}
|
|
42
|
+
/** 5xx. */
|
|
43
|
+
export declare class ApiError extends TimbereyeError {
|
|
44
|
+
}
|
|
45
|
+
/** No usable response: DNS, connection reset, TLS, or the body could not be read. */
|
|
46
|
+
export declare class ConnectionError extends TimbereyeError {
|
|
47
|
+
readonly cause: unknown;
|
|
48
|
+
constructor(message: string, cause?: unknown, type?: string);
|
|
49
|
+
}
|
|
50
|
+
/** The per-attempt `timeoutMs` elapsed. */
|
|
51
|
+
export declare class TimeoutError extends ConnectionError {
|
|
52
|
+
constructor(timeoutMs: number);
|
|
53
|
+
}
|
|
54
|
+
/** The caller's `AbortSignal` fired. Never retried. */
|
|
55
|
+
export declare class AbortError extends TimbereyeError {
|
|
56
|
+
constructor();
|
|
57
|
+
}
|
|
58
|
+
/** A webhook failed verification. `code` says why. */
|
|
59
|
+
export declare class WebhookSignatureError extends TimbereyeError {
|
|
60
|
+
constructor(code: string, message: string);
|
|
61
|
+
}
|
|
62
|
+
/** Build the error for a non-2xx response. `body` is the parsed JSON, if the body was JSON. */
|
|
63
|
+
export declare function errorFromResponse(status: number, body: unknown, requestIdHeader: string | null): TimbereyeError;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** Base class of everything the SDK throws on purpose. */
|
|
2
|
+
export class TimbereyeError extends Error {
|
|
3
|
+
constructor(init) {
|
|
4
|
+
super(init.message);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
this.type = init.type ?? "client_error";
|
|
7
|
+
this.code = init.code ?? null;
|
|
8
|
+
this.param = init.param ?? null;
|
|
9
|
+
this.requestId = init.requestId ?? null;
|
|
10
|
+
this.status = init.status;
|
|
11
|
+
this.docUrl = init.docUrl ?? null;
|
|
12
|
+
this.existingId = init.existingId ?? null;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** 400, 404, 409, 412, 413, 422. */
|
|
16
|
+
export class InvalidRequestError extends TimbereyeError {
|
|
17
|
+
}
|
|
18
|
+
/** 401. */
|
|
19
|
+
export class AuthenticationError extends TimbereyeError {
|
|
20
|
+
}
|
|
21
|
+
/** 403. */
|
|
22
|
+
export class PermissionError extends TimbereyeError {
|
|
23
|
+
}
|
|
24
|
+
/** 429. `retryAfterSeconds` is the server's `Retry-After`, when sent. */
|
|
25
|
+
export class RateLimitError extends TimbereyeError {
|
|
26
|
+
constructor() {
|
|
27
|
+
super(...arguments);
|
|
28
|
+
this.retryAfterSeconds = null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** 5xx. */
|
|
32
|
+
export class ApiError extends TimbereyeError {
|
|
33
|
+
}
|
|
34
|
+
/** No usable response: DNS, connection reset, TLS, or the body could not be read. */
|
|
35
|
+
export class ConnectionError extends TimbereyeError {
|
|
36
|
+
constructor(message, cause, type = "connection_error") {
|
|
37
|
+
super({ message, type });
|
|
38
|
+
this.cause = cause;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The per-attempt `timeoutMs` elapsed. */
|
|
42
|
+
export class TimeoutError extends ConnectionError {
|
|
43
|
+
constructor(timeoutMs) {
|
|
44
|
+
super(`Request timed out after ${timeoutMs} ms`, undefined, "timeout_error");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** The caller's `AbortSignal` fired. Never retried. */
|
|
48
|
+
export class AbortError extends TimbereyeError {
|
|
49
|
+
constructor() {
|
|
50
|
+
super({ message: "Request aborted", type: "abort_error" });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** A webhook failed verification. `code` says why. */
|
|
54
|
+
export class WebhookSignatureError extends TimbereyeError {
|
|
55
|
+
constructor(code, message) {
|
|
56
|
+
super({ message, type: "webhook_signature_error", code });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const BY_TYPE = {
|
|
60
|
+
invalid_request_error: InvalidRequestError,
|
|
61
|
+
authentication_error: AuthenticationError,
|
|
62
|
+
permission_error: PermissionError,
|
|
63
|
+
rate_limit_error: RateLimitError,
|
|
64
|
+
api_error: ApiError,
|
|
65
|
+
};
|
|
66
|
+
function typeFromStatus(status) {
|
|
67
|
+
if (status === 401)
|
|
68
|
+
return "authentication_error";
|
|
69
|
+
if (status === 403)
|
|
70
|
+
return "permission_error";
|
|
71
|
+
if (status === 429)
|
|
72
|
+
return "rate_limit_error";
|
|
73
|
+
if (status >= 500)
|
|
74
|
+
return "api_error";
|
|
75
|
+
return "invalid_request_error";
|
|
76
|
+
}
|
|
77
|
+
/** Build the error for a non-2xx response. `body` is the parsed JSON, if the body was JSON. */
|
|
78
|
+
export function errorFromResponse(status, body, requestIdHeader) {
|
|
79
|
+
const e = body?.error;
|
|
80
|
+
const err = e && typeof e === "object" ? e : {};
|
|
81
|
+
const type = typeof err.type === "string" && err.type in BY_TYPE ? err.type : typeFromStatus(status);
|
|
82
|
+
const Cls = BY_TYPE[type] ?? TimbereyeError;
|
|
83
|
+
return new Cls({
|
|
84
|
+
message: typeof err.message === "string" ? err.message : `Request failed with status ${status}`,
|
|
85
|
+
type,
|
|
86
|
+
code: typeof err.code === "string" ? err.code : null,
|
|
87
|
+
param: typeof err.param === "string" ? err.param : null,
|
|
88
|
+
requestId: typeof err.request_id === "string" ? err.request_id : requestIdHeader,
|
|
89
|
+
docUrl: typeof err.doc_url === "string" ? err.doc_url : null,
|
|
90
|
+
existingId: typeof err.existing_id === "string" ? err.existing_id : null,
|
|
91
|
+
status,
|
|
92
|
+
});
|
|
93
|
+
}
|