@zyphe-sdk/core 0.1.13 → 0.1.14

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.
@@ -1,70 +0,0 @@
1
- import { readFileSync, writeFileSync } from "fs";
2
- import openapiTS, { astToString, OpenAPI3 } from "openapi-typescript";
3
- import ts from "typescript";
4
-
5
- const JSON_SCHEMA_URL = new URL("../public/openapi.json", import.meta.url)
6
- .pathname;
7
-
8
- await fetch("http://localhost:3000/api-docs/sdk-openapi.json")
9
- .then((res) => res.json())
10
- .then((schema) => {
11
- writeFileSync(JSON_SCHEMA_URL, JSON.stringify(schema, null, 2));
12
- });
13
-
14
- const SCHEMA = JSON.parse(
15
- readFileSync(JSON_SCHEMA_URL, "utf-8")
16
- ) as unknown as OpenAPI3;
17
-
18
- // https://openapi-ts.dev/node#example-blob-types
19
- const BLOB = ts.factory.createTypeReferenceNode(
20
- ts.factory.createIdentifier("Blob")
21
- );
22
- const NULL = ts.factory.createLiteralTypeNode(ts.factory.createNull());
23
-
24
- const ast = await openapiTS(SCHEMA, {
25
- transform(schemaObject, _metadata) {
26
- // Override `binary` fields to be `Blob`, rather than `string`
27
- if (schemaObject.format === "binary") {
28
- return schemaObject.nullable
29
- ? ts.factory.createUnionTypeNode([BLOB, NULL])
30
- : BLOB;
31
- }
32
-
33
- // Override `DvConfig['thresholds']` in order to achieve better type safety
34
- if (
35
- schemaObject.type === "object" &&
36
- _metadata.path?.includes("DvConfig")
37
- ) {
38
- // Get the DvConfigThreshold enum values from the schema
39
- const thresholdEnum = SCHEMA.components?.schemas?.DvConfigThreshold
40
- .enum as string[] | undefined;
41
- if (!thresholdEnum) {
42
- return undefined;
43
- }
44
-
45
- // Only modify the thresholds property if it exists
46
- if (schemaObject.properties?.thresholds) {
47
- const thresholdsSchema = schemaObject.properties.thresholds;
48
- schemaObject.properties.thresholds = {
49
- type: "object",
50
- nullable:
51
- "nullable" in thresholdsSchema
52
- ? thresholdsSchema.nullable
53
- : undefined,
54
- properties: Object.fromEntries(
55
- thresholdEnum.map((key) => [key, { type: "number" }])
56
- ),
57
- };
58
- }
59
-
60
- return undefined;
61
- }
62
- },
63
- });
64
-
65
- // https://openapi-ts.dev/node#usage
66
- const contents = astToString(ast);
67
-
68
- const OUTPUT_PATH = new URL("../public/openapi.d.ts", import.meta.url).pathname;
69
-
70
- writeFileSync(OUTPUT_PATH, contents);
package/src/client.ts DELETED
@@ -1,10 +0,0 @@
1
- import createClient from "openapi-fetch";
2
- import type { paths } from "@zyphe-sdk/core/openapi";
3
- import { EnvironmentConfigs } from "./constants";
4
- import type { SDKOptions } from "./types";
5
-
6
- export const zypheApiClient = (opts: SDKOptions) => {
7
- return createClient<paths>({
8
- baseUrl: EnvironmentConfigs[opts.environment].apiUrl,
9
- });
10
- };
package/src/constants.ts DELETED
@@ -1,29 +0,0 @@
1
- export const Environments = {
2
- LOCAL: "local",
3
- STAGING: "staging",
4
- PRODUCTION: "production",
5
- } as const;
6
-
7
- export type Environment = (typeof Environments)[keyof typeof Environments];
8
-
9
- interface EnvironmentConfig {
10
- appUrl: string;
11
- apiUrl: string;
12
- }
13
-
14
- export const EnvironmentConfigs: Record<Environment, EnvironmentConfig> = {
15
- [Environments.LOCAL]: {
16
- appUrl: "http://localhost:5173",
17
- apiUrl: "http://localhost:3000",
18
- },
19
- [Environments.STAGING]: {
20
- appUrl: "https://app-dev.zyphe.com",
21
- apiUrl: "https://api-dev.zyphe.com",
22
- },
23
- [Environments.PRODUCTION]: {
24
- appUrl: "https://verify.zyphe.com",
25
- apiUrl: "https://api.zyphe.com",
26
- },
27
- };
28
-
29
- export const API_KEY_HEADER = "x-api-key";
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from "./constants";
2
- export * from "./types";
3
- export * from "./verification-session";
4
- export * from "./webhook";
package/src/types.ts DELETED
@@ -1,82 +0,0 @@
1
- import type { components } from "../public/openapi";
2
- import type { Environment } from "./constants";
3
-
4
- export type SdkCreateVerificationRequestResponse =
5
- components["schemas"]["SdkCreateVerificationRequestResponse"];
6
-
7
- /**
8
- * Parameters for initializing the Zyphe iframe for a Flow.
9
- * These will remain constant for each user that visits the Flow URL.
10
- */
11
- export interface InitializeZypheFlowParams {
12
- /**
13
- * The ID of the Flow
14
- * UUID v4 format
15
- * @example "4810bc63-bfdd-4487-ae57-c939046f56b6"
16
- */
17
- flowId: string;
18
- /**
19
- * The ID of the FlowStep
20
- * UUID v4 format
21
- * @example "4810bc63-bfdd-4487-ae57-c939046f56b6"
22
- */
23
- flowStepId: string;
24
- /**
25
- * The email of the user.
26
- * @example "user@example.com"
27
- */
28
- email: string;
29
- /**
30
- * The type of Flow URL.
31
- * The third path segment of your Flow URL.
32
- * @example "http://localhost:5173/flow/flowSlug/kyc/stepSlug"
33
- */
34
- product: "kyc"; //| "kyb";
35
- /**
36
- * Whether the Flow is a "sandbox" Flow.
37
- *
38
- * This will prepend "sandbox" to the final URL.
39
- * @example "http://localhost:5173/sandbox/flow/flowSlug/kyc/stepSlug"
40
- */
41
- isSandbox: boolean;
42
- /**
43
- * Custom data to be passed to the Flow.
44
- * @example { "custom_data": "custom_value" }
45
- */
46
- customData?: Record<string, string>;
47
- }
48
-
49
- export interface SDKOptions {
50
- apiKey: string;
51
- environment: Environment;
52
- /**
53
- * If set, the QR code displayed on desktop devices of a Document Verification flow will direct to this URL.
54
- * If not set, the QR code will direct to the corresponding zyphe.com URL, depending upon your configured environment.
55
- *
56
- * The URL will include the query parameters `zypheVr` and `zypheToken`.
57
- *
58
- * @default "https://app-dev.zyphe.com" || "https://verify.zyphe.com"
59
- * @example "http://example.com"
60
- */
61
- handoffBaseUrl?: string;
62
- /**
63
- * The main background color of the page.
64
- * This will override the primary color configured in verify.zyphe.com
65
- *
66
- * The accepted values are flexible, but we recommend a hex code.
67
- * @example "#000000"
68
- */
69
- primaryColor?: string;
70
- /**
71
- * The accent color of the page, used for buttons, icons, etc.
72
- * This will override the secondary color configured in verify.zyphe.com
73
- *
74
- * The accepted values are flexible, but we recommend a hex code.
75
- * @example "#000000"
76
- */
77
- secondaryColor?: string;
78
- /**
79
- * If true, the verification session will be displayed in "fullscreen" mode.
80
- */
81
- isFullscreen?: boolean;
82
- }
@@ -1,94 +0,0 @@
1
- import { zypheApiClient } from "./client";
2
- import { API_KEY_HEADER, EnvironmentConfigs, Environments } from "./constants";
3
- import type {
4
- InitializeZypheFlowParams,
5
- SdkCreateVerificationRequestResponse,
6
- SDKOptions,
7
- } from "./types";
8
-
9
- interface CreateVerificationSessionParams {
10
- email: string;
11
- flowId: string;
12
- flowStepId: string;
13
- isSandbox: boolean;
14
- customData?: Record<string, string>;
15
- }
16
-
17
- export function createVerificationSession(
18
- {
19
- email,
20
- flowId,
21
- flowStepId,
22
- isSandbox,
23
- customData,
24
- }: CreateVerificationSessionParams,
25
- opts: SDKOptions
26
- ) {
27
- const client = zypheApiClient(opts);
28
-
29
- return client.POST("/sdk/flow/{flow_id}/vr/create", {
30
- body: { email, flowStepId, customData },
31
- headers: {
32
- [API_KEY_HEADER]: opts.apiKey,
33
- },
34
- params: {
35
- path: {
36
- flow_id: flowId,
37
- },
38
- query: {
39
- sandbox: isSandbox,
40
- },
41
- },
42
- });
43
- }
44
-
45
- function getFlowUrlOrigin(environment: SDKOptions["environment"]) {
46
- switch (environment) {
47
- case Environments.LOCAL:
48
- return EnvironmentConfigs[Environments.LOCAL].appUrl;
49
- case Environments.STAGING:
50
- return EnvironmentConfigs[Environments.STAGING].appUrl;
51
- case Environments.PRODUCTION:
52
- return EnvironmentConfigs[Environments.PRODUCTION].appUrl;
53
- default:
54
- throw new Error(`Invalid environment: ${environment}`);
55
- }
56
- }
57
-
58
- export function constructVerificationSessionUrl({
59
- flowParams,
60
- verificationSession,
61
- opts,
62
- }: {
63
- flowParams: InitializeZypheFlowParams;
64
- verificationSession: SdkCreateVerificationRequestResponse;
65
- opts: SDKOptions;
66
- }) {
67
- const origin = getFlowUrlOrigin(opts.environment);
68
- const { isSandbox, product } = flowParams;
69
- const { handoffBaseUrl, primaryColor, secondaryColor, isFullscreen } = opts;
70
-
71
- if (!verificationSession) {
72
- throw new Error("Failed to create verification session");
73
- }
74
-
75
- let baseUrl = `${origin}${isSandbox ? "/sandbox" : ""}/flow/${verificationSession.flowSlug}/${product}/${verificationSession.flowStepSlug}?zypheVr=${encodeURIComponent(verificationSession.verificationRequest.id)}&zypheEmail=${encodeURIComponent(verificationSession.email)}&zypheToken=${encodeURIComponent(verificationSession.zypheToken)}`;
76
-
77
- if (handoffBaseUrl) {
78
- baseUrl += `&zypheHandoffBaseUrl=${encodeURIComponent(handoffBaseUrl)}`;
79
- }
80
-
81
- if (primaryColor) {
82
- baseUrl += `&zyphePrimaryColor=${encodeURIComponent(primaryColor)}`;
83
- }
84
-
85
- if (secondaryColor) {
86
- baseUrl += `&zypheSecondaryColor=${encodeURIComponent(secondaryColor)}`;
87
- }
88
-
89
- if (isFullscreen) {
90
- baseUrl += `&zypheFullscreen=${encodeURIComponent(isFullscreen)}`;
91
- }
92
-
93
- return baseUrl;
94
- }
package/src/webhook.ts DELETED
@@ -1,104 +0,0 @@
1
- export interface SignatureComponents {
2
- timestamp: string;
3
- signatureHex: string;
4
- }
5
-
6
- /**
7
- * Parses a webhook signature header of the form "t=<timestamp>,v0=<signature>"
8
- * @param signatureHeader - The header string, e.g. "t=1234567890,v0=abcdef..."
9
- * @returns The parsed timestamp and signature hex
10
- */
11
- export function parseSignatureHeader(
12
- signatureHeader: string
13
- ): SignatureComponents {
14
- const match = signatureHeader.match(/^t=(\d+),v0=([a-fA-F0-9]+)$/);
15
- if (!match) {
16
- throw new Error("Invalid signature header format");
17
- }
18
- const [, timestamp, signatureHex] = match;
19
-
20
- if (!timestamp || !signatureHex) {
21
- throw new Error("Invalid signature header format");
22
- }
23
-
24
- return { timestamp, signatureHex };
25
- }
26
-
27
- /**
28
- * Converts a hex string to a Uint8Array
29
- * @param hex - The hex string to convert
30
- * @returns The resulting Uint8Array
31
- */
32
- export function hexToBytes(hex: string): Uint8Array {
33
- if (hex.length % 2 !== 0) throw new Error("Invalid hex string");
34
- const bytes = new Uint8Array(hex.length / 2);
35
- for (let i = 0; i < hex.length; i += 2) {
36
- bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
37
- }
38
- return bytes;
39
- }
40
-
41
- /**
42
- * Converts an ArrayBuffer to a hex string
43
- * @param buffer - The buffer to convert
44
- * @returns The hex string representation
45
- */
46
- export function bufferToHex(buffer: ArrayBuffer): string {
47
- return Array.from(new Uint8Array(buffer))
48
- .map((b) => b.toString(16).padStart(2, "0"))
49
- .join("");
50
- }
51
-
52
- /**
53
- * Compares two strings in constant time to prevent timing attacks
54
- * @param a - First string
55
- * @param b - Second string
56
- * @returns True if strings are equal, false otherwise
57
- */
58
- export function timingSafeEqual(a: string, b: string): boolean {
59
- if (a.length !== b.length) return false;
60
- let result = 0;
61
- for (let i = 0; i < a.length; i++) {
62
- result |= a.charCodeAt(i) ^ b.charCodeAt(i);
63
- }
64
- return result === 0;
65
- }
66
-
67
- export const WebhookSignatureErrorCodes = {
68
- MISSING_SIGNATURE_HEADER: 1,
69
- INVALID_SIGNATURE_HEADER: 2,
70
- SIGNATURE_MISMATCH: 3,
71
- } as const;
72
-
73
- export const WebhookSignatureErrorMessages = {
74
- [WebhookSignatureErrorCodes.MISSING_SIGNATURE_HEADER]:
75
- "Missing signature header",
76
- [WebhookSignatureErrorCodes.INVALID_SIGNATURE_HEADER]:
77
- "Invalid signature header",
78
- [WebhookSignatureErrorCodes.SIGNATURE_MISMATCH]: "Signature mismatch",
79
- } as const;
80
-
81
- export interface WebhookVerifierOptions<T extends Function> {
82
- /**
83
- * The hex-encoded secret key used to verify the signature
84
- */
85
- secretHex: string;
86
-
87
- /**
88
- * The name of the header containing the signature
89
- * @default "x-signature"
90
- */
91
- signatureHeader?: string;
92
-
93
- /**
94
- * Optional function to handle unauthorized requests
95
- * @default Returns 401 Unauthorized with JSON error
96
- */
97
- onUnauthorized?: T;
98
-
99
- /**
100
- * Whether to make the raw body available on req.rawBody
101
- * @default true
102
- */
103
- exposeRawBody?: boolean;
104
- }
package/tsconfig.json DELETED
@@ -1,32 +0,0 @@
1
- {
2
- "$schema": "https://json.schemastore.org/tsconfig",
3
- "compilerOptions": {
4
- /* Base options: */
5
- "esModuleInterop": true,
6
- "skipLibCheck": true,
7
- "target": "es2023",
8
- "allowJs": true,
9
- "resolveJsonModule": true,
10
- "moduleDetection": "force",
11
- "isolatedModules": true,
12
- "verbatimModuleSyntax": true,
13
-
14
- /* Strictness */
15
- "strict": true,
16
- "noUncheckedIndexedAccess": true,
17
- "noImplicitOverride": true,
18
-
19
- /* Linting: */
20
- "noFallthroughCasesInSwitch": true,
21
- "noUncheckedSideEffectImports": true,
22
- "forceConsistentCasingInFileNames": true,
23
- "noPropertyAccessFromIndexSignature": true,
24
-
25
- /* If NOT transpiling with TypeScript: */
26
- "module": "preserve",
27
-
28
- /* Browser agnostic definitions: */
29
- "lib": ["ES2023"]
30
- },
31
- "include": ["src/**/*.ts"]
32
- }
package/tsup.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineConfig } from "tsup";
2
-
3
- export default defineConfig({
4
- dts: true,
5
- format: ["esm"],
6
- sourcemap: true,
7
- outDir: "dist",
8
- entry: ["src/index.ts"],
9
- platform: "neutral",
10
- publicDir: true,
11
- });