@zyphe-sdk/core 0.1.5 → 0.1.7

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,22 @@
1
+
2
+ 
3
+ > @zyphe-sdk/core@0.1.7 build /Users/mtumiati/dev/zyphe/zyphe-sdk/packages/core
4
+ > tsup
5
+
6
+ CLI Building entry: src/index.ts
7
+ CLI Using tsconfig: tsconfig.json
8
+ CLI tsup v8.5.0
9
+ CLI Using tsup config: /Users/mtumiati/dev/zyphe/zyphe-sdk/packages/core/tsup.config.ts
10
+ CLI Target: es2023
11
+ ESM Build start
12
+ CJS Build start
13
+ ESM dist/index.js 4.28 KB
14
+ ESM dist/index.js.map 9.36 KB
15
+ ESM ⚡️ Build success in 12ms
16
+ CJS dist/index.cjs 6.08 KB
17
+ CJS dist/index.cjs.map 9.63 KB
18
+ CJS ⚡️ Build success in 13ms
19
+ DTS Build start
20
+ DTS ⚡️ Build success in 609ms
21
+ DTS dist/index.d.ts 61.70 KB
22
+ DTS dist/index.d.cts 61.70 KB
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Zyphe SDK – Core Webhook Signature Verification
1
+ # Zyphe SDK – Core
2
2
 
3
- This is the core SDK package for Zyphe. It contains utilities to interact with Zyphe platform.
3
+ This is the core SDK package for Zyphe. It contains utilities to interact with the Zyphe platform, including webhook signature verification and verification session management.
4
4
 
5
5
  ## Installing package
6
6
 
@@ -12,14 +12,13 @@ pnpm install @zyphe-sdk/core
12
12
 
13
13
  Then import and use the package in your project as described in the Usage section.
14
14
 
15
- ## Usage: Verifying a Webhook Signature
15
+ ---
16
16
 
17
- ### Webhook Signature Verification
18
- This package provides the core webhook signature verification logic for Zyphe. It enables secure verification of incoming webhook requests in both Node.js and browser environments using HMAC-SHA256 signatures.
17
+ ## 1. Webhook Signature Verification
19
18
 
20
- The main function exported by this package is `verifyWebhookSignature`, which allows you to securely verify incoming webhook requests.
19
+ This package provides the core webhook signature verification logic for Zyphe. It enables secure verification of incoming webhook requests in both Node.js and browser environments using HMAC-SHA256 signatures.
21
20
 
22
- #### Example
21
+ ### Basic Usage
23
22
 
24
23
  ```ts
25
24
  import { verifyWebhookSignature } from "@zyphe-sdk/core";
@@ -41,8 +40,69 @@ if (isValid) {
41
40
  - `signatureHeader`: The signature header string, e.g. `t=1234567890,v0=abcdef...`.
42
41
  - Returns: A Promise that resolves to `true` if the signature is valid, or `false` otherwise.
43
42
 
44
- This function works in both Node.js and modern browsers. It automatically selects the appropriate implementation for the environment.
43
+ #### Advanced Utilities
44
+ - `parseSignatureHeader(signatureHeader)` – Parse the signature header into timestamp and signature.
45
+ - `hexToBytes(hex)` / `bufferToHex(buffer)` – Convert between hex and bytes.
46
+ - `timingSafeEqual(a, b)` – Constant-time string comparison.
47
+ - Error codes/messages for robust error handling.
48
+
49
+ ---
50
+
51
+ ## 2. Verification Session Management
52
+
53
+ You can programmatically create verification sessions and construct user-facing URLs for onboarding flows.
54
+
55
+ ### Create a Verification Session
56
+ ```ts
57
+ import { createVerificationSession } from "@zyphe-sdk/core";
58
+
59
+ const response = await createVerificationSession(
60
+ "user@example.com", // email
61
+ "<flowId>", // flowId
62
+ "<flowStepId>", // flowStepId
63
+ false, // isSandbox
64
+ {
65
+ apiKey: "<your-api-key>",
66
+ environment: "staging", // or "production", "local"
67
+ }
68
+ );
69
+ ```
70
+
71
+ ### Construct a Verification Session URL
72
+ ```ts
73
+ import { constructVerificationSessionUrl } from "@zyphe-sdk/core";
74
+
75
+ const url = constructVerificationSessionUrl({
76
+ flowParams: {
77
+ flowId: "...",
78
+ flowStepId: "...",
79
+ email: "user@example.com",
80
+ product: "kyc",
81
+ isSandbox: false,
82
+ },
83
+ verificationSession: response.data, // from createVerificationSession
84
+ opts: {
85
+ apiKey: "<your-api-key>",
86
+ environment: "staging",
87
+ handoffBaseUrl: "https://your-app.com",
88
+ primaryColor: "#000000",
89
+ secondaryColor: "#ffffff",
90
+ isFullscreen: true,
91
+ },
92
+ });
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 3. Types and Configuration
98
+
99
+ - `InitializeZypheFlowParams`, `SDKOptions`, `SdkCreateVerificationRequestResponse` – for type-safe integration.
100
+ - `Environments`, `EnvironmentConfigs`, `API_KEY_HEADER` – for environment and API configuration.
101
+
102
+ ---
45
103
 
