@cstar.help/js 0.13.0 → 0.15.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.
@@ -20,14 +20,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/webhook/node.ts
21
21
  var node_exports = {};
22
22
  __export(node_exports, {
23
+ DEFAULT_TOLERANCE_SECONDS: () => DEFAULT_TOLERANCE_SECONDS,
23
24
  WebhookSignatureVerificationError: () => WebhookSignatureVerificationError,
24
25
  constructEvent: () => constructEvent,
26
+ signPayloadStripe: () => signPayloadStripe,
25
27
  verifySignature: () => verifySignature
26
28
  });
27
29
  module.exports = __toCommonJS(node_exports);
28
30
  var import_node_crypto = require("crypto");
29
31
 
30
32
  // src/webhook/index.ts
33
+ var DEFAULT_TOLERANCE_SECONDS = 300;
31
34
  var WebhookSignatureVerificationError = class extends Error {
32
35
  constructor(message) {
33
36
  super(message);
@@ -36,22 +39,67 @@ var WebhookSignatureVerificationError = class extends Error {
36
39
  };
37
40
 
38
41
  // src/webhook/node.ts
39
- function constructEvent(rawBody, signature, secret) {
40
- if (!verifySignature(rawBody, signature, secret)) {
42
+ function parseStripeHeader(header) {
43
+ if (!header || header.startsWith("sha256=")) return null;
44
+ let timestamp = null;
45
+ const v1 = [];
46
+ for (const part of header.split(",")) {
47
+ const eq = part.indexOf("=");
48
+ if (eq === -1) continue;
49
+ const key = part.slice(0, eq).trim();
50
+ const value = part.slice(eq + 1).trim();
51
+ if (key === "t") {
52
+ const parsed = Number.parseInt(value, 10);
53
+ if (Number.isFinite(parsed)) timestamp = parsed;
54
+ } else if (key === "v1") {
55
+ v1.push(value);
56
+ }
57
+ }
58
+ if (timestamp === null || v1.length === 0) return null;
59
+ return { timestamp, v1 };
60
+ }
61
+ function constantTimeEqualHex(a, b) {
62
+ if (a.length !== b.length) return false;
63
+ try {
64
+ return (0, import_node_crypto.timingSafeEqual)(Buffer.from(a), Buffer.from(b));
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+ function signPayloadStripe(rawBody, secret) {
70
+ const ts = Math.floor(Date.now() / 1e3);
71
+ const sig = (0, import_node_crypto.createHmac)("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
72
+ return `t=${ts},v1=${sig}`;
73
+ }
74
+ function constructEvent(rawBody, signature, secret, options) {
75
+ if (!verifySignature(rawBody, signature, secret, options)) {
41
76
  throw new WebhookSignatureVerificationError(
42
77
  "Webhook signature verification failed. Ensure you are using the raw request body and the correct endpoint secret."
43
78
  );
44
79
  }
45
80
  return JSON.parse(rawBody);
46
81
  }
47
- function verifySignature(rawBody, signature, secret) {
82
+ function verifySignature(rawBody, signature, secret, options) {
83
+ if (typeof signature !== "string" || signature.length === 0) return false;
84
+ const stripe = parseStripeHeader(signature);
85
+ if (stripe) {
86
+ const tolerance = options?.tolerance ?? DEFAULT_TOLERANCE_SECONDS;
87
+ const now = Math.floor(Date.now() / 1e3);
88
+ if (Math.abs(now - stripe.timestamp) > tolerance) return false;
89
+ const expected2 = (0, import_node_crypto.createHmac)("sha256", secret).update(`${stripe.timestamp}.${rawBody}`).digest("hex");
90
+ for (const candidate of stripe.v1) {
91
+ if (constantTimeEqualHex(candidate, expected2)) return true;
92
+ }
93
+ return false;
94
+ }
48
95
  const expected = "sha256=" + (0, import_node_crypto.createHmac)("sha256", secret).update(rawBody).digest("hex");
49
- if (signature.length !== expected.length) return false;
50
- return (0, import_node_crypto.timingSafeEqual)(Buffer.from(signature), Buffer.from(expected));
96
+ return constantTimeEqualHex(signature, expected);
51
97
  }
52
98
  // Annotate the CommonJS export names for ESM import in node:
53
99
  0 && (module.exports = {
100
+ DEFAULT_TOLERANCE_SECONDS,
54
101
  WebhookSignatureVerificationError,
55
102
  constructEvent,
103
+ signPayloadStripe,
56
104
  verifySignature
57
105
  });
@@ -412,11 +412,28 @@ interface WebhookEvent<T extends WebhookEventType = WebhookEventType> {
412
412
  data: WebhookEventDataMap[T];
413
413
  }
414
414
 
415
+ /** Default replay window for Stripe-style signatures: 5 minutes (300s). */
416
+ declare const DEFAULT_TOLERANCE_SECONDS = 300;
417
+ /** Options for signature verification — accepted by both verify and construct calls. */
418
+ interface VerifyOptions {
419
+ /**
420
+ * Maximum age (in seconds) of a Stripe-style timestamp before the signature
421
+ * is rejected as expired. Defaults to {@link DEFAULT_TOLERANCE_SECONDS}.
422
+ * Ignored for legacy `sha256=<hex>` signatures (which carry no timestamp).
423
+ */
424
+ tolerance?: number;
425
+ }
415
426
  /** Thrown when webhook signature verification fails. */
416
427
  declare class WebhookSignatureVerificationError extends Error {
417
428
  constructor(message: string);
418
429
  }
419
430
 
431
+ /**
432
+ * Sign a payload in Stripe-style format `t=<unix>,v1=<hex>` (Node-only,
433
+ * synchronous). Used by the cStar server-side webhook dispatcher and
434
+ * `cstar listen --forward-to`. The HMAC is computed over `${ts}.${rawBody}`.
435
+ */
436
+ declare function signPayloadStripe(rawBody: string, secret: string): string;
420
437
  /**
421
438
  * Verify a webhook signature and parse the event (synchronous, Node.js only).
422
439
  *
@@ -427,14 +444,20 @@ declare class WebhookSignatureVerificationError extends Error {
427
444
  * @param rawBody - Raw request body as a string (NOT parsed JSON)
428
445
  * @param signature - Value of the `X-Signature` header
429
446
  * @param secret - Your webhook endpoint's secret (`whsec_*`)
447
+ * @param options - Optional verifier options (e.g. replay tolerance)
430
448
  * @returns Parsed and verified webhook event
431
449
  * @throws {WebhookSignatureVerificationError} If verification fails
432
450
  */
433
- declare function constructEvent(rawBody: string, signature: string, secret: string): WebhookEvent;
451
+ declare function constructEvent(rawBody: string, signature: string, secret: string, options?: VerifyOptions): WebhookEvent;
434
452
  /**
435
453
  * Verify an HMAC-SHA256 signature (synchronous, Node.js only).
436
- * Uses timing-safe comparison to prevent timing attacks.
454
+ *
455
+ * Accepts both the canonical Stripe-style format `t=<unix>,v1=<hex>` (signed
456
+ * over `${ts}.${rawBody}`, with replay-window enforcement) and the legacy
457
+ * `sha256=<hex>` format (signed over `rawBody`, no timestamp). Use
458
+ * `options.tolerance` to override the default 300s replay window. Uses
459
+ * timing-safe comparison.
437
460
  */
438
- declare function verifySignature(rawBody: string, signature: string, secret: string): boolean;
461
+ declare function verifySignature(rawBody: string, signature: string, secret: string, options?: VerifyOptions): boolean;
439
462
 
440
- export { type WebhookEvent, WebhookSignatureVerificationError, constructEvent, verifySignature };
463
+ export { DEFAULT_TOLERANCE_SECONDS, type VerifyOptions, type WebhookEvent, WebhookSignatureVerificationError, constructEvent, signPayloadStripe, verifySignature };
@@ -412,11 +412,28 @@ interface WebhookEvent<T extends WebhookEventType = WebhookEventType> {
412
412
  data: WebhookEventDataMap[T];
413
413
  }
414
414
 
415
+ /** Default replay window for Stripe-style signatures: 5 minutes (300s). */
416
+ declare const DEFAULT_TOLERANCE_SECONDS = 300;
417
+ /** Options for signature verification — accepted by both verify and construct calls. */
418
+ interface VerifyOptions {
419
+ /**
420
+ * Maximum age (in seconds) of a Stripe-style timestamp before the signature
421
+ * is rejected as expired. Defaults to {@link DEFAULT_TOLERANCE_SECONDS}.
422
+ * Ignored for legacy `sha256=<hex>` signatures (which carry no timestamp).
423
+ */
424
+ tolerance?: number;
425
+ }
415
426
  /** Thrown when webhook signature verification fails. */
416
427
  declare class WebhookSignatureVerificationError extends Error {
417
428
  constructor(message: string);
418
429
  }
419
430
 
431
+ /**
432
+ * Sign a payload in Stripe-style format `t=<unix>,v1=<hex>` (Node-only,
433
+ * synchronous). Used by the cStar server-side webhook dispatcher and
434
+ * `cstar listen --forward-to`. The HMAC is computed over `${ts}.${rawBody}`.
435
+ */
436
+ declare function signPayloadStripe(rawBody: string, secret: string): string;
420
437
  /**
421
438
  * Verify a webhook signature and parse the event (synchronous, Node.js only).
422
439
  *
@@ -427,14 +444,20 @@ declare class WebhookSignatureVerificationError extends Error {
427
444
  * @param rawBody - Raw request body as a string (NOT parsed JSON)
428
445
  * @param signature - Value of the `X-Signature` header
429
446
  * @param secret - Your webhook endpoint's secret (`whsec_*`)
447
+ * @param options - Optional verifier options (e.g. replay tolerance)
430
448
  * @returns Parsed and verified webhook event
431
449
  * @throws {WebhookSignatureVerificationError} If verification fails
432
450
  */
433
- declare function constructEvent(rawBody: string, signature: string, secret: string): WebhookEvent;
451
+ declare function constructEvent(rawBody: string, signature: string, secret: string, options?: VerifyOptions): WebhookEvent;
434
452
  /**
435
453
  * Verify an HMAC-SHA256 signature (synchronous, Node.js only).
436
- * Uses timing-safe comparison to prevent timing attacks.
454
+ *
455
+ * Accepts both the canonical Stripe-style format `t=<unix>,v1=<hex>` (signed
456
+ * over `${ts}.${rawBody}`, with replay-window enforcement) and the legacy
457
+ * `sha256=<hex>` format (signed over `rawBody`, no timestamp). Use
458
+ * `options.tolerance` to override the default 300s replay window. Uses
459
+ * timing-safe comparison.
437
460
  */
438
- declare function verifySignature(rawBody: string, signature: string, secret: string): boolean;
461
+ declare function verifySignature(rawBody: string, signature: string, secret: string, options?: VerifyOptions): boolean;
439
462
 
440
- export { type WebhookEvent, WebhookSignatureVerificationError, constructEvent, verifySignature };
463
+ export { DEFAULT_TOLERANCE_SECONDS, type VerifyOptions, type WebhookEvent, WebhookSignatureVerificationError, constructEvent, signPayloadStripe, verifySignature };
@@ -2,6 +2,7 @@
2
2
  import { createHmac, timingSafeEqual } from "crypto";
3
3
 
4
4
  // src/webhook/index.ts
5
+ var DEFAULT_TOLERANCE_SECONDS = 300;
5
6
  var WebhookSignatureVerificationError = class extends Error {
6
7
  constructor(message) {
7
8
  super(message);
@@ -10,21 +11,66 @@ var WebhookSignatureVerificationError = class extends Error {
10
11
  };
11
12
 
12
13
  // src/webhook/node.ts
13
- function constructEvent(rawBody, signature, secret) {
14
- if (!verifySignature(rawBody, signature, secret)) {
14
+ function parseStripeHeader(header) {
15
+ if (!header || header.startsWith("sha256=")) return null;
16
+ let timestamp = null;
17
+ const v1 = [];
18
+ for (const part of header.split(",")) {
19
+ const eq = part.indexOf("=");
20
+ if (eq === -1) continue;
21
+ const key = part.slice(0, eq).trim();
22
+ const value = part.slice(eq + 1).trim();
23
+ if (key === "t") {
24
+ const parsed = Number.parseInt(value, 10);
25
+ if (Number.isFinite(parsed)) timestamp = parsed;
26
+ } else if (key === "v1") {
27
+ v1.push(value);
28
+ }
29
+ }
30
+ if (timestamp === null || v1.length === 0) return null;
31
+ return { timestamp, v1 };
32
+ }
33
+ function constantTimeEqualHex(a, b) {
34
+ if (a.length !== b.length) return false;
35
+ try {
36
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+ function signPayloadStripe(rawBody, secret) {
42
+ const ts = Math.floor(Date.now() / 1e3);
43
+ const sig = createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
44
+ return `t=${ts},v1=${sig}`;
45
+ }
46
+ function constructEvent(rawBody, signature, secret, options) {
47
+ if (!verifySignature(rawBody, signature, secret, options)) {
15
48
  throw new WebhookSignatureVerificationError(
16
49
  "Webhook signature verification failed. Ensure you are using the raw request body and the correct endpoint secret."
17
50
  );
18
51
  }
19
52
  return JSON.parse(rawBody);
20
53
  }
21
- function verifySignature(rawBody, signature, secret) {
54
+ function verifySignature(rawBody, signature, secret, options) {
55
+ if (typeof signature !== "string" || signature.length === 0) return false;
56
+ const stripe = parseStripeHeader(signature);
57
+ if (stripe) {
58
+ const tolerance = options?.tolerance ?? DEFAULT_TOLERANCE_SECONDS;
59
+ const now = Math.floor(Date.now() / 1e3);
60
+ if (Math.abs(now - stripe.timestamp) > tolerance) return false;
61
+ const expected2 = createHmac("sha256", secret).update(`${stripe.timestamp}.${rawBody}`).digest("hex");
62
+ for (const candidate of stripe.v1) {
63
+ if (constantTimeEqualHex(candidate, expected2)) return true;
64
+ }
65
+ return false;
66
+ }
22
67
  const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
23
- if (signature.length !== expected.length) return false;
24
- return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
68
+ return constantTimeEqualHex(signature, expected);
25
69
  }
26
70
  export {
71
+ DEFAULT_TOLERANCE_SECONDS,
27
72
  WebhookSignatureVerificationError,
28
73
  constructEvent,
74
+ signPayloadStripe,
29
75
  verifySignature
30
76
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cstar.help/js",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Official TypeScript SDK for the cStar customer support platform",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",