@replicer/sdk 0.1.1 → 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/dist/webhooks.cjs CHANGED
@@ -20,26 +20,110 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/webhooks.ts
21
21
  var webhooks_exports = {};
22
22
  __export(webhooks_exports, {
23
+ DEFAULT_WEBHOOK_TOLERANCE_SECONDS: () => DEFAULT_WEBHOOK_TOLERANCE_SECONDS,
24
+ WEBHOOK_SIGNATURE_HEADER: () => WEBHOOK_SIGNATURE_HEADER,
25
+ WebhookSignatureError: () => WebhookSignatureError,
26
+ constructEvent: () => constructEvent,
23
27
  verifyWebhookSignature: () => verifyWebhookSignature
24
28
  });
25
29
  module.exports = __toCommonJS(webhooks_exports);
30
+
31
+ // src/signature.ts
26
32
  var import_node_crypto = require("crypto");
27
- var SIGNATURE_PREFIX = "sha256=";
28
- var HEX_SHA256 = /^[0-9a-f]{64}$/;
29
- function verifyWebhookSignature({ payload, signature, secret }) {
30
- if (typeof signature !== "string" || !secret) return false;
31
- let hex = signature.trim();
32
- if (hex.slice(0, SIGNATURE_PREFIX.length).toLowerCase() === SIGNATURE_PREFIX) {
33
- hex = hex.slice(SIGNATURE_PREFIX.length);
34
- }
35
- hex = hex.toLowerCase();
36
- if (!HEX_SHA256.test(hex)) return false;
37
- const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(payload).digest();
38
- const received = Buffer.from(hex, "hex");
39
- if (received.length !== expected.length) return false;
40
- return (0, import_node_crypto.timingSafeEqual)(expected, received);
33
+ var SIGNATURE_HEADER = "Replicer-Signature";
34
+ var DEFAULT_TOLERANCE_SECONDS = 300;
35
+ var HEX_SHA256 = /^[0-9a-f]{64}$/i;
36
+ var UNIX_SECONDS = /^\d{1,12}$/;
37
+ function parseHeader(header) {
38
+ let timestamp = null;
39
+ const signatures = [];
40
+ for (const part of header.split(",")) {
41
+ const eq = part.indexOf("=");
42
+ if (eq <= 0) continue;
43
+ const key = part.slice(0, eq).trim();
44
+ const value = part.slice(eq + 1).trim();
45
+ if (key === "t") {
46
+ if (timestamp !== null || !UNIX_SECONDS.test(value)) return null;
47
+ timestamp = Number(value);
48
+ } else if (key === "v1" && HEX_SHA256.test(value)) {
49
+ signatures.push(Buffer.from(value, "hex"));
50
+ }
51
+ }
52
+ if (timestamp === null || signatures.length === 0) return null;
53
+ return { timestamp, signatures };
54
+ }
55
+ function sign(secret, timestamp, payload) {
56
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp}.`).update(payload).digest();
57
+ }
58
+ function verifySignatureHeader(input) {
59
+ if (!input || typeof input.header !== "string") return false;
60
+ const payload = input.payload;
61
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array)) return false;
62
+ const secrets = [input.secret, ...Array.isArray(input.secrets) ? input.secrets : []].filter((s) => typeof s === "string" && s !== "");
63
+ if (secrets.length === 0) return false;
64
+ const parsed = parseHeader(input.header);
65
+ if (!parsed) return false;
66
+ const tolerance = typeof input.toleranceSeconds === "number" && Number.isFinite(input.toleranceSeconds) && input.toleranceSeconds >= 0 ? input.toleranceSeconds : DEFAULT_TOLERANCE_SECONDS;
67
+ const nowMs = (input.now ?? /* @__PURE__ */ new Date()).getTime();
68
+ if (!Number.isFinite(nowMs)) return false;
69
+ if (Math.abs(nowMs / 1e3 - parsed.timestamp) > tolerance) return false;
70
+ let match = false;
71
+ for (const secret of secrets) {
72
+ const expected = sign(secret, parsed.timestamp, payload);
73
+ for (const received of parsed.signatures) {
74
+ if ((0, import_node_crypto.timingSafeEqual)(expected, received)) match = true;
75
+ }
76
+ }
77
+ return match;
78
+ }
79
+
80
+ // src/webhooks.ts
81
+ var WEBHOOK_SIGNATURE_HEADER = SIGNATURE_HEADER;
82
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
83
+ var WebhookSignatureError = class extends Error {
84
+ constructor(message) {
85
+ super(message);
86
+ this.name = "WebhookSignatureError";
87
+ }
88
+ };
89
+ function assertNoRenamedSignature(input) {
90
+ if (!input || typeof input !== "object") return;
91
+ const fields = input;
92
+ if (fields.header === void 0 && "signature" in fields) {
93
+ throw new TypeError(
94
+ `'signature' was renamed to 'header' in @replicer/sdk 0.2.0: pass the ${WEBHOOK_SIGNATURE_HEADER} header value as 'header'`
95
+ );
96
+ }
97
+ }
98
+ function verifyWebhookSignature(input) {
99
+ assertNoRenamedSignature(input);
100
+ return verifySignatureHeader(input);
101
+ }
102
+ function constructEvent(input) {
103
+ assertNoRenamedSignature(input);
104
+ if (!verifyWebhookSignature(input)) {
105
+ throw new WebhookSignatureError("Invalid webhook signature");
106
+ }
107
+ const text = typeof input.payload === "string" ? input.payload : new TextDecoder().decode(input.payload);
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(text);
111
+ } catch {
112
+ throw new WebhookSignatureError("Webhook payload is not valid JSON");
113
+ }
114
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
115
+ throw new WebhookSignatureError("Webhook payload is not a JSON object");
116
+ }
117
+ if (parsed.object !== "event") {
118
+ throw new WebhookSignatureError("Webhook payload is not an event");
119
+ }
120
+ return parsed;
41
121
  }
42
122
  // Annotate the CommonJS export names for ESM import in node:
43
123
  0 && (module.exports = {
124
+ DEFAULT_WEBHOOK_TOLERANCE_SECONDS,
125
+ WEBHOOK_SIGNATURE_HEADER,
126
+ WebhookSignatureError,
127
+ constructEvent,
44
128
  verifyWebhookSignature
45
129
  });
@@ -1,23 +1,42 @@
1
- /**
2
- * Server-only webhook helpers. Import from `@replicer/sdk/webhooks`; the main entry stays free of
3
- * `node:` imports so it bundles for edge runtimes and browsers.
4
- */
1
+ import { ar as WebhookEvent } from './types-DXQsrvOU.cjs';
2
+ export { av as AnyWebhookEvent, bd as WebhookEventDataMap, bf as WebhookEventType } from './types-DXQsrvOU.cjs';
3
+
4
+ /** Name of the signature header (HTTP header names are case-insensitive). */
5
+ declare const WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
6
+ /** Default accepted distance, in seconds, between the signed timestamp and now. */
7
+ declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
5
8
  interface VerifyWebhookSignatureInput {
6
- /** The exact request body as received (do not re-serialize parsed JSON). */
9
+ /** The raw request body exactly as received (never re-serialized JSON). */
7
10
  payload: string | Uint8Array;
8
- /** Value of the `X-Replicer-Signature` header: `sha256=<hex>` (a bare hex digest is also accepted). */
9
- signature: string | null | undefined;
10
- /** The endpoint signing secret. */
11
- secret: string;
11
+ /** Value of the `Replicer-Signature` header: `t=<unix>,v1=<hex>[,v1=<hex>]`. */
12
+ header: string | null | undefined;
13
+ /** The endpoint signing secret (`whsec_…`). One of `secret` / `secrets` is required. */
14
+ secret?: string;
15
+ /** Several secrets, any of which may match (for example the new and the old one during a rotation). */
16
+ secrets?: string[];
17
+ /** Maximum distance between the signed timestamp `t` and now (default 300). */
18
+ toleranceSeconds?: number;
19
+ /** Current time (default `new Date()`), for tests. */
20
+ now?: Date;
12
21
  }
22
+ /** Thrown by `constructEvent` for a missing, invalid or expired signature, or a body that is not a JSON event. */
23
+ declare class WebhookSignatureError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * Verify the `Replicer-Signature` header of a webhook delivery: true when any `v1` signature
28
+ * matches any of the given secrets (constant-time compare) and the signed timestamp is within
29
+ * `toleranceSeconds` of now. Returns `false`, never throws, for a missing or malformed header, a
30
+ * stale timestamp, no secret or no match. Throws `TypeError` only for a programmer error: passing
31
+ * the 0.1.0 `signature` field (renamed to `header` in 0.2.0) without `header`.
32
+ */
33
+ declare function verifyWebhookSignature(input: VerifyWebhookSignatureInput): boolean;
13
34
  /**
14
- * Verify the `X-Replicer-Signature` header of a webhook delivery (HMAC-SHA256 over the raw body,
15
- * compared in constant time). Returns `false`, never throws, for a missing, malformed or
16
- * wrong-length signature.
17
- *
18
- * The `X-Replicer-Timestamp` header is NOT covered by the signature: for replay protection,
19
- * de-duplicate on `X-Replicer-Delivery-Id` / the event id instead of relying on the timestamp.
35
+ * Verify the signature, then parse the body. Throws `WebhookSignatureError` when the signature is
36
+ * not valid (see `verifyWebhookSignature`) or the body is not a JSON object with `object: "event"`
37
+ * (a signed API tool call is signed the same way and must not pass as an event), and `TypeError`
38
+ * when given the 0.1.0 `signature` field instead of `header`.
20
39
  */
21
- declare function verifyWebhookSignature({ payload, signature, secret }: VerifyWebhookSignatureInput): boolean;
40
+ declare function constructEvent<T = Record<string, unknown>>(input: VerifyWebhookSignatureInput): WebhookEvent<T>;
22
41
 
23
- export { type VerifyWebhookSignatureInput, verifyWebhookSignature };
42
+ export { DEFAULT_WEBHOOK_TOLERANCE_SECONDS, type VerifyWebhookSignatureInput, WEBHOOK_SIGNATURE_HEADER, WebhookEvent, WebhookSignatureError, constructEvent, verifyWebhookSignature };
@@ -1,23 +1,42 @@
1
- /**
2
- * Server-only webhook helpers. Import from `@replicer/sdk/webhooks`; the main entry stays free of
3
- * `node:` imports so it bundles for edge runtimes and browsers.
4
- */
1
+ import { ar as WebhookEvent } from './types-DXQsrvOU.js';
2
+ export { av as AnyWebhookEvent, bd as WebhookEventDataMap, bf as WebhookEventType } from './types-DXQsrvOU.js';
3
+
4
+ /** Name of the signature header (HTTP header names are case-insensitive). */
5
+ declare const WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
6
+ /** Default accepted distance, in seconds, between the signed timestamp and now. */
7
+ declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
5
8
  interface VerifyWebhookSignatureInput {
6
- /** The exact request body as received (do not re-serialize parsed JSON). */
9
+ /** The raw request body exactly as received (never re-serialized JSON). */
7
10
  payload: string | Uint8Array;
8
- /** Value of the `X-Replicer-Signature` header: `sha256=<hex>` (a bare hex digest is also accepted). */
9
- signature: string | null | undefined;
10
- /** The endpoint signing secret. */
11
- secret: string;
11
+ /** Value of the `Replicer-Signature` header: `t=<unix>,v1=<hex>[,v1=<hex>]`. */
12
+ header: string | null | undefined;
13
+ /** The endpoint signing secret (`whsec_…`). One of `secret` / `secrets` is required. */
14
+ secret?: string;
15
+ /** Several secrets, any of which may match (for example the new and the old one during a rotation). */
16
+ secrets?: string[];
17
+ /** Maximum distance between the signed timestamp `t` and now (default 300). */
18
+ toleranceSeconds?: number;
19
+ /** Current time (default `new Date()`), for tests. */
20
+ now?: Date;
12
21
  }
22
+ /** Thrown by `constructEvent` for a missing, invalid or expired signature, or a body that is not a JSON event. */
23
+ declare class WebhookSignatureError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /**
27
+ * Verify the `Replicer-Signature` header of a webhook delivery: true when any `v1` signature
28
+ * matches any of the given secrets (constant-time compare) and the signed timestamp is within
29
+ * `toleranceSeconds` of now. Returns `false`, never throws, for a missing or malformed header, a
30
+ * stale timestamp, no secret or no match. Throws `TypeError` only for a programmer error: passing
31
+ * the 0.1.0 `signature` field (renamed to `header` in 0.2.0) without `header`.
32
+ */
33
+ declare function verifyWebhookSignature(input: VerifyWebhookSignatureInput): boolean;
13
34
  /**
14
- * Verify the `X-Replicer-Signature` header of a webhook delivery (HMAC-SHA256 over the raw body,
15
- * compared in constant time). Returns `false`, never throws, for a missing, malformed or
16
- * wrong-length signature.
17
- *
18
- * The `X-Replicer-Timestamp` header is NOT covered by the signature: for replay protection,
19
- * de-duplicate on `X-Replicer-Delivery-Id` / the event id instead of relying on the timestamp.
35
+ * Verify the signature, then parse the body. Throws `WebhookSignatureError` when the signature is
36
+ * not valid (see `verifyWebhookSignature`) or the body is not a JSON object with `object: "event"`
37
+ * (a signed API tool call is signed the same way and must not pass as an event), and `TypeError`
38
+ * when given the 0.1.0 `signature` field instead of `header`.
20
39
  */
21
- declare function verifyWebhookSignature({ payload, signature, secret }: VerifyWebhookSignatureInput): boolean;
40
+ declare function constructEvent<T = Record<string, unknown>>(input: VerifyWebhookSignatureInput): WebhookEvent<T>;
22
41
 
23
- export { type VerifyWebhookSignatureInput, verifyWebhookSignature };
42
+ export { DEFAULT_WEBHOOK_TOLERANCE_SECONDS, type VerifyWebhookSignatureInput, WEBHOOK_SIGNATURE_HEADER, WebhookEvent, WebhookSignatureError, constructEvent, verifyWebhookSignature };
package/dist/webhooks.js CHANGED
@@ -1,20 +1,55 @@
1
+ import {
2
+ DEFAULT_TOLERANCE_SECONDS,
3
+ SIGNATURE_HEADER,
4
+ verifySignatureHeader
5
+ } from "./chunk-CIXVIMX2.js";
6
+
1
7
  // src/webhooks.ts
2
- import { createHmac, timingSafeEqual } from "crypto";
3
- var SIGNATURE_PREFIX = "sha256=";
4
- var HEX_SHA256 = /^[0-9a-f]{64}$/;
5
- function verifyWebhookSignature({ payload, signature, secret }) {
6
- if (typeof signature !== "string" || !secret) return false;
7
- let hex = signature.trim();
8
- if (hex.slice(0, SIGNATURE_PREFIX.length).toLowerCase() === SIGNATURE_PREFIX) {
9
- hex = hex.slice(SIGNATURE_PREFIX.length);
8
+ var WEBHOOK_SIGNATURE_HEADER = SIGNATURE_HEADER;
9
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
10
+ var WebhookSignatureError = class extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "WebhookSignatureError";
10
14
  }
11
- hex = hex.toLowerCase();
12
- if (!HEX_SHA256.test(hex)) return false;
13
- const expected = createHmac("sha256", secret).update(payload).digest();
14
- const received = Buffer.from(hex, "hex");
15
- if (received.length !== expected.length) return false;
16
- return timingSafeEqual(expected, received);
15
+ };
16
+ function assertNoRenamedSignature(input) {
17
+ if (!input || typeof input !== "object") return;
18
+ const fields = input;
19
+ if (fields.header === void 0 && "signature" in fields) {
20
+ throw new TypeError(
21
+ `'signature' was renamed to 'header' in @replicer/sdk 0.2.0: pass the ${WEBHOOK_SIGNATURE_HEADER} header value as 'header'`
22
+ );
23
+ }
24
+ }
25
+ function verifyWebhookSignature(input) {
26
+ assertNoRenamedSignature(input);
27
+ return verifySignatureHeader(input);
28
+ }
29
+ function constructEvent(input) {
30
+ assertNoRenamedSignature(input);
31
+ if (!verifyWebhookSignature(input)) {
32
+ throw new WebhookSignatureError("Invalid webhook signature");
33
+ }
34
+ const text = typeof input.payload === "string" ? input.payload : new TextDecoder().decode(input.payload);
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(text);
38
+ } catch {
39
+ throw new WebhookSignatureError("Webhook payload is not valid JSON");
40
+ }
41
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
42
+ throw new WebhookSignatureError("Webhook payload is not a JSON object");
43
+ }
44
+ if (parsed.object !== "event") {
45
+ throw new WebhookSignatureError("Webhook payload is not an event");
46
+ }
47
+ return parsed;
17
48
  }
18
49
  export {
50
+ DEFAULT_WEBHOOK_TOLERANCE_SECONDS,
51
+ WEBHOOK_SIGNATURE_HEADER,
52
+ WebhookSignatureError,
53
+ constructEvent,
19
54
  verifyWebhookSignature
20
55
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@replicer/sdk",
3
- "version": "0.1.1",
4
- "description": "Typed JavaScript/TypeScript client for the Replicer API: calls, campaigns, knowledge bases, contacts, calendar, messages and TTS.",
3
+ "version": "0.3.0",
4
+ "description": "Typed JavaScript/TypeScript client for the Replicer API: calls, campaigns, knowledge bases, contacts, calendar, messages, TTS and webhooks.",
5
5
  "keywords": [
6
6
  "replicer",
7
7
  "sdk",
@@ -10,6 +10,7 @@
10
10
  "calls",
11
11
  "campaigns",
12
12
  "knowledge-base",
13
+ "webhooks",
13
14
  "api"
14
15
  ],
15
16
  "license": "MIT",
@@ -40,12 +41,25 @@
40
41
  "default": "./dist/webhooks.cjs"
41
42
  }
42
43
  },
44
+ "./tools": {
45
+ "import": {
46
+ "types": "./dist/tools.d.ts",
47
+ "default": "./dist/tools.js"
48
+ },
49
+ "require": {
50
+ "types": "./dist/tools.d.cts",
51
+ "default": "./dist/tools.cjs"
52
+ }
53
+ },
43
54
  "./package.json": "./package.json"
44
55
  },
45
56
  "typesVersions": {
46
57
  "*": {
47
58
  "webhooks": [
48
59
  "./dist/webhooks.d.ts"
60
+ ],
61
+ "tools": [
62
+ "./dist/tools.d.ts"
49
63
  ]
50
64
  }
51
65
  },