104
+ ## Resources
105
+ - See the dedicated middleware packages for Express, Fastify, Hono, and NestJS for webhook signature verification in those frameworks.
46
106
 
47
107
  ---
48
108
  Made with ❤️ by Zyphe Inc
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,35 +17,134 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ API_KEY_HEADER: () => API_KEY_HEADER,
34
+ EnvironmentConfigs: () => EnvironmentConfigs,
35
+ Environments: () => Environments,
23
36
  WebhookSignatureErrorCodes: () => WebhookSignatureErrorCodes,
24
37
  WebhookSignatureErrorMessages: () => WebhookSignatureErrorMessages,
25
38
  bufferToHex: () => bufferToHex,
39
+ constructVerificationSessionUrl: () => constructVerificationSessionUrl,
40
+ createVerificationSession: () => createVerificationSession,
26
41
  hexToBytes: () => hexToBytes,
27
42
  parseSignatureHeader: () => parseSignatureHeader,
28
- timingSafeEqual: () => timingSafeEqual,
29
- verifyWebhookSignature: () => verifyWebhookSignature,
30
- verifyWebhookSignatureHeaderBrowser: () => verifyWebhookSignatureHeader,
31
- verifyWebhookSignatureHeaderNode: () => verifyWebhookSignatureHeader2
43
+ timingSafeEqual: () => timingSafeEqual
32
44
  });
33
- module.exports = __toCommonJS(src_exports);
45
+ module.exports = __toCommonJS(index_exports);
34
46
 
