@timbereye/sdk 0.0.0-stage → 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/CHANGELOG.md +123 -0
- package/LICENSE +202 -0
- package/README.md +346 -2
- package/dist/cjs/case.d.ts +23 -0
- package/dist/cjs/case.js +54 -0
- package/dist/cjs/client.d.ts +98 -0
- package/dist/cjs/client.js +132 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +107 -0
- package/dist/cjs/generated/schema.d.ts +14862 -0
- package/dist/cjs/generated/schema.js +6 -0
- package/dist/cjs/http.d.ts +104 -0
- package/dist/cjs/http.js +253 -0
- package/dist/cjs/index.d.ts +14 -0
- package/dist/cjs/index.js +29 -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 +11195 -0
- package/dist/cjs/resources.js +506 -0
- package/dist/cjs/runtime.d.ts +20 -0
- package/dist/cjs/runtime.js +74 -0
- package/dist/cjs/types.d.ts +649 -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 +67 -0
- package/dist/cjs/webhooks.js +213 -0
- package/dist/esm/case.d.ts +23 -0
- package/dist/esm/case.js +47 -0
- package/dist/esm/client.d.ts +98 -0
- package/dist/esm/client.js +128 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +93 -0
- package/dist/esm/generated/schema.d.ts +14862 -0
- package/dist/esm/generated/schema.js +5 -0
- package/dist/esm/http.d.ts +104 -0
- package/dist/esm/http.js +247 -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 +11195 -0
- package/dist/esm/resources.js +503 -0
- package/dist/esm/runtime.d.ts +20 -0
- package/dist/esm/runtime.js +46 -0
- package/dist/esm/types.d.ts +649 -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 +67 -0
- package/dist/esm/webhooks.js +208 -0
- package/package.json +51 -5
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.M3_PER_CUBIC_FOOT = exports.KG_PER_SHORT_TON = exports.KG_PER_POUND = exports.M_PER_INCH = exports.M_PER_FOOT = void 0;
|
|
4
|
+
exports.formatLength = formatLength;
|
|
5
|
+
exports.formatDiameter = formatDiameter;
|
|
6
|
+
exports.formatWeight = formatWeight;
|
|
7
|
+
exports.formatVolume = formatVolume;
|
|
8
|
+
function resolve(u) {
|
|
9
|
+
return typeof u === "string" ? u : u.displayUnits;
|
|
10
|
+
}
|
|
11
|
+
exports.M_PER_FOOT = 0.3048;
|
|
12
|
+
exports.M_PER_INCH = 0.0254;
|
|
13
|
+
exports.KG_PER_POUND = 0.45359237;
|
|
14
|
+
exports.KG_PER_SHORT_TON = 907.18474;
|
|
15
|
+
exports.M3_PER_CUBIC_FOOT = 0.028316846592;
|
|
16
|
+
function fmt(n, digits) {
|
|
17
|
+
return String(Number(n.toFixed(digits)));
|
|
18
|
+
}
|
|
19
|
+
/** Lengths: metres, or feet. */
|
|
20
|
+
function formatLength(valueM, source, digits = 2) {
|
|
21
|
+
const units = resolve(source);
|
|
22
|
+
return units === "imperial" ? `${fmt(valueM / exports.M_PER_FOOT, digits)} ft` : `${fmt(valueM, digits)} m`;
|
|
23
|
+
}
|
|
24
|
+
/** Diameters: centimetres, or inches. */
|
|
25
|
+
function formatDiameter(valueM, source, digits = 1) {
|
|
26
|
+
const units = resolve(source);
|
|
27
|
+
return units === "imperial" ? `${fmt(valueM / exports.M_PER_INCH, digits)} in` : `${fmt(valueM * 100, digits)} cm`;
|
|
28
|
+
}
|
|
29
|
+
/** Weights: kilograms below one tonne and tonnes above; pounds below one short ton and short tons above. */
|
|
30
|
+
function formatWeight(valueKg, source, digits = 2) {
|
|
31
|
+
const units = resolve(source);
|
|
32
|
+
if (units === "imperial") {
|
|
33
|
+
return Math.abs(valueKg) >= exports.KG_PER_SHORT_TON
|
|
34
|
+
? `${fmt(valueKg / exports.KG_PER_SHORT_TON, digits)} short tons`
|
|
35
|
+
: `${fmt(valueKg / exports.KG_PER_POUND, digits)} lb`;
|
|
36
|
+
}
|
|
37
|
+
return Math.abs(valueKg) >= 1000 ? `${fmt(valueKg / 1000, digits)} t` : `${fmt(valueKg, digits)} kg`;
|
|
38
|
+
}
|
|
39
|
+
/** Volumes: cubic metres, or cubic feet. Board-foot rule outputs are shown from `volume.native`, not converted. */
|
|
40
|
+
function formatVolume(valueM3, source, digits = 3) {
|
|
41
|
+
const units = resolve(source);
|
|
42
|
+
return units === "imperial"
|
|
43
|
+
? `${fmt(valueM3 / exports.M3_PER_CUBIC_FOOT, digits)} ft³`
|
|
44
|
+
: `${fmt(valueM3, digits)} m³`;
|
|
45
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { WebhookEvent } from "./types.js";
|
|
2
|
+
export type HeadersInput = {
|
|
3
|
+
get(name: string): string | null;
|
|
4
|
+
} | Record<string, string | string[] | undefined>;
|
|
5
|
+
export interface VerifyOptions {
|
|
6
|
+
/** Maximum age (and clock skew) of `webhook-timestamp` in seconds. Default 300. */
|
|
7
|
+
toleranceSeconds?: number;
|
|
8
|
+
/** Advanced (used by tests): the clock, in milliseconds. */
|
|
9
|
+
now?: () => number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A request a webhook arrived on, for `te.webhooks.verify(req)`:
|
|
13
|
+
*
|
|
14
|
+
* - a Fetch `Request` (Next.js route handlers, Hono, Cloudflare Workers, Deno, Bun): its body is read here;
|
|
15
|
+
* - a Node `IncomingMessage` (Express, Fastify, plain `http`) whose `body` is the raw bytes, as
|
|
16
|
+
* `express.raw({ type: "application/json" })` leaves it, or whose body has not been read by anything yet.
|
|
17
|
+
*/
|
|
18
|
+
export type WebhookRequest = {
|
|
19
|
+
headers: {
|
|
20
|
+
get(name: string): string | null;
|
|
21
|
+
};
|
|
22
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
23
|
+
bodyUsed?: boolean;
|
|
24
|
+
} | {
|
|
25
|
+
headers: Record<string, string | string[] | undefined>;
|
|
26
|
+
body?: unknown;
|
|
27
|
+
readableEnded?: boolean;
|
|
28
|
+
on?: (event: string, listener: (...args: any[]) => void) => unknown;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The raw body and headers of a webhook request, or a {@link WebhookSignatureError} (`raw_body_required`)
|
|
32
|
+
* that says how to get the raw body when the request's body was already parsed or consumed.
|
|
33
|
+
*/
|
|
34
|
+
export declare function readWebhookRequest(req: WebhookRequest): Promise<{
|
|
35
|
+
body: Uint8Array | string;
|
|
36
|
+
headers: HeadersInput;
|
|
37
|
+
}>;
|
|
38
|
+
/**
|
|
39
|
+
* Verify a Standard Webhooks delivery and return the event. Pass the raw body exactly as received
|
|
40
|
+
* (string, Uint8Array, a Node buffer or ArrayBuffer), never a re-serialised parse.
|
|
41
|
+
*
|
|
42
|
+
* It is async because Web Crypto is: `await te.webhooks.verify(...)`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function verifyWebhook(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersInput, secret: string | string[], options?: VerifyOptions): Promise<WebhookEvent>;
|
|
45
|
+
/** What {@link generateTestWebhookHeaders} signs. */
|
|
46
|
+
export interface TestWebhookParams {
|
|
47
|
+
/** The raw body to sign, exactly as your handler will receive it (a string or bytes, not an object). */
|
|
48
|
+
payload: string | Uint8Array | ArrayBuffer;
|
|
49
|
+
/** The `whsec_…` secret your handler verifies with. */
|
|
50
|
+
secret: string;
|
|
51
|
+
/** `webhook-id`. Default: the payload's `id` when it is an event (as in a real delivery), else `msg_` and random hex. */
|
|
52
|
+
id?: string;
|
|
53
|
+
/** `webhook-timestamp`, in Unix seconds. Default: now. Pass an old one to test your handler's tolerance. */
|
|
54
|
+
timestamp?: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The headers Timbereye would send with `payload`, signed with `secret` (Standard Webhooks: `webhook-id`,
|
|
58
|
+
* `webhook-timestamp`, `webhook-signature`), for testing your webhook handler without the network. `verifyWebhook`
|
|
59
|
+
* accepts them. Never use it to accept a request: it signs, it does not check.
|
|
60
|
+
*
|
|
61
|
+
* ```ts
|
|
62
|
+
* const body = JSON.stringify(event)
|
|
63
|
+
* const headers = await generateTestWebhookHeaders({ payload: body, secret: "whsec_…" })
|
|
64
|
+
* await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }))
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function generateTestWebhookHeaders(params: TestWebhookParams): Promise<Record<string, string>>;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readWebhookRequest = readWebhookRequest;
|
|
4
|
+
exports.verifyWebhook = verifyWebhook;
|
|
5
|
+
exports.generateTestWebhookHeaders = generateTestWebhookHeaders;
|
|
6
|
+
const case_js_1 = require("./case.js");
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const runtime_js_1 = require("./runtime.js");
|
|
9
|
+
function header(headers, name) {
|
|
10
|
+
if (typeof headers.get === "function") {
|
|
11
|
+
return headers.get(name) ?? undefined;
|
|
12
|
+
}
|
|
13
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
14
|
+
if (k.toLowerCase() === name)
|
|
15
|
+
return Array.isArray(v) ? v.join(" ") : v;
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
function b64decode(s) {
|
|
20
|
+
const bin = atob(s);
|
|
21
|
+
const out = new Uint8Array(bin.length);
|
|
22
|
+
for (let i = 0; i < bin.length; i++)
|
|
23
|
+
out[i] = bin.charCodeAt(i);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
const RAW_BODY_HELP = "Webhook signatures are computed over the exact bytes Timbereye sent, so verify needs the raw body. " +
|
|
27
|
+
"In Express, give the webhook route the raw parser instead of express.json(): " +
|
|
28
|
+
'app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), handler). ' +
|
|
29
|
+
"Or call verify(rawBody, headers, secret) with the body as received.";
|
|
30
|
+
function isBytes(value) {
|
|
31
|
+
return value instanceof Uint8Array || value instanceof ArrayBuffer;
|
|
32
|
+
}
|
|
33
|
+
function isFetchRequest(req) {
|
|
34
|
+
return (typeof req.arrayBuffer === "function" &&
|
|
35
|
+
typeof req.headers.get === "function");
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The raw body and headers of a webhook request, or a {@link WebhookSignatureError} (`raw_body_required`)
|
|
39
|
+
* that says how to get the raw body when the request's body was already parsed or consumed.
|
|
40
|
+
*/
|
|
41
|
+
async function readWebhookRequest(req) {
|
|
42
|
+
if (req === null || typeof req !== "object" || req.headers === undefined) {
|
|
43
|
+
throw new errors_js_1.WebhookSignatureError("invalid_request", "verify(req) needs a Fetch Request or a Node request with headers.");
|
|
44
|
+
}
|
|
45
|
+
if (isFetchRequest(req)) {
|
|
46
|
+
if (req.bodyUsed === true) {
|
|
47
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `The request's body was already read. ${RAW_BODY_HELP}`);
|
|
48
|
+
}
|
|
49
|
+
return { body: new Uint8Array(await req.arrayBuffer()), headers: req.headers };
|
|
50
|
+
}
|
|
51
|
+
const node = req;
|
|
52
|
+
const body = node.body;
|
|
53
|
+
if (typeof body === "string" || isBytes(body)) {
|
|
54
|
+
return { body: body instanceof ArrayBuffer ? new Uint8Array(body) : body, headers: node.headers };
|
|
55
|
+
}
|
|
56
|
+
if (body !== undefined && body !== null && typeof body === "object" && Object.keys(body).length === 0) {
|
|
57
|
+
// express.raw and express.json leave {} when the content type did not match them.
|
|
58
|
+
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}`);
|
|
59
|
+
}
|
|
60
|
+
if (body !== undefined && body !== null) {
|
|
61
|
+
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}`);
|
|
62
|
+
}
|
|
63
|
+
if (typeof node.on === "function" && node.readableEnded !== true) {
|
|
64
|
+
const bytes = await new Promise((resolve, reject) => {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
node.on("data", (chunk) => chunks.push(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk));
|
|
67
|
+
node.on("end", () => {
|
|
68
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
69
|
+
let offset = 0;
|
|
70
|
+
for (const c of chunks) {
|
|
71
|
+
out.set(c, offset);
|
|
72
|
+
offset += c.length;
|
|
73
|
+
}
|
|
74
|
+
resolve(out);
|
|
75
|
+
});
|
|
76
|
+
node.on("error", reject);
|
|
77
|
+
});
|
|
78
|
+
return { body: bytes, headers: node.headers };
|
|
79
|
+
}
|
|
80
|
+
throw new errors_js_1.WebhookSignatureError("raw_body_required", `The request has no body to verify. ${RAW_BODY_HELP}`);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Verify a Standard Webhooks delivery and return the event. Pass the raw body exactly as received
|
|
84
|
+
* (string, Uint8Array, a Node buffer or ArrayBuffer), never a re-serialised parse.
|
|
85
|
+
*
|
|
86
|
+
* It is async because Web Crypto is: `await te.webhooks.verify(...)`.
|
|
87
|
+
*/
|
|
88
|
+
async function verifyWebhook(rawBody, headers, secret, options = {}) {
|
|
89
|
+
const id = header(headers, "webhook-id");
|
|
90
|
+
const timestamp = header(headers, "webhook-timestamp");
|
|
91
|
+
const signature = header(headers, "webhook-signature");
|
|
92
|
+
if (!id || !timestamp || !signature) {
|
|
93
|
+
throw new errors_js_1.WebhookSignatureError("missing_headers", "Missing webhook-id, webhook-timestamp or webhook-signature header");
|
|
94
|
+
}
|
|
95
|
+
if (!/^\d+$/.test(timestamp))
|
|
96
|
+
throw new errors_js_1.WebhookSignatureError("invalid_timestamp", "webhook-timestamp is not an integer");
|
|
97
|
+
const tolerance = options.toleranceSeconds ?? 300;
|
|
98
|
+
const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000);
|
|
99
|
+
if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) {
|
|
100
|
+
throw new errors_js_1.WebhookSignatureError("timestamp_out_of_tolerance", "webhook-timestamp is outside the tolerance window");
|
|
101
|
+
}
|
|
102
|
+
const bodyBytes = typeof rawBody === "string"
|
|
103
|
+
? new TextEncoder().encode(rawBody)
|
|
104
|
+
: rawBody instanceof Uint8Array
|
|
105
|
+
? rawBody
|
|
106
|
+
: new Uint8Array(rawBody);
|
|
107
|
+
const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
|
|
108
|
+
const signed = new Uint8Array(prefix.length + bodyBytes.length);
|
|
109
|
+
signed.set(prefix);
|
|
110
|
+
signed.set(bodyBytes, prefix.length);
|
|
111
|
+
// Candidate signatures: "v1,<base64>" entries separated by spaces; other versions are ignored.
|
|
112
|
+
const candidates = [];
|
|
113
|
+
for (const part of signature.split(" ")) {
|
|
114
|
+
const [version, value] = part.split(",", 2);
|
|
115
|
+
if (version !== "v1" || !value)
|
|
116
|
+
continue;
|
|
117
|
+
try {
|
|
118
|
+
candidates.push(b64decode(value));
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
// malformed base64: cannot match
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const crypto = await (0, runtime_js_1.getWebCrypto)();
|
|
125
|
+
const secrets = Array.isArray(secret) ? secret : [secret];
|
|
126
|
+
let valid = false;
|
|
127
|
+
for (const s of secrets) {
|
|
128
|
+
let keyBytes;
|
|
129
|
+
try {
|
|
130
|
+
keyBytes = b64decode(s.startsWith("whsec_") ? s.slice(6) : s);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
throw new errors_js_1.WebhookSignatureError("invalid_secret", "Webhook secret is not whsec_<base64>");
|
|
134
|
+
}
|
|
135
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
136
|
+
for (const sig of candidates) {
|
|
137
|
+
// subtle.verify compares in constant time.
|
|
138
|
+
if (await crypto.subtle.verify("HMAC", key, sig, signed))
|
|
139
|
+
valid = true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (!valid)
|
|
143
|
+
throw new errors_js_1.WebhookSignatureError("signature_mismatch", "No matching signature found for the payload");
|
|
144
|
+
try {
|
|
145
|
+
return (0, case_js_1.toCamel)(JSON.parse(new TextDecoder().decode(bodyBytes)));
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
throw new errors_js_1.WebhookSignatureError("invalid_payload", "Webhook body is not valid JSON");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function bytesOf(payload) {
|
|
152
|
+
return typeof payload === "string"
|
|
153
|
+
? new TextEncoder().encode(payload)
|
|
154
|
+
: payload instanceof Uint8Array
|
|
155
|
+
? payload
|
|
156
|
+
: new Uint8Array(payload);
|
|
157
|
+
}
|
|
158
|
+
function b64encode(bytes) {
|
|
159
|
+
let bin = "";
|
|
160
|
+
for (let i = 0; i < bytes.length; i++)
|
|
161
|
+
bin += String.fromCharCode(bytes[i]);
|
|
162
|
+
return btoa(bin);
|
|
163
|
+
}
|
|
164
|
+
function defaultMessageId(body) {
|
|
165
|
+
try {
|
|
166
|
+
const parsed = JSON.parse(new TextDecoder().decode(body));
|
|
167
|
+
if (typeof parsed?.id === "string" && parsed.id !== "")
|
|
168
|
+
return parsed.id;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
// not JSON: a random id
|
|
172
|
+
}
|
|
173
|
+
return `msg_${(0, runtime_js_1.randomUUID)().replace(/-/g, "").slice(0, 24)}`;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The headers Timbereye would send with `payload`, signed with `secret` (Standard Webhooks: `webhook-id`,
|
|
177
|
+
* `webhook-timestamp`, `webhook-signature`), for testing your webhook handler without the network. `verifyWebhook`
|
|
178
|
+
* accepts them. Never use it to accept a request: it signs, it does not check.
|
|
179
|
+
*
|
|
180
|
+
* ```ts
|
|
181
|
+
* const body = JSON.stringify(event)
|
|
182
|
+
* const headers = await generateTestWebhookHeaders({ payload: body, secret: "whsec_…" })
|
|
183
|
+
* await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }))
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
async function generateTestWebhookHeaders(params) {
|
|
187
|
+
const { secret } = params;
|
|
188
|
+
if (typeof secret !== "string" || secret === "")
|
|
189
|
+
throw new errors_js_1.WebhookSignatureError("invalid_secret", "generateTestWebhookHeaders needs the whsec_… secret");
|
|
190
|
+
const body = bytesOf(params.payload);
|
|
191
|
+
const id = params.id ?? defaultMessageId(body);
|
|
192
|
+
const timestamp = String(Math.floor(params.timestamp ?? Date.now() / 1000));
|
|
193
|
+
let keyBytes;
|
|
194
|
+
try {
|
|
195
|
+
keyBytes = b64decode(secret.startsWith("whsec_") ? secret.slice(6) : secret);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
throw new errors_js_1.WebhookSignatureError("invalid_secret", "Webhook secret is not whsec_<base64>");
|
|
199
|
+
}
|
|
200
|
+
const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
|
|
201
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
202
|
+
signed.set(prefix);
|
|
203
|
+
signed.set(body, prefix.length);
|
|
204
|
+
const crypto = await (0, runtime_js_1.getWebCrypto)();
|
|
205
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
206
|
+
const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed));
|
|
207
|
+
return {
|
|
208
|
+
"content-type": "application/json",
|
|
209
|
+
"webhook-id": id,
|
|
210
|
+
"webhook-timestamp": timestamp,
|
|
211
|
+
"webhook-signature": `v1,${b64encode(signature)}`,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
@@ -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 = "by_kind" | "headers" | "layout" | "metadata" | "msf" | "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,47 @@
|
|
|
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 = [
|
|
10
|
+
"by_kind",
|
|
11
|
+
"details",
|
|
12
|
+
"headers",
|
|
13
|
+
"layout",
|
|
14
|
+
"metadata",
|
|
15
|
+
"msf",
|
|
16
|
+
"rejection_gates",
|
|
17
|
+
];
|
|
18
|
+
const OPAQUE_SNAKE = new Set(OPAQUE_KEYS);
|
|
19
|
+
const OPAQUE_CAMEL = new Set(OPAQUE_KEYS.map(snakeToCamel));
|
|
20
|
+
export function snakeToCamel(key) {
|
|
21
|
+
return key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
22
|
+
}
|
|
23
|
+
export function camelToSnake(key) {
|
|
24
|
+
return key.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
25
|
+
}
|
|
26
|
+
function isPlainObject(v) {
|
|
27
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
28
|
+
}
|
|
29
|
+
function convert(value, mapKey, opaque) {
|
|
30
|
+
if (Array.isArray(value))
|
|
31
|
+
return value.map((v) => convert(v, mapKey, opaque));
|
|
32
|
+
if (!isPlainObject(value))
|
|
33
|
+
return value;
|
|
34
|
+
const out = {};
|
|
35
|
+
for (const [k, v] of Object.entries(value)) {
|
|
36
|
+
out[mapKey(k)] = opaque.has(k) ? v : convert(v, mapKey, opaque);
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
/** Convert a request value from the SDK's camelCase to the API's snake_case. */
|
|
41
|
+
export function toSnake(value) {
|
|
42
|
+
return convert(value, camelToSnake, OPAQUE_CAMEL);
|
|
43
|
+
}
|
|
44
|
+
/** Convert a response value from the API's snake_case to the SDK's camelCase. */
|
|
45
|
+
export function toCamel(value) {
|
|
46
|
+
return convert(value, snakeToCamel, OPAQUE_SNAKE);
|
|
47
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type ClientOptions } from "./http.js";
|
|
2
|
+
import { createResources } from "./resources.js";
|
|
3
|
+
import { type TestWebhookParams, 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
|
+
* For tests: the headers Timbereye would send with `payload`, signed with `secret` (default: the client's
|
|
39
|
+
* webhook secret, else `TIMBEREYE_WEBHOOK_SECRET`). `verify` and `handler` accept them. It signs; it never
|
|
40
|
+
* checks a request.
|
|
41
|
+
*/
|
|
42
|
+
generateTestHeaders(params: Omit<TestWebhookParams, "secret"> & {
|
|
43
|
+
secret?: string;
|
|
44
|
+
}): Promise<Record<string, string>>;
|
|
45
|
+
}
|
|
46
|
+
/** What `webhooks.handler` returns: a Fetch handler, or a Node/Express one. */
|
|
47
|
+
export interface WebhookRouteHandler {
|
|
48
|
+
(req: Request): Promise<Response>;
|
|
49
|
+
(req: WebhookRequest, res: WebhookResponse, next?: (error?: unknown) => void): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** The part of a Node `ServerResponse` the handler uses. */
|
|
52
|
+
export interface WebhookResponse {
|
|
53
|
+
statusCode: number;
|
|
54
|
+
headersSent?: boolean;
|
|
55
|
+
setHeader(name: string, value: string): unknown;
|
|
56
|
+
end(body?: string): unknown;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* ```ts
|
|
60
|
+
* const te = new Timbereye() // reads TIMBEREYE_SECRET_KEY (and TIMBEREYE_WEBHOOK_SECRET for webhooks.verify)
|
|
61
|
+
* const group = await te.groups.create({ kind: "container", externalRef: "MSKU1234567" })
|
|
62
|
+
* ```
|
|
63
|
+
*
|
|
64
|
+
* `new Timbereye(apiKey, options)` and `new Timbereye({ apiKey, webhookSecret, baseUrl, ... })` also work; an
|
|
65
|
+
* explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
|
|
66
|
+
* `TIMBEREYE_API_URL`).
|
|
67
|
+
*/
|
|
68
|
+
export declare class Timbereye {
|
|
69
|
+
/** Test mode only: a simulated scan and refinement, so the loop can run with no device and no model. */
|
|
70
|
+
readonly testMode: ReturnType<typeof createResources>["testMode"];
|
|
71
|
+
readonly groups: ReturnType<typeof createResources>["groups"];
|
|
72
|
+
readonly items: ReturnType<typeof createResources>["items"];
|
|
73
|
+
readonly scans: ReturnType<typeof createResources>["scans"];
|
|
74
|
+
readonly images: ReturnType<typeof createResources>["images"];
|
|
75
|
+
readonly places: ReturnType<typeof createResources>["places"];
|
|
76
|
+
/** Tag printing: label designs for the 62 mm QR tags. */
|
|
77
|
+
readonly labelTemplates: ReturnType<typeof createResources>["labelTemplates"];
|
|
78
|
+
/** Tag printing: batches of tags and their ZPL or PDF print files. */
|
|
79
|
+
readonly tagBatches: ReturnType<typeof createResources>["tagBatches"];
|
|
80
|
+
readonly species: ReturnType<typeof createResources>["species"];
|
|
81
|
+
readonly volumeRules: ReturnType<typeof createResources>["volumeRules"];
|
|
82
|
+
readonly events: ReturnType<typeof createResources>["events"];
|
|
83
|
+
readonly webhookEndpoints: ReturnType<typeof createResources>["webhookEndpoints"];
|
|
84
|
+
readonly captureTokens: ReturnType<typeof createResources>["captureTokens"];
|
|
85
|
+
/** Key management: dashboard sessions only (an API key is refused with 403 `session_required`). */
|
|
86
|
+
readonly apiKeys: ReturnType<typeof createResources>["apiKeys"];
|
|
87
|
+
readonly team: ReturnType<typeof createResources>["team"];
|
|
88
|
+
readonly auditLog: ReturnType<typeof createResources>["auditLog"];
|
|
89
|
+
readonly usage: ReturnType<typeof createResources>["usage"];
|
|
90
|
+
/** The organisation's billing (dashboard sessions only). */
|
|
91
|
+
readonly billing: ReturnType<typeof createResources>["billing"];
|
|
92
|
+
readonly models: ReturnType<typeof createResources>["models"];
|
|
93
|
+
readonly account: ReturnType<typeof createResources>["account"];
|
|
94
|
+
/** The developer console's bootstrap and onboarding: dashboard sessions only. */
|
|
95
|
+
readonly console: ReturnType<typeof createResources>["console"];
|
|
96
|
+
readonly webhooks: WebhookHelpers;
|
|
97
|
+
constructor(apiKeyOrOptions?: string | TimbereyeOptions, options?: TimbereyeOptions);
|
|
98
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
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 { generateTestWebhookHeaders, 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, baseUrl, ... })` also work; an
|
|
21
|
+
* explicit key, secret or `baseUrl` wins over the environment (`TIMBEREYE_SECRET_KEY`, `TIMBEREYE_WEBHOOK_SECRET`,
|
|
22
|
+
* `TIMBEREYE_API_URL`).
|
|
23
|
+
*/
|
|
24
|
+
export class Timbereye {
|
|
25
|
+
constructor(apiKeyOrOptions, options = {}) {
|
|
26
|
+
const merged = typeof apiKeyOrOptions === "object" && apiKeyOrOptions !== null
|
|
27
|
+
? apiKeyOrOptions
|
|
28
|
+
: { ...options, apiKey: apiKeyOrOptions ?? options.apiKey };
|
|
29
|
+
const { apiKey: explicitKey, webhookSecret, ...transportOptions } = merged;
|
|
30
|
+
const apiKey = explicitKey ?? readEnv("TIMBEREYE_SECRET_KEY");
|
|
31
|
+
if (apiKey === undefined) {
|
|
32
|
+
throw new TimbereyeError({
|
|
33
|
+
message: "No Timbereye API key: set TIMBEREYE_SECRET_KEY in the environment, or pass the key: " +
|
|
34
|
+
'new Timbereye("te_test_sk_…").',
|
|
35
|
+
type: "client_error",
|
|
36
|
+
code: "api_key_missing",
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
this.webhooks = {
|
|
40
|
+
verify: ((first, ...rest) => {
|
|
41
|
+
if (typeof first === "string" ||
|
|
42
|
+
first instanceof Uint8Array ||
|
|
43
|
+
first instanceof ArrayBuffer) {
|
|
44
|
+
const [headers, secret, verifyOptions] = rest;
|
|
45
|
+
return verifyWebhook(first, headers, secret, verifyOptions);
|
|
46
|
+
}
|
|
47
|
+
return verifyRequest(first, webhookSecret, rest[0]);
|
|
48
|
+
}),
|
|
49
|
+
handler: (onEvent, verifyOptions) => webhookHandler(webhookSecret, onEvent, verifyOptions),
|
|
50
|
+
generateTestHeaders: async (params) => {
|
|
51
|
+
const configured = Array.isArray(webhookSecret) ? webhookSecret[0] : webhookSecret;
|
|
52
|
+
const secret = params.secret ?? configured ?? readEnv("TIMBEREYE_WEBHOOK_SECRET");
|
|
53
|
+
if (secret === undefined)
|
|
54
|
+
throw new WebhookSignatureError("webhook_secret_missing", "No webhook secret: pass { secret }, set TIMBEREYE_WEBHOOK_SECRET, or new Timbereye({ webhookSecret }).");
|
|
55
|
+
return generateTestWebhookHeaders({ ...params, secret });
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
// An explicit baseUrl, else TIMBEREYE_API_URL where the runtime has an environment, else production.
|
|
59
|
+
const baseUrl = transportOptions.baseUrl ?? readEnv("TIMBEREYE_API_URL");
|
|
60
|
+
const r = createResources(new Transport(apiKey, baseUrl === undefined ? transportOptions : { ...transportOptions, baseUrl }));
|
|
61
|
+
this.testMode = r.testMode;
|
|
62
|
+
this.groups = r.groups;
|
|
63
|
+
this.items = r.items;
|
|
64
|
+
this.scans = r.scans;
|
|
65
|
+
this.images = r.images;
|
|
66
|
+
this.places = r.places;
|
|
67
|
+
this.labelTemplates = r.labelTemplates;
|
|
68
|
+
this.tagBatches = r.tagBatches;
|
|
69
|
+
this.species = r.species;
|
|
70
|
+
this.volumeRules = r.volumeRules;
|
|
71
|
+
this.events = r.events;
|
|
72
|
+
this.webhookEndpoints = r.webhookEndpoints;
|
|
73
|
+
this.captureTokens = r.captureTokens;
|
|
74
|
+
this.apiKeys = r.apiKeys;
|
|
75
|
+
this.team = r.team;
|
|
76
|
+
this.auditLog = r.auditLog;
|
|
77
|
+
this.usage = r.usage;
|
|
78
|
+
this.billing = r.billing;
|
|
79
|
+
this.models = r.models;
|
|
80
|
+
this.account = r.account;
|
|
81
|
+
this.console = r.console;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function verifyRequest(req, configured, options) {
|
|
85
|
+
const secret = configured ?? readEnv("TIMBEREYE_WEBHOOK_SECRET");
|
|
86
|
+
if (secret === undefined || (Array.isArray(secret) && secret.length === 0)) {
|
|
87
|
+
throw new WebhookSignatureError("webhook_secret_missing", "No webhook secret: set TIMBEREYE_WEBHOOK_SECRET (the endpoint's whsec_… secret) in the environment, " +
|
|
88
|
+
"or pass it: new Timbereye({ webhookSecret }).");
|
|
89
|
+
}
|
|
90
|
+
const { body, headers } = await readWebhookRequest(req);
|
|
91
|
+
return verifyWebhook(body, headers, secret, options);
|
|
92
|
+
}
|
|
93
|
+
function webhookHandler(configured, onEvent, options) {
|
|
94
|
+
return (async (req, res, next) => {
|
|
95
|
+
const answer = (status, body) => {
|
|
96
|
+
if (res === undefined)
|
|
97
|
+
return new Response(body, { status, headers: { "content-type": "application/json" } });
|
|
98
|
+
if (res.headersSent !== true) {
|
|
99
|
+
res.statusCode = status;
|
|
100
|
+
res.setHeader("content-type", "application/json");
|
|
101
|
+
res.end(body);
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
};
|
|
105
|
+
try {
|
|
106
|
+
let event;
|
|
107
|
+
try {
|
|
108
|
+
event = await verifyRequest(req, configured, options);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (error instanceof WebhookSignatureError &&
|
|
112
|
+
error.code !== null &&
|
|
113
|
+
FORGED_CODES.has(error.code))
|
|
114
|
+
return answer(400, JSON.stringify({ error: { code: error.code, message: error.message } }));
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
await onEvent(event);
|
|
118
|
+
return answer(200, "{}");
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (res === undefined)
|
|
122
|
+
throw error;
|
|
123
|
+
if (next !== undefined)
|
|
124
|
+
return next(error);
|
|
125
|
+
answer(500, JSON.stringify({ error: { code: "handler_error" } }));
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|