@kite-sa/sdk 0.6.0 → 0.9.2

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.
@@ -0,0 +1,106 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ /** Every event type this version of the SDK knows. */
3
+ export const WEBHOOK_EVENT_TYPES = [
4
+ "listing.created",
5
+ "listing.price_changed",
6
+ "listing.updated",
7
+ "listing.delisted",
8
+ "listing.relisted",
9
+ ];
10
+ /**
11
+ * Header Kite signs each webhook delivery with. Deliveries also carry the
12
+ * deprecated `Darak-Signature` with the same value; either verifies.
13
+ */
14
+ export const SIGNATURE_HEADER = "Kite-Signature";
15
+ /** How old a signature may be before it is rejected, in seconds. */
16
+ export const TOLERANCE_SECONDS = 300;
17
+ /**
18
+ * Checks a `Kite-Signature` header (`t=<unix>,v1=<hex>`) against the raw
19
+ * request body: HMAC-SHA256 of `${t}.${body}` under your endpoint's signing
20
+ * secret, compared in constant time. Pass the body exactly as received, before
21
+ * any JSON parsing. `secret` may be an array so a rotation can overlap: the old
22
+ * secret keeps verifying until the deploy carrying the new one is through.
23
+ * During a rotation overlap the header has a `v1` entry per live secret; the
24
+ * signature is valid if any of them matches.
25
+ *
26
+ * Imported from `@kite-sa/sdk/webhooks` because it needs `node:crypto`; the
27
+ * main entry stays runtime-neutral.
28
+ */
29
+ export function verifyWebhookSignature(header, body, secret, options = {}) {
30
+ if (!header)
31
+ return { valid: false, reason: "malformed" };
32
+ const pairs = header
33
+ .split(",")
34
+ .map((p) => p.trim().split("=", 2))
35
+ .filter((p) => p.length === 2);
36
+ const tText = pairs.find(([k]) => k === "t")?.[1];
37
+ const t = Number(tText);
38
+ // After a secret rotation the header carries one `v1` per live secret (new
39
+ // first) until the overlap ends; any of them may match.
40
+ const v1s = pairs.filter(([k, v]) => k === "v1" && v).map(([, v]) => v);
41
+ if (v1s.length === 0 || !tText || !Number.isFinite(t)) {
42
+ return { valid: false, reason: "malformed" };
43
+ }
44
+ // Age first and independently of the secret: a genuine but stale signature
45
+ // is a replay, not an authentication failure.
46
+ const now = options.now ?? Math.floor(Date.now() / 1000);
47
+ if (Math.abs(now - t) > (options.toleranceSeconds ?? TOLERANCE_SECONDS)) {
48
+ return { valid: false, reason: "too_old" };
49
+ }
50
+ const secrets = typeof secret === "string" ? [secret] : secret;
51
+ const given = v1s.map((v1) => Buffer.from(v1, "utf8"));
52
+ const matches = secrets.some((s) => {
53
+ const expected = Buffer.from(createHmac("sha256", s).update(`${t}.${body}`).digest("hex"));
54
+ return given.some((g) => expected.length === g.length && timingSafeEqual(expected, g));
55
+ });
56
+ return matches ? { valid: true } : { valid: false, reason: "no_match" };
57
+ }
58
+ /**
59
+ * Thrown by `parseWebhookEvent`. `reason` is for your logs; never send it back
60
+ * to the caller.
61
+ */
62
+ export class WebhookError extends Error {
63
+ reason;
64
+ constructor(reason, message) {
65
+ super(message);
66
+ this.reason = reason;
67
+ this.name = "WebhookError";
68
+ }
69
+ }
70
+ /**
71
+ * Verifies a delivery with `verifyWebhookSignature` and returns its event,
72
+ * typed by `type`. Throws `WebhookError` when the signature doesn't verify,
73
+ * the body isn't a JSON event, or `type` is one this SDK doesn't know (a newer
74
+ * event type: answer 2xx and ignore it, or upgrade). Pass the raw body, before
75
+ * any JSON parsing.
76
+ *
77
+ * Test events carry `test: true`. Deliveries are at least once: deduplicate on
78
+ * `event.id`, which is also the `Kite-Event-Id` header.
79
+ */
80
+ export function parseWebhookEvent(header, body, secret, options = {}) {
81
+ const result = verifyWebhookSignature(header, body, secret, options);
82
+ if (!result.valid) {
83
+ const reason = result.reason ?? "no_match";
84
+ throw new WebhookError(reason, `Invalid webhook signature (${reason}).`);
85
+ }
86
+ let event;
87
+ try {
88
+ event = JSON.parse(body);
89
+ }
90
+ catch {
91
+ throw new WebhookError("invalid_json", "Webhook body is not valid JSON.");
92
+ }
93
+ if (!event ||
94
+ typeof event !== "object" ||
95
+ Array.isArray(event) ||
96
+ !("data" in event) ||
97
+ !event.data ||
98
+ typeof event.data !== "object") {
99
+ throw new WebhookError("invalid_json", "Webhook body is not an event object.");
100
+ }
101
+ const type = event.type;
102
+ if (!WEBHOOK_EVENT_TYPES.includes(type)) {
103
+ throw new WebhookError("unknown_type", `Unknown webhook event type: ${String(type)}.`);
104
+ }
105
+ return event;
106
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kite-sa/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.9.2",
4
4
  "description": "Official JavaScript/TypeScript client for the Kite API: Saudi real-estate listings and market data.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,6 +8,10 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "import": "./dist/index.js"
11
+ },
12
+ "./webhooks": {
13
+ "types": "./dist/webhooks.d.ts",
14
+ "import": "./dist/webhooks.js"
11
15
  }
12
16
  },
13
17
  "files": [