35
- // src/webhook/common.ts
47
+ // src/constants.ts
48
+ var Environments = {
49
+ LOCAL: "local",
50
+ STAGING: "staging",
51
+ PRODUCTION: "production"
52
+ };
53
+ var EnvironmentConfigs = {
54
+ [Environments.LOCAL]: {
55
+ appUrl: "http://localhost:5173",
56
+ apiUrl: "http://localhost:3000"
57
+ },
58
+ [Environments.STAGING]: {
59
+ appUrl: "https://app-dev.zyphe.com",
60
+ apiUrl: "https://api-dev.zyphe.com"
61
+ },
62
+ [Environments.PRODUCTION]: {
63
+ appUrl: "https://verify.zyphe.com",
64
+ apiUrl: "https://api.zyphe.com"
65
+ }
66
+ };
67
+ var API_KEY_HEADER = "x-api-key";
68
+
69
+ // src/client.ts
70
+ var import_openapi_fetch = __toESM(require("openapi-fetch"), 1);
71
+ var zypheApiClient = (opts) => {
72
+ return (0, import_openapi_fetch.default)({
73
+ baseUrl: EnvironmentConfigs[opts.environment].apiUrl
74
+ });
75
+ };
76
+
77
+ // src/verification-session.ts
78
+ function createVerificationSession(email, flowId, flowStepId, isSandbox, opts) {
79
+ const client = zypheApiClient(opts);
80
+ return client.POST("/sdk/flow/{flow_id}/vr/create", {
81
+ body: { email, flowStepId },
82
+ headers: {
83
+ [API_KEY_HEADER]: opts.apiKey
84
+ },
85
+ params: {
86
+ path: {
87
+ flow_id: flowId
88
+ },
89
+ query: {
90
+ sandbox: isSandbox
91
+ }
92
+ }
93
+ });
94
+ }
95
+ function getFlowUrlOrigin(environment) {
96
+ switch (environment) {
97
+ case Environments.LOCAL:
98
+ return EnvironmentConfigs[Environments.LOCAL].appUrl;
99
+ case Environments.STAGING:
100
+ return EnvironmentConfigs[Environments.STAGING].appUrl;
101
+ case Environments.PRODUCTION:
102
+ return EnvironmentConfigs[Environments.PRODUCTION].appUrl;
103
+ default:
104
+ throw new Error(`Invalid environment: ${environment}`);
105
+ }
106
+ }
107
+ function constructVerificationSessionUrl({
108
+ flowParams,
109
+ verificationSession,
110
+ opts
111
+ }) {
112
+ const origin = getFlowUrlOrigin(opts.environment);
113
+ const { isSandbox, product } = flowParams;
114
+ const { handoffBaseUrl, primaryColor, secondaryColor, isFullscreen } = opts;
115
+ if (!verificationSession) {
116
+ throw new Error("Failed to create verification session");
117
+ }
118
+ let baseUrl = `${origin}${isSandbox ? "/sandbox" : ""}/flow/${verificationSession.flowSlug}/${product}/${verificationSession.flowStepSlug}?zypheVr=${encodeURIComponent(verificationSession.verificationRequest.id)}&zypheEmail=${encodeURIComponent(verificationSession.email)}&zypheToken=${encodeURIComponent(verificationSession.zypheToken)}`;
119
+ if (handoffBaseUrl) {
120
+ baseUrl += `&zypheHandoffBaseUrl=${encodeURIComponent(handoffBaseUrl)}`;
121
+ }
122
+ if (primaryColor) {
123
+ baseUrl += `&zyphePrimaryColor=${encodeURIComponent(primaryColor)}`;
124
+ }
125
+ if (secondaryColor) {
126
+ baseUrl += `&zypheSecondaryColor=${encodeURIComponent(secondaryColor)}`;
127
+ }
128
+ if (isFullscreen) {
129
+ baseUrl += `&zypheFullscreen=${encodeURIComponent(isFullscreen)}`;
130
+ }
131
+ return baseUrl;
132
+ }
133
+
134
+ // src/webhook.ts
36
135
  function parseSignatureHeader(signatureHeader) {
37
136
  const match = signatureHeader.match(/^t=(\d+),v0=([a-fA-F0-9]+)$/);
38
137
  if (!match) {
39
138
  throw new Error("Invalid signature header format");
40
139
  }
41
140
  const [, timestamp, signatureHex] = match;
141
+ if (!timestamp || !signatureHex) {
142
+ throw new Error("Invalid signature header format");
143
+ }
42
144
  return { timestamp, signatureHex };
43
145
  }
