@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.
Files changed (53) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/LICENSE +202 -0
  3. package/README.md +330 -2
  4. package/dist/cjs/case.d.ts +23 -0
  5. package/dist/cjs/case.js +46 -0
  6. package/dist/cjs/client.d.ts +89 -0
  7. package/dist/cjs/client.js +122 -0
  8. package/dist/cjs/errors.d.ts +63 -0
  9. package/dist/cjs/errors.js +107 -0
  10. package/dist/cjs/generated/schema.d.ts +13436 -0
  11. package/dist/cjs/generated/schema.js +6 -0
  12. package/dist/cjs/http.d.ts +92 -0
  13. package/dist/cjs/http.js +238 -0
  14. package/dist/cjs/index.d.ts +14 -0
  15. package/dist/cjs/index.js +28 -0
  16. package/dist/cjs/package.json +1 -0
  17. package/dist/cjs/pagination.d.ts +31 -0
  18. package/dist/cjs/pagination.js +52 -0
  19. package/dist/cjs/resources.d.ts +7879 -0
  20. package/dist/cjs/resources.js +456 -0
  21. package/dist/cjs/runtime.d.ts +20 -0
  22. package/dist/cjs/runtime.js +74 -0
  23. package/dist/cjs/types.d.ts +525 -0
  24. package/dist/cjs/types.js +2 -0
  25. package/dist/cjs/units.d.ts +26 -0
  26. package/dist/cjs/units.js +45 -0
  27. package/dist/cjs/webhooks.d.ts +44 -0
  28. package/dist/cjs/webhooks.js +149 -0
  29. package/dist/esm/case.d.ts +23 -0
  30. package/dist/esm/case.js +39 -0
  31. package/dist/esm/client.d.ts +89 -0
  32. package/dist/esm/client.js +118 -0
  33. package/dist/esm/errors.d.ts +63 -0
  34. package/dist/esm/errors.js +93 -0
  35. package/dist/esm/generated/schema.d.ts +13436 -0
  36. package/dist/esm/generated/schema.js +5 -0
  37. package/dist/esm/http.d.ts +92 -0
  38. package/dist/esm/http.js +232 -0
  39. package/dist/esm/index.d.ts +14 -0
  40. package/dist/esm/index.js +6 -0
  41. package/dist/esm/pagination.d.ts +31 -0
  42. package/dist/esm/pagination.js +49 -0
  43. package/dist/esm/resources.d.ts +7879 -0
  44. package/dist/esm/resources.js +453 -0
  45. package/dist/esm/runtime.d.ts +20 -0
  46. package/dist/esm/runtime.js +46 -0
  47. package/dist/esm/types.d.ts +525 -0
  48. package/dist/esm/types.js +1 -0
  49. package/dist/esm/units.d.ts +26 -0
  50. package/dist/esm/units.js +38 -0
  51. package/dist/esm/webhooks.d.ts +44 -0
  52. package/dist/esm/webhooks.js +145 -0
  53. package/package.json +51 -5
