Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add shared HTTP client and migrate Veriff API calls

Kiran Kacdbfc262d3f
diff --git a/apps/web/app/(ee)/api/cron/partners/verify-country-change/route.ts b/apps/web/app/(ee)/api/cron/partners/verify-country-change/route.ts
index b1d753c7bd..460d005d3f 100644
--- a/apps/web/app/(ee)/api/cron/partners/verify-country-change/route.ts
+++ b/apps/web/app/(ee)/api/cron/partners/verify-country-change/route.ts
@@ -1,6 +1,6 @@
import { withCron } from "@/lib/cron/with-cron";
import { prisma } from "@/lib/prisma";
-import { fetchVeriffSessionDecision } from "@/lib/veriff/fetch-veriff-session-decision";
+import { veriffClient } from "@/lib/veriff/client";
import {
mergeVeriffMetadata,
parseVeriffMetadata,
@@ -52,23 +52,13 @@ export const POST = withCron(async ({ rawBody }) => {
// Fetch the original Veriff decision to get the document country
let documentCountry: string | null = null;
- try {
- const { verification } = await fetchVeriffSessionDecision(
- partner.veriffSessionId,
- );
-
- documentCountry =
- (verification.document?.country || verification.person?.nationality) ??
- null;
- } catch (error) {
- console.error(
- `Failed to fetch Veriff decision for partner ${partnerId}:`,
- error,
- );
+ const { verification } = await veriffClient.fetchSessionDecision(
+ partner.veriffSessionId,
+ );
- // Don't revoke on uncertainty — QStash will retry
- throw error;
- }
+ documentCountry =
+ (verification.document?.country || verification.person?.nationality) ??
+ null;
if (!documentCountry) {
return logAndRespond(
diff --git a/apps/web/lib/assert-env.ts b/apps/web/lib/assert-env.ts
new file mode 100644
index 0000000000..df1561333f
--- /dev/null
+++ b/apps/web/lib/assert-env.ts
@@ -0,0 +1,9 @@
+export function assertEnv(name: string): string {
+ const value = process.env[name];
+
+ if (!value) {
+ throw new Error(`${name} is not configured.`);
+ }
+
+ return value;
+}
diff --git a/apps/web/lib/http/base-client.ts b/apps/web/lib/http/base-client.ts
new file mode 100644
index 0000000000..292e6a0724
--- /dev/null
+++ b/apps/web/lib/http/base-client.ts
@@ -0,0 +1,347 @@
+import { logger } from "@/lib/axiom/server";
+import * as z from "zod/v4";
+
+const DEFAULT_TIMEOUT_MS = 30_000;
+const MAX_LOGGED_BODY_LENGTH = 2_000;
+
+type QueryValue = string | number | boolean | null | undefined;
+
+export interface HttpRequestOptions<
+ TInput extends z.ZodType = z.ZodType,
+ TOutput extends z.ZodType = z.ZodType,
+> {
+ // request input — validated with inputSchema when provided, then sent as
+ // query params for GET/DELETE requests or as the request body otherwise
+ input?: z.input<TInput>;
+ inputSchema?: TInput;
+ outputSchema: TOutput;
+ headers?: Record<string, string>;
+ bodyType?: "json" | "form";
+ timeout?: number;
+ signal?: AbortSignal;
+}
+
+export class HttpClientError extends Error {
+ readonly vendor: string;
+ readonly method: string;
+ readonly url: string;
+ readonly status: number | null;
+ readonly responseBody: string | null;
+
+ constructor({
+ vendor,
+ method,
+ url,
+ status,
+ responseBody,
+ message,
+ }: {
+ vendor: string;
+ method: string;
+ url: string;
+ status: number | null;
+ responseBody: string | null;
+ message: string;
+ }) {
+ super(message);
+ this.name = "HttpClientError";
+ this.vendor = vendor;
+ this.method = method;
+ this.url = url;
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+// Base class for external vendor API clients.
+export abstract class HttpBaseClient {
+ protected abstract readonly vendor: string;
+ protected abstract readonly baseUrl: string;
+
+ // Header-based auth. Return {} for vendors that authenticate via query
+ // params. Called per-request, so env validation belongs here
+ protected abstract buildAuthHeaders():
+ | Record<string, string>
+ | Promise<Record<string, string>>;
+
+ // Override for vendors that authenticate via query params. Any secret param
+ // must also be listed in redactedQueryParams.
+ protected buildAuthQuery(): Record<string, string> {
+ return {};
+ }
+
+ // Query params whose values are replaced with "REDACTED" in every log
+ // message and error. Request headers are never logged.
+ protected readonly redactedQueryParams: string[] = [];
+
+ // Override to translate HTTP failures into vendor-specific errors
+ // (e.g. a DubApiError with a caller-facing message).
+ protected mapError({
+ method,
+ url,
+ status,
+ responseBody,
+ }: {
+ method: string;
+ url: string;
+ status: number;
+ responseBody: string | null;
+ data: unknown;
+ }): Error {
+ return new HttpClientError({
+ vendor: this.vendor,
+ method,
+ url,
+ status,
+ responseBody,
+ message: `[${this.vendor}] ${method} ${url} failed with status ${status}`,
+ });
+ }
+
+ private readonly debug: boolean;
+ private readonly timeout: number;
+
+ constructor({
+ debug,
+ timeout,
+ }: {
+ debug?: boolean;
+ timeout?: number;
+ } = {}) {
+ this.debug = debug ?? process.env.NODE_ENV === "development";
+ this.timeout = timeout ?? DEFAULT_TIMEOUT_MS;
+ }
+
+ async get<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ return this.request("GET", path, options);
+ }
+
+ async post<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ return this.request("POST", path, options);
+ }
+
+ async put<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ return this.request("PUT", path, options);
+ }
+
+ async patch<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ return this.request("PATCH", path, options);
+ }
+
+ async delete<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ return this.request("DELETE", path, options);
+ }
+
+ private async request<TInput extends z.ZodType, TOutput extends z.ZodType>(
+ method: string,
+ path: string,
+ options: HttpRequestOptions<TInput, TOutput>,
+ ): Promise<z.output<TOutput>> {
+ const url = new URL(`${this.baseUrl}${path}`);
+
+ let input: unknown = options.input;
+
+ if (options.inputSchema && options.input !== undefined) {
+ input = options.inputSchema.parse(options.input);
+ }
+
+ // GET/DELETE requests carry no body — their input becomes query params
+ const inputAsQuery = method === "GET" || method === "DELETE";
+
+ let query: Record<string, QueryValue | QueryValue[]> | undefined;
+
+ if (inputAsQuery && input !== undefined) {
+ query = input as Record<string, QueryValue | QueryValue[]>;
+ }
+
+ this.buildQueryParams(url, query);
+
+ const safeUrl = this.redactUrl(url);
+
+ let body: BodyInit | undefined;
+ const headers: Record<string, string> = {};
+
+ if (!inputAsQuery && input !== undefined) {
+ if (options.bodyType === "form") {
+ body = new URLSearchParams(input as Record<string, string>);
+ } else {
+ body = JSON.stringify(input);
+ headers["Content-Type"] = "application/json";
+ }
+ }
+
+ Object.assign(headers, await this.buildAuthHeaders(), options.headers);
+
+ const signal =
+ options.signal ?? AbortSignal.timeout(options.timeout ?? this.timeout);
+
+ let response: Response;
+
+ try {
+ response = await fetch(url, {
+ method,
+ headers,
+ body,
+ signal,
+ });
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ const message = `[${this.vendor}] ${method} ${safeUrl} network error: ${reason}`;
+
+ await this.logError(message, {
+ method,
+ url: safeUrl,
+ status: null,
+ error: reason,
+ });
+
+ throw new HttpClientError({
+ vendor: this.vendor,
+ method,
+ url: safeUrl,
+ status: null,
+ responseBody: null,
+ message,
+ });
+ }
+
+ const text = await response.text();
+ let data: unknown = null;
+
+ if (text) {
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = text;
+ }
+ }
+
+ if (this.debug) {
+ console.log(
+ `[${this.vendor}] ${method} ${safeUrl} -> ${response.status}`,
+ data,
+ );
+ }
+
+ if (!response.ok) {
+ const responseBody = this.truncate(text);
+
+ await this.logError(
+ `[${this.vendor}] ${method} ${safeUrl} failed with status ${response.status}`,
+ {
+ method,
+ url: safeUrl,
+ status: response.status,
+ responseBody,
+ },
+ );
+
+ throw this.mapError({
+ method,
+ url: safeUrl,
+ status: response.status,
+ responseBody,
+ data,
+ });
+ }
+
+ const parsed = options.outputSchema.safeParse(data);
+
+ if (!parsed.success) {
+ const message = `[${this.vendor}] ${method} ${safeUrl} response validation failed`;
+
+ await this.logError(message, {
+ method,
+ url: safeUrl,
+ status: response.status,
+ issues: z.prettifyError(parsed.error),
+ responseBody: this.truncate(text),
+ });
+
+ throw new HttpClientError({
+ vendor: this.vendor,
+ method,
+ url: safeUrl,
+ status: response.status,
+ responseBody: this.truncate(text),
+ message,
+ });
+ }
+
+ return parsed.data as z.output<TOutput>;
+ }
+
+ private buildQueryParams(
+ url: URL,
+ query: Record<string, QueryValue | QueryValue[]> = {},
+ ) {
+ const merged = {
+ ...query,
+ ...this.buildAuthQuery(),
+ };
+
+ for (const [key, value] of Object.entries(merged)) {
+ if (value === null || value === undefined) {
+ continue;
+ }
+
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (item === null || item === undefined) {
+ continue;
+ }
+
+ url.searchParams.append(key, String(item));
+ }
+ } else {
+ url.searchParams.append(key, String(value));
+ }
+ }
+ }
+
+ private redactUrl(url: URL): string {
+ const safe = new URL(url);
+
+ for (const param of this.redactedQueryParams) {
+ if (safe.searchParams.has(param)) {
+ safe.searchParams.set(param, "REDACTED");
+ }
+ }
+
+ return safe.toString();
+ }
+
+ private truncate(text: string): string | null {
+ if (!text) {
+ return null;
+ }
+
+ return text.slice(0, MAX_LOGGED_BODY_LENGTH);
+ }
+
+ private async logError(message: string, metadata: Record<string, unknown>) {
+ console.error(message, metadata);
+
+ logger.error(message, {
+ vendor: this.vendor,
+ ...metadata,
+ });
+
+ await logger.flush();
+ }
+}
diff --git a/apps/web/lib/veriff/client.ts b/apps/web/lib/veriff/client.ts
new file mode 100644
index 0000000000..978c584e4a
--- /dev/null
+++ b/apps/web/lib/veriff/client.ts
@@ -0,0 +1,48 @@
+import { assertEnv } from "@/lib/assert-env";
+import { HttpBaseClient } from "@/lib/http/base-client";
+import crypto from "crypto";
+import * as z from "zod/v4";
+import {
+ veriffCreateSessionInputSchema,
+ veriffCreateSessionOutputSchema,
+ veriffDecisionEventSchema,
+} from "./schema";
+
+class VeriffClient extends HttpBaseClient {
+ protected readonly vendor = "Veriff";
+ protected readonly baseUrl = "https://stationapi.veriff.com/v1";
+
+ protected buildAuthHeaders() {
+ return {
+ "X-AUTH-CLIENT": assertEnv("VERIFF_API_KEY"),
+ };
+ }
+
+ // POST /v1/sessions
+ async createSession(input: z.input<typeof veriffCreateSessionInputSchema>) {
+ return await veriffClient.post("/sessions", {
+ input,
+ inputSchema: veriffCreateSessionInputSchema,
+ outputSchema: veriffCreateSessionOutputSchema,
+ });
+ }
+
+ // GET /v1/sessions/{sessionId}/decision
+ async fetchSessionDecision(sessionId: string) {
+ const hmacSignature = crypto
+ .createHmac("sha256", assertEnv("VERIFF_SHARED_SECRET"))
+ .update(sessionId)
+ .digest("hex");
+
+ return await veriffClient.get(`/sessions/${sessionId}/decision`, {
+ headers: {
+ "X-HMAC-SIGNATURE": hmacSignature,
+ },
+ outputSchema: veriffDecisionEventSchema,
+ });
+ }
+}
+
+export const veriffClient = new VeriffClient({
+ debug: true,
+});
diff --git a/apps/web/lib/veriff/create-veriff-session.ts b/apps/web/lib/veriff/create-veriff-session.ts
index b18154463c..9cf8017ae2 100644
--- a/apps/web/lib/veriff/create-veriff-session.ts
+++ b/apps/web/lib/veriff/create-veriff-session.ts
@@ -1,25 +1,16 @@
import { Partner } from "@prisma/client";
-import {
- veriffCreateSessionInputSchema,
- veriffCreateSessionOutputSchema,
-} from "./schema";
+import { veriffClient } from "./client";
export async function createVeriffSession({
partner,
}: {
partner: Pick<Partner, "id" | "email" | "name">;
}) {
- const apiKey = process.env.VERIFF_API_KEY;
-
- if (!apiKey) {
- throw new Error("VERIFF_API_KEY is not configured.");
- }
-
const nameParts = partner.name.split(" ");
const firstName = nameParts[0] || partner.name;
const lastName = nameParts.slice(1).join(" ") || partner.name;
- const input = veriffCreateSessionInputSchema.parse({
+ return await veriffClient.createSession({
verification: {
vendorData: partner.id,
person: {
@@ -28,29 +19,4 @@ export async function createVeriffSession({
},
},
});
-
- const rawResponse = await fetch("https://stationapi.veriff.com/v1/sessions", {
- method: "POST",
- headers: {
- "X-AUTH-CLIENT": apiKey,
- "Content-Type": "application/json",
- },
- body: JSON.stringify(input),
- });
-
- const response = await rawResponse.json();
-
- if (!rawResponse.ok) {
- console.error("[Veriff] Error", response);
- throw new Error("Failed to create verification session.");
- }
-
- const parsedResponse = veriffCreateSessionOutputSchema.safeParse(response);
-
- if (!parsedResponse.success) {
- console.error("[Veriff] Invalid response", parsedResponse.error);
- throw new Error("Failed to create verification session.");
- }
-
- return parsedResponse.data;
}
diff --git a/apps/web/lib/veriff/fetch-veriff-session-decision.ts b/apps/web/lib/veriff/fetch-veriff-session-decision.ts
deleted file mode 100644
index 42c6f40bc1..0000000000
--- a/apps/web/lib/veriff/fetch-veriff-session-decision.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import crypto from "crypto";
-import { veriffDecisionEventSchema } from "./schema";
-
-// GET /v1/sessions/{sessionId}/decision
-export async function fetchVeriffSessionDecision(sessionId: string) {
- const apiKey = process.env.VERIFF_API_KEY;
- const sharedSecret = process.env.VERIFF_SHARED_SECRET;
-
- if (!apiKey) {
- throw new Error("VERIFF_API_KEY is not configured.");
- }
-
- if (!sharedSecret) {
- throw new Error("VERIFF_SHARED_SECRET is not configured.");
- }
-
- const hmacSignature = crypto
- .createHmac("sha256", sharedSecret)
- .update(sessionId)
- .digest("hex");
-
- const rawResponse = await fetch(
- `https://stationapi.veriff.com/v1/sessions/${sessionId}/decision`,
- {
- method: "GET",
- headers: {
- "X-AUTH-CLIENT": apiKey,
- "X-HMAC-SIGNATURE": hmacSignature,
- "Content-Type": "application/json",
- },
- },
- );
-
- const responseText = await rawResponse.text();
- const response = responseText ? JSON.parse(responseText) : null;
-
- if (!rawResponse.ok) {
- throw new VeriffApiError({
- message: `[Veriff] Failed to fetch decision for session ${sessionId}: ${rawResponse.status}`,
- status: rawResponse.status,
- responseBody: responseText || null,
- });
- }
-
- return veriffDecisionEventSchema.parse(response);
-}
-
-class VeriffApiError extends Error {
- status: number;
- responseBody: string | null;
-
- constructor({
- message,
- status,
- responseBody,
- }: {
- message: string;
- status: number;
- responseBody: string | null;
- }) {
- super(message);
- this.name = "VeriffApiError";
- this.status = status;
- this.responseBody = responseBody;
- }
-}