44
146
  function hexToBytes(hex) {
45
- if (hex.length % 2 !== 0)
46
- throw new Error("Invalid hex string");
147
+ if (hex.length % 2 !== 0) throw new Error("Invalid hex string");
47
148
  const bytes = new Uint8Array(hex.length / 2);
48
149
  for (let i = 0; i < hex.length; i += 2) {
49
150
  bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
@@ -54,8 +155,7 @@ function bufferToHex(buffer) {
54
155
  return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
55
156
  }
56
157
  function timingSafeEqual(a, b) {
57
- if (a.length !== b.length)
58
- return false;
158
+ if (a.length !== b.length) return false;
59
159
  let result = 0;
60
160
  for (let i = 0; i < a.length; i++) {
61
161
  result |= a.charCodeAt(i) ^ b.charCodeAt(i);
@@ -72,77 +172,4 @@ var WebhookSignatureErrorMessages = {
72
172
  [WebhookSignatureErrorCodes.INVALID_SIGNATURE_HEADER]: "Invalid signature header",
73
173
  [WebhookSignatureErrorCodes.SIGNATURE_MISMATCH]: "Signature mismatch"
74
174
  };
75
-
76
- // src/webhook/browser.ts
77
- async function verifyWebhookSignatureHeader(secretHex, rawBodyString, signatureHeader) {
78
- try {
79
- const { timestamp, signatureHex } = parseSignatureHeader(signatureHeader);
80
- const signedPayload = `${timestamp}.${rawBodyString}`;
81
- const secretKeyBytes = hexToBytes(secretHex);
82
- const cryptoKey = await window.crypto.subtle.importKey(
83
- "raw",
84
- secretKeyBytes,
85
- { name: "HMAC", hash: "SHA-256" },
86
- false,
87
- ["sign", "verify"]
88
- );
89
- const encoder = new TextEncoder();
90
- const payloadBytes = encoder.encode(signedPayload);
91
- const signatureBuffer = await window.crypto.subtle.sign(
92
- "HMAC",
93
- cryptoKey,
94
- payloadBytes
95
- );
96
- const computedSignature = bufferToHex(signatureBuffer);
97
- return timingSafeEqual(computedSignature, signatureHex);
98
- } catch (error) {
99
- console.error("Error verifying webhook signature:", error);
100
- return false;
101
- }
102
- }
103
-
104
- // src/webhook/node.ts
105
- var import_crypto = require("crypto");
106
- function verifyWebhookSignatureHeader2(secretHex, rawBodyString, signatureHeader) {
107
- try {
108
- const { timestamp, signatureHex } = parseSignatureHeader(signatureHeader);
109
- const signedPayload = `${timestamp}.${rawBodyString}`;
110
- const hmac = (0, import_crypto.createHmac)("sha256", Buffer.from(secretHex, "hex"));
111
- hmac.update(signedPayload);
112
- const computedSignature = hmac.digest("hex");
113
- return (0, import_crypto.timingSafeEqual)(
114
- Buffer.from(computedSignature, "hex"),
115
- Buffer.from(signatureHex, "hex")
116
- );
117
- } catch (error) {
118
- console.error("Error verifying webhook signature:", error);
119
- return false;
120
- }
121
- }
122
-
123
- // src/webhook/webhook.ts
124
- async function verifyWebhookSignature(secretHex, rawBodyString, signatureHeader) {
125
- var _a, _b;
126
- if (typeof window !== "undefined" && ((_a = window == null ? void 0 : window.crypto) == null ? void 0 : _a.subtle)) {
127
- return verifyWebhookSignatureHeader(secretHex, rawBodyString, signatureHeader);
128
- } else if (typeof process !== "undefined" && ((_b = process == null ? void 0 : process.versions) == null ? void 0 : _b.node)) {
129
- return verifyWebhookSignatureHeader2(secretHex, rawBodyString, signatureHeader);
130
- } else {
131
- throw new Error(
132
- "Unsupported environment: neither browser Web Crypto API nor Node.js crypto is available"
133
- );
134
- }
135
- }
136
- // Annotate the CommonJS export names for ESM import in node:
137
- 0 && (module.exports = {
138
- WebhookSignatureErrorCodes,
139
- WebhookSignatureErrorMessages,
140
- bufferToHex,
141
- hexToBytes,
142
- parseSignatureHeader,
143
- timingSafeEqual,
144
- verifyWebhookSignature,
145
- verifyWebhookSignatureHeaderBrowser,
146
- verifyWebhookSignatureHeaderNode
147
- });
148
175
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/webhook/common.ts","../src/webhook/browser.ts","../src/webhook/node.ts","../src/webhook/webhook.ts"],"sourcesContent":["// Re-export all webhook functionality\nexport * from \"./webhook/webhook\";\n\n// You can also add named exports for specific functions if you want to make them more discoverable\nexport { verifyWebhookSignature } from \"./webhook/webhook\";\nexport {\n verifyWebhookSignatureHeaderBrowser,\n verifyWebhookSignatureHeaderNode,\n} from \"./webhook/webhook\";\n\nexport {\n WebhookSignatureErrorCodes,\n WebhookSignatureErrorMessages,\n} from \"./webhook/common\";\n\nexport type { WebhookVerifierOptions } from \"./webhook/middlewares/common\";\n","export interface SignatureComponents {\n timestamp: string;\n signatureHex: string;\n}\n\n/**\n * Parses a webhook signature header of the form \"t=<timestamp>,v0=<signature>\"\n * @param signatureHeader - The header string, e.g. \"t=1234567890,v0=abcdef...\"\n * @returns The parsed timestamp and signature hex\n */\nexport function parseSignatureHeader(\n signatureHeader: string\n): SignatureComponents {\n const match = signatureHeader.match(/^t=(\\d+),v0=([a-fA-F0-9]+)$/);\n if (!match) {\n throw new Error(\"Invalid signature header format\");\n }\n const [, timestamp, signatureHex] = match;\n return { timestamp, signatureHex };\n}\n\n/**\n * Converts a hex string to a Uint8Array\n * @param hex - The hex string to convert\n * @returns The resulting Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) throw new Error(\"Invalid hex string\");\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Converts an ArrayBuffer to a hex string\n * @param buffer - The buffer to convert\n * @returns The hex string representation\n */\nexport function bufferToHex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Compares two strings in constant time to prevent timing attacks\n * @param a - First string\n * @param b - Second string\n * @returns True if strings are equal, false otherwise\n */\nexport function timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n\nexport const WebhookSignatureErrorCodes = {\n MISSING_SIGNATURE_HEADER: 1,\n INVALID_SIGNATURE_HEADER: 2,\n SIGNATURE_MISMATCH: 3,\n} as const;\n\nexport const WebhookSignatureErrorMessages = {\n [WebhookSignatureErrorCodes.MISSING_SIGNATURE_HEADER]:\n \"Missing signature header\",\n [WebhookSignatureErrorCodes.INVALID_SIGNATURE_HEADER]:\n \"Invalid signature header\",\n [WebhookSignatureErrorCodes.SIGNATURE_MISMATCH]: \"Signature mismatch\",\n} as const;\n","import {\n parseSignatureHeader,\n hexToBytes,\n bufferToHex,\n timingSafeEqual,\n} from \"./common\";\n\n/**\n * Verifies a webhook signature header using the Web Crypto API (browser).\n * @param secretHex - The hex-encoded secret key.\n * @param rawBodyString - The raw request body as a string.\n * @param signatureHeader - The header string, e.g. \"t=1234567890,v0=abcdef...\"\n * @returns Promise resolving to true if the signature is valid, false otherwise.\n */\nexport async function verifyWebhookSignatureHeader(\n secretHex: string,\n rawBodyString: string,\n signatureHeader: string\n): Promise<boolean> {\n try {\n // Parse the header\n const { timestamp, signatureHex } = parseSignatureHeader(signatureHeader);\n\n // Reconstruct the signed payload\n const signedPayload = `${timestamp}.${rawBodyString}`;\n\n // Convert hex secret to Uint8Array\n const secretKeyBytes = hexToBytes(secretHex);\n\n // Import the secret key for HMAC\n const cryptoKey = await window.crypto.subtle.importKey(\n \"raw\",\n secretKeyBytes,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"]\n );\n\n // Encode the payload as Uint8Array\n const encoder = new TextEncoder();\n const payloadBytes = encoder.encode(signedPayload);\n\n // Compute the HMAC signature\n const signatureBuffer = await window.crypto.subtle.sign(\n \"HMAC\",\n cryptoKey,\n payloadBytes\n );\n\n const computedSignature = bufferToHex(signatureBuffer);\n\n // Constant-time comparison\n return timingSafeEqual(computedSignature, signatureHex);\n } catch (error) {\n console.error(\"Error verifying webhook signature:\", error);\n return false;\n }\n}\n","import { createHmac, timingSafeEqual as cryptoTimingSafeEqual } from \"crypto\";\nimport { parseSignatureHeader } from \"./common\";\n\n/**\n * Verifies a webhook signature header using Node.js crypto.\n * @param secretHex - The hex-encoded secret key.\n * @param rawBodyString - The raw request body as a string.\n * @param signatureHeader - The header string, e.g. \"t=1234567890,v0=abcdef...\"\n * @returns True if the signature is valid, false otherwise.\n */\nexport function verifyWebhookSignatureHeader(\n secretHex: string,\n rawBodyString: string,\n signatureHeader: string\n): boolean {\n try {\n // Parse the header\n const { timestamp, signatureHex } = parseSignatureHeader(signatureHeader);\n\n // Reconstruct the signed payload\n const signedPayload = `${timestamp}.${rawBodyString}`;\n\n // Create HMAC using the secret\n const hmac = createHmac(\"sha256\", Buffer.from(secretHex, \"hex\"));\n\n // Update with the payload\n hmac.update(signedPayload);\n\n // Get the computed signature\n const computedSignature = hmac.digest(\"hex\");\n\n // Compare signatures in constant time\n return cryptoTimingSafeEqual(\n Buffer.from(computedSignature, \"hex\"),\n Buffer.from(signatureHex, \"hex\")\n );\n } catch (error) {\n console.error(\"Error verifying webhook signature:\", error);\n return false;\n }\n}\n","/// <reference lib=\"dom\" />\nimport { verifyWebhookSignatureHeader as verifyBrowser } from \"./browser\";\nimport { verifyWebhookSignatureHeader as verifyNode } from \"./node\";\n\n// Type declarations for global objects\ndeclare const window: (Window & typeof globalThis) | undefined;\ndeclare const process: NodeJS.Process | undefined;\n\n/**\n * Verifies a webhook signature header in either browser or Node.js environment.\n * @param secretHex - The hex-encoded secret key.\n * @param rawBodyString - The raw request body as a string.\n * @param signatureHeader - The header string, e.g. \"t=1234567890,v0=abcdef...\"\n * @returns Promise resolving to true if the signature is valid, false otherwise.\n */\nexport async function verifyWebhookSignature(\n secretHex: string,\n rawBodyString: string,\n signatureHeader: string\n): Promise<boolean> {\n // Determine environment and use the appropriate implementation\n if (typeof window !== \"undefined\" && window?.crypto?.subtle) {\n // Browser environment\n return verifyBrowser(secretHex, rawBodyString, signatureHeader);\n } else if (typeof process !== \"undefined\" && process?.versions?.node) {\n // Node.js environment\n return verifyNode(secretHex, rawBodyString, signatureHeader);\n } else {\n throw new Error(\n \"Unsupported environment: neither browser Web Crypto API nor Node.js crypto is available\"\n );\n }\n}\n\n// Export individual implementations for advanced use cases\nexport { verifyWebhookSignatureHeader as verifyWebhookSignatureHeaderBrowser } from \"./browser\";\nexport { verifyWebhookSignatureHeader as verifyWebhookSignatureHeaderNode } from \"./node\";\nexport * from \"./common\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0CAAAA;AAAA;AAAA;;;ACUO,SAAS,qBACd,iBACqB;AACrB,QAAM,QAAQ,gBAAgB,MAAM,6BAA6B;AACjE,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,QAAM,CAAC,EAAE,WAAW,YAAY,IAAI;AACpC,SAAO,EAAE,WAAW,aAAa;AACnC;AAOO,SAAS,WAAW,KAAyB;AAClD,MAAI,IAAI,SAAS,MAAM;AAAG,UAAM,IAAI,MAAM,oBAAoB;AAC9D,QAAM,QAAQ,IAAI,WAAW,IAAI,SAAS,CAAC;AAC3C,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,UAAM,IAAI,CAAC,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE;AAAA,EACjD;AACA,SAAO;AACT;AAOO,SAAS,YAAY,QAA6B;AACvD,SAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,EACrC,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AACZ;AAQO,SAAS,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;AAGxE,UAAM,gBAAgB,GAAG,SAAS,IAAI,aAAa;AAGnD,UAAM,WAAO,0BAAW,UAAU,OAAO,KAAK,WAAW,KAAK,CAAC;AAG/D,SAAK,OAAO,aAAa;AAGzB,UAAM,oBAAoB,KAAK,OAAO,KAAK;AAG3C,eAAO,cAAAC;AAAA,MACL,OAAO,KAAK,mBAAmB,KAAK;AAAA,MACpC,OAAO,KAAK,cAAc,KAAK;AAAA,IACjC;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,sCAAsC,KAAK;AACzD,WAAO;AAAA,EACT;AACF;;;ACzBA,eAAsB,uBACpB,WACA,eACA,iBACkB;AAnBpB;AAqBE,MAAI,OAAO,WAAW,iBAAe,sCAAQ,WAAR,mBAAgB,SAAQ;AAE3D,WAAO,6BAAc,WAAW,eAAe,eAAe;AAAA,EAChE,WAAW,OAAO,YAAY,iBAAe,wCAAS,aAAT,mBAAmB,OAAM;AAEpE,WAAOC,8BAAW,WAAW,eAAe,eAAe;AAAA,EAC7D,OAAO;AACL,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;","names":["verifyWebhookSignatureHeader","verifyWebhookSignatureHeader","cryptoTimingSafeEqual","verifyWebhookSignatureHeader"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/client.ts","../src/verification-session.ts","../src/webhook.ts"],"sourcesContent":["export * from \"./constants\";\nexport * from \"./types\";\nexport * from \"./verification-session\";\nexport * from \"./webhook\";\n","export const Environments = {\n LOCAL: \"local\",\n STAGING: \"staging\",\n PRODUCTION: \"production\",\n} as const;\n\nexport type Environment = (typeof Environments)[keyof typeof Environments];\n\ninterface EnvironmentConfig {\n appUrl: string;\n apiUrl: string;\n}\n\nexport const EnvironmentConfigs: Record<Environment, EnvironmentConfig> = {\n [Environments.LOCAL]: {\n appUrl: \"http://localhost:5173\",\n apiUrl: \"http://localhost:3000\",\n },\n [Environments.STAGING]: {\n appUrl: \"https://app-dev.zyphe.com\",\n apiUrl: \"https://api-dev.zyphe.com\",\n },\n [Environments.PRODUCTION]: {\n appUrl: \"https://verify.zyphe.com\",\n apiUrl: \"https://api.zyphe.com\",\n },\n};\n\nexport const API_KEY_HEADER = \"x-api-key\";\n","import createClient from \"openapi-fetch\";\nimport type { paths } from \"@zyphe-sdk/core/openapi\";\nimport { EnvironmentConfigs } from \"./constants\";\nimport type { SDKOptions } from \"./types\";\n\nexport const zypheApiClient = (opts: SDKOptions) => {\n return createClient<paths>({\n baseUrl: EnvironmentConfigs[opts.environment].apiUrl,\n });\n};\n","import { zypheApiClient } from \"./client\";\nimport { API_KEY_HEADER, EnvironmentConfigs, Environments } from \"./constants\";\nimport type {\n InitializeZypheFlowParams,\n SdkCreateVerificationRequestResponse,\n SDKOptions,\n} from \"./types\";\n\nexport function createVerificationSession(\n email: string,\n flowId: string,\n flowStepId: string,\n isSandbox: boolean,\n opts: SDKOptions\n) {\n const client = zypheApiClient(opts);\n\n return client.POST(\"/sdk/flow/{flow_id}/vr/create\", {\n body: { email, flowStepId },\n headers: {\n [API_KEY_HEADER]: opts.apiKey,\n },\n params: {\n path: {\n flow_id: flowId,\n },\n query: {\n sandbox: isSandbox,\n },\n },\n });\n}\n\nfunction getFlowUrlOrigin(environment: SDKOptions[\"environment\"]) {\n switch (environment) {\n case Environments.LOCAL:\n return EnvironmentConfigs[Environments.LOCAL].appUrl;\n case Environments.STAGING:\n return EnvironmentConfigs[Environments.STAGING].appUrl;\n case Environments.PRODUCTION:\n return EnvironmentConfigs[Environments.PRODUCTION].appUrl;\n default:\n throw new Error(`Invalid environment: ${environment}`);\n }\n}\n\nexport function constructVerificationSessionUrl({\n flowParams,\n verificationSession,\n opts,\n}: {\n flowParams: InitializeZypheFlowParams;\n verificationSession: SdkCreateVerificationRequestResponse;\n opts: SDKOptions;\n}) {\n const origin = getFlowUrlOrigin(opts.environment);\n const { isSandbox, product } = flowParams;\n const { handoffBaseUrl, primaryColor, secondaryColor, isFullscreen } = opts;\n\n if (!verificationSession) {\n throw new Error(\"Failed to create verification session\");\n }\n\n let baseUrl = `${origin}${isSandbox ? \"/sandbox\" : \"\"}/flow/${verificationSession.flowSlug}/${product}/${verificationSession.flowStepSlug}?zypheVr=${encodeURIComponent(verificationSession.verificationRequest.id)}&zypheEmail=${encodeURIComponent(verificationSession.email)}&zypheToken=${encodeURIComponent(verificationSession.zypheToken)}`;\n\n if (handoffBaseUrl) {\n baseUrl += `&zypheHandoffBaseUrl=${encodeURIComponent(handoffBaseUrl)}`;\n }\n\n if (primaryColor) {\n baseUrl += `&zyphePrimaryColor=${encodeURIComponent(primaryColor)}`;\n }\n\n if (secondaryColor) {\n baseUrl += `&zypheSecondaryColor=${encodeURIComponent(secondaryColor)}`;\n }\n\n if (isFullscreen) {\n baseUrl += `&zypheFullscreen=${encodeURIComponent(isFullscreen)}`;\n }\n\n return baseUrl;\n}\n","export interface SignatureComponents {\n timestamp: string;\n signatureHex: string;\n}\n\n/**\n * Parses a webhook signature header of the form \"t=<timestamp>,v0=<signature>\"\n * @param signatureHeader - The header string, e.g. \"t=1234567890,v0=abcdef...\"\n * @returns The parsed timestamp and signature hex\n */\nexport function parseSignatureHeader(\n signatureHeader: string\n): SignatureComponents {\n const match = signatureHeader.match(/^t=(\\d+),v0=([a-fA-F0-9]+)$/);\n if (!match) {\n throw new Error(\"Invalid signature header format\");\n }\n const [, timestamp, signatureHex] = match;\n\n if (!timestamp || !signatureHex) {\n throw new Error(\"Invalid signature header format\");\n }\n\n return { timestamp, signatureHex };\n}\n\n/**\n * Converts a hex string to a Uint8Array\n * @param hex - The hex string to convert\n * @returns The resulting Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) throw new Error(\"Invalid hex string\");\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Converts an ArrayBuffer to a hex string\n * @param buffer - The buffer to convert\n * @returns The hex string representation\n */\nexport function bufferToHex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Compares two strings in constant time to prevent timing attacks\n * @param a - First string\n * @param b - Second string\n * @returns True if strings are equal, false otherwise\n */\nexport function timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n\nexport const WebhookSignatureErrorCodes = {\n MISSING_SIGNATURE_HEADER: 1,\n INVALID_SIGNATURE_HEADER: 2,\n SIGNATURE_MISMATCH: 3,\n} as const;\n\nexport const WebhookSignatureErrorMessages = {\n [WebhookSignatureErrorCodes.MISSING_SIGNATURE_HEADER]:\n \"Missing signature header\",\n [WebhookSignatureErrorCodes.INVALID_SIGNATURE_HEADER]:\n \"Invalid signature header\",\n [WebhookSignatureErrorCodes.SIGNATURE_MISMATCH]: \"Signature mismatch\",\n} as const;\n\nexport interface WebhookVerifierOptions<T extends Function> {\n /**\n * The hex-encoded secret key used to verify the signature\n */\n secretHex: string;\n\n /**\n * The name of the header containing the signature\n * @default \"x-signature\"\n */\n signatureHeader?: string;\n\n /**\n * Optional function to handle unauthorized requests\n * @default Returns 401 Unauthorized with JSON error\n */\n onUnauthorized?: T;\n\n /**\n * Whether to make the raw body available on req.rawBody\n * @default true\n */\n exposeRawBody?: boolean;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,eAAe;AAAA,EAC1B,OAAO;AAAA,EACP,SAAS;AAAA,EACT,YAAY;AACd;AASO,IAAM,qBAA6D;AAAA,EACxE,CAAC,aAAa,KAAK,GAAG;AAAA,IACpB,QAAQ;AAA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