@@ -0,0 +1,145 @@
1
+ import { toCamel } from "./case.js";
2
+ import { WebhookSignatureError } from "./errors.js";
3
+ import { getWebCrypto } from "./runtime.js";
4
+ function header(headers, name) {
5
+ if (typeof headers.get === "function") {
6
+ return headers.get(name) ?? undefined;
7
+ }
8
+ for (const [k, v] of Object.entries(headers)) {
9
+ if (k.toLowerCase() === name)
10
+ return Array.isArray(v) ? v.join(" ") : v;
11
+ }
12
+ return undefined;
13
+ }
14
+ function b64decode(s) {
15
+ const bin = atob(s);
16
+ const out = new Uint8Array(bin.length);
17
+ for (let i = 0; i < bin.length; i++)
18
+ out[i] = bin.charCodeAt(i);
19
+ return out;
20
+ }
21
+ const RAW_BODY_HELP = "Webhook signatures are computed over the exact bytes Timbereye sent, so verify needs the raw body. " +
22
+ "In Express, give the webhook route the raw parser instead of express.json(): " +
23
+ 'app.post("/webhooks/timbereye", express.raw({ type: "application/json" }), handler). ' +
24
+ "Or call verify(rawBody, headers, secret) with the body as received.";
25
+ function isBytes(value) {
26
+ return value instanceof Uint8Array || value instanceof ArrayBuffer;
27
+ }
28
+ function isFetchRequest(req) {
29
+ return (typeof req.arrayBuffer === "function" &&
30
+ typeof req.headers.get === "function");
31
+ }
32
+ /**
33
+ * The raw body and headers of a webhook request, or a {@link WebhookSignatureError} (`raw_body_required`)
34
+ * that says how to get the raw body when the request's body was already parsed or consumed.
35
+ */
36
+ export async function readWebhookRequest(req) {
37
+ if (req === null || typeof req !== "object" || req.headers === undefined) {
38
+ throw new WebhookSignatureError("invalid_request", "verify(req) needs a Fetch Request or a Node request with headers.");
39
+ }
40
+ if (isFetchRequest(req)) {
41
+ if (req.bodyUsed === true) {
42
+ throw new WebhookSignatureError("raw_body_required", `The request's body was already read. ${RAW_BODY_HELP}`);
43
+ }
44
+ return { body: new Uint8Array(await req.arrayBuffer()), headers: req.headers };
45
+ }
46
+ const node = req;
47
+ const body = node.body;
48
+ if (typeof body === "string" || isBytes(body)) {
49
+ return { body: body instanceof ArrayBuffer ? new Uint8Array(body) : body, headers: node.headers };
50
+ }
51
+ if (body !== undefined && body !== null && typeof body === "object" && Object.keys(body).length === 0) {
52
+ // express.raw and express.json leave {} when the content type did not match them.
53
+ throw new WebhookSignatureError("raw_body_required", `req.body is an empty object: no raw parser read this request (check its type option). ${RAW_BODY_HELP}`);
54
+ }
55
+ if (body !== undefined && body !== null) {
56
+ throw new WebhookSignatureError("raw_body_required", `The request's body was already parsed (req.body is ${Array.isArray(body) ? "an array" : typeof body}). ${RAW_BODY_HELP}`);
57
+ }
58
+ if (typeof node.on === "function" && node.readableEnded !== true) {
59
+ const bytes = await new Promise((resolve, reject) => {
60
+ const chunks = [];
61
+ node.on("data", (chunk) => chunks.push(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk));
62
+ node.on("end", () => {
63
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
64
+ let offset = 0;
65
+ for (const c of chunks) {
66
+ out.set(c, offset);
67
+ offset += c.length;
68
+ }
69
+ resolve(out);
70
+ });
71
+ node.on("error", reject);
72
+ });
73
+ return { body: bytes, headers: node.headers };
74
+ }
75
+ throw new WebhookSignatureError("raw_body_required", `The request has no body to verify. ${RAW_BODY_HELP}`);
76
+ }
77
+ /**
78
+ * Verify a Standard Webhooks delivery and return the event. Pass the raw body exactly as received
79
+ * (string, Uint8Array, a Node buffer or ArrayBuffer), never a re-serialised parse.
80
+ *
81
+ * It is async because Web Crypto is: `await te.webhooks.verify(...)`.
82
+ */
83
+ export async function verifyWebhook(rawBody, headers, secret, options = {}) {
84
+ const id = header(headers, "webhook-id");
85
+ const timestamp = header(headers, "webhook-timestamp");
86
+ const signature = header(headers, "webhook-signature");
87
+ if (!id || !timestamp || !signature) {
88
+ throw new WebhookSignatureError("missing_headers", "Missing webhook-id, webhook-timestamp or webhook-signature header");
89
+ }
90
+ if (!/^\d+$/.test(timestamp))
91
+ throw new WebhookSignatureError("invalid_timestamp", "webhook-timestamp is not an integer");
92
+ const tolerance = options.toleranceSeconds ?? 300;
93
+ const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000);
94
+ if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) {
95
+ throw new WebhookSignatureError("timestamp_out_of_tolerance", "webhook-timestamp is outside the tolerance window");
96
+ }
97
+ const bodyBytes = typeof rawBody === "string"
98
+ ? new TextEncoder().encode(rawBody)
99
+ : rawBody instanceof Uint8Array
100
+ ? rawBody
101
+ : new Uint8Array(rawBody);
102
+ const prefix = new TextEncoder().encode(`${id}.${timestamp}.`);
103
+ const signed = new Uint8Array(prefix.length + bodyBytes.length);
104
+ signed.set(prefix);
105
+ signed.set(bodyBytes, prefix.length);
106
+ // Candidate signatures: "v1,<base64>" entries separated by spaces; other versions are ignored.
107
+ const candidates = [];
108
+ for (const part of signature.split(" ")) {
109
+ const [version, value] = part.split(",", 2);
110
+ if (version !== "v1" || !value)
111
+ continue;
112
+ try {
113
+ candidates.push(b64decode(value));
114
+ }
115
+ catch {
116
+ // malformed base64: cannot match
117
+ }
118
+ }
119
+ const crypto = await getWebCrypto();
120
+ const secrets = Array.isArray(secret) ? secret : [secret];
121
+ let valid = false;
122
+ for (const s of secrets) {
123
+ let keyBytes;
124
+ try {
125
+ keyBytes = b64decode(s.startsWith("whsec_") ? s.slice(6) : s);
126
+ }
127
+ catch {
128
+ throw new WebhookSignatureError("invalid_secret", "Webhook secret is not whsec_<base64>");
129
+ }
130
+ const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
131
+ for (const sig of candidates) {
132
+ // subtle.verify compares in constant time.
133
+ if (await crypto.subtle.verify("HMAC", key, sig, signed))
134
+ valid = true;
135
+ }
136
+ }
137
+ if (!valid)
138
+ throw new WebhookSignatureError("signature_mismatch", "No matching signature found for the payload");
139
+ try {
140
+ return toCamel(JSON.parse(new TextDecoder().decode(bodyBytes)));
141
+ }
142
+ catch {
143
+ throw new WebhookSignatureError("invalid_payload", "Webhook body is not valid JSON");
144
+ }
145
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
- "name": "@timbereye/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@timbereye/sdk",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for the Timbereye API: measurements of logs and loads, groups, scans, places and webhooks.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/cjs/index.js",
8
+ "types": "./dist/esm/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/esm/index.d.ts",
13
+ "default": "./dist/esm/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/cjs/index.d.ts",
17
+ "default": "./dist/cjs/index.js"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE",
25
+ "CHANGELOG.md"
26
+ ],
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "keywords": [
32
+ "timbereye",
33
+ "forestry",
34
+ "logs",
35
+ "timber",
36
+ "measurement",
37
+ "sdk"
38
+ ],
39
+ "scripts": {
40
+ "generate": "../../node_modules/.bin/openapi-typescript ../../Timbereye/OpenApi/timbereye.v1.yaml --default-non-nullable false -o src/generated/schema.ts",
41
+ "build": "rm -rf dist && ../../node_modules/.bin/tsc -p tsconfig.build.json && ../../node_modules/.bin/tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json','{\\\"type\\\":\\\"commonjs\\\"}\\n')\"",
42
+ "typecheck": "../../node_modules/.bin/tsc -p tsconfig.json --noEmit",
43
+ "test": "../../node_modules/.bin/mocha",
44
+ "prepack": "npm run build"
45
+ },
46
+ "module": "./dist/esm/index.js",
47
+ "author": "Timbereye",
48
+ "homepage": "https://www.timbereye.com/docs/typescript-sdk/",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }