import {z} from 'zod' export type AcceptorKeyRef = string; export type Pan = string; export type ExpiryMonth = number; export type ExpiryYear = number; export type Cvc = string; export type HolderName = string; export type InputCard = {number: Pan, expiryMonth: ExpiryMonth, expiryYear: ExpiryYear, cvc?: Cvc | undefined, holderName?: HolderName | undefined}; export type ProcessorTokenKey = string; export type CardByProcessorTokenKey = {processorTokenKey: ProcessorTokenKey, cvc?: string | undefined}; export type Card = InputCard | CardByProcessorTokenKey; export type Intent = 'purchase' | 'reservation' | 'account-status' | 'payout' | 'payout-status' | 'funding' | 'advice' | 'refund'; export type CardEntry = 'e-commerce' | 'card-on-file' | 'token' | 'token-on-file'; export type Order = 'checkout' | 'unspecified' | 'one-click' | 'recurring' | 'ucof' | 'installment' | 'standing-order'; export type ThreeDsType = {intent: Intent, cardEntry?: CardEntry | undefined, order: Order}; export type AmountValue = number; export type SchemasCurrencyCode = string; export type Amount = {value: AmountValue, currency: SchemasCurrencyCode}; export type ChallengeIndicator = 'no-preference' | 'no-challenge' | 'challenge-preferred' | 'challenge-mandated' | 'no-challenge-tra' | 'no-challenge-low-value' | 'no-challenge-scp' | 'data-only'; export type NotificationUrl = string; export type BrowserAcceptHeader = string; export type BrowserLanguage = string; export type BrowserUserAgent = string; export type BrowserIP = string; export type BrowserScreenWidth = string; export type BrowserScreenHeight = string; export type BrowserTimeZoneOffset = string; export type BrowserJavaEnabled = boolean; export type BrowserColorDepth = string; export type AuthenticationContext = {notificationUrl: NotificationUrl, browserData: {acceptHeader: BrowserAcceptHeader, language: BrowserLanguage, userAgent: BrowserUserAgent, browserIP?: BrowserIP | undefined, javascriptEnabled: true, screenWidth: BrowserScreenWidth, screenHeight: BrowserScreenHeight, timeZoneOffset: BrowserTimeZoneOffset, javaEnabled: BrowserJavaEnabled, colorDepth: BrowserColorDepth} | {acceptHeader: BrowserAcceptHeader, language: BrowserLanguage, userAgent: BrowserUserAgent, browserIP?: BrowserIP | undefined, javascriptEnabled: false, screenWidth?: BrowserScreenWidth | undefined, screenHeight?: BrowserScreenHeight | undefined, timeZoneOffset?: BrowserTimeZoneOffset | undefined, javaEnabled?: BrowserJavaEnabled | undefined, colorDepth?: BrowserColorDepth | undefined}}; export type TransactionReference = string; export type LocalTransactionDateTime = unknown; export type RecurringExpiry = string; export type RecurringFrequency = number; export type InstallmentTerms = number; export type DynamicDescriptor = {merchantName?: string | undefined}; export type PhoneNumber = {countryCode: string, number: string}; export type CardholderInformation = {email?: string | undefined, phone?: ({work?: PhoneNumber | undefined, mobile?: PhoneNumber | undefined, home?: PhoneNumber | undefined}) | undefined}; export type ComponentsSchemasStateOrProvince = string; export type ComponentsSchemasCity = string; export type ComponentsSchemasLine1 = string; export type ComponentsSchemasLine2 = string; export type ComponentsSchemasPostalCode = string; export type AddressInput = {countryCode: {alpha3: string} | {alpha2: string} | {numeric: string}, stateOrProvince?: ComponentsSchemasStateOrProvince | undefined, city: ComponentsSchemasCity, line1: ComponentsSchemasLine1, line2?: ComponentsSchemasLine2 | undefined, postalCode: ComponentsSchemasPostalCode}; export type PublicCreate3dsRequestWithMerchantAcceptor = {merchantAcceptorKey: AcceptorKeyRef, card: Card, type: ThreeDsType, amount: Amount, challengeIndicator?: ChallengeIndicator | undefined, authenticationContext: AuthenticationContext, transactionReference?: TransactionReference | undefined, localTransactionDateTime?: LocalTransactionDateTime | undefined, recurringExpiry?: RecurringExpiry | undefined, recurringFrequency?: RecurringFrequency | undefined, installmentTerms?: InstallmentTerms | undefined, dynamicDescriptor?: DynamicDescriptor | undefined, cardholderInformation?: CardholderInformation | undefined, threeDSServerTransID?: string | undefined, billingAddress?: AddressInput | undefined, shippingAddress?: AddressInput | undefined}; export type SchemasCountryCodeAlpha3 = {alpha3: string}; export type SchemasCountryCodeAlpha2 = {alpha2: string}; export type SchemasCountryCodeNumeric = {numeric: string}; export type MerchantInfoRequest = {acquirerBin?: string | undefined, merchantId: string, mcc: string, merchantName: string, merchantCountryCode: SchemasCountryCodeAlpha3 | SchemasCountryCodeAlpha2 | SchemasCountryCodeNumeric, websiteUrl: string, network: 'american-express' | 'bancontact' | 'diners' | 'mastercard' | 'visa'}; export type PublicCreate3dsRequestWithMerchantInfo = {merchantInfo: MerchantInfoRequest, card: Card, type: ThreeDsType, amount: Amount, challengeIndicator?: ChallengeIndicator | undefined, authenticationContext: AuthenticationContext, transactionReference?: TransactionReference | undefined, localTransactionDateTime?: LocalTransactionDateTime | undefined, recurringExpiry?: RecurringExpiry | undefined, recurringFrequency?: RecurringFrequency | undefined, installmentTerms?: InstallmentTerms | undefined, dynamicDescriptor?: DynamicDescriptor | undefined, cardholderInformation?: CardholderInformation | undefined, threeDSServerTransID?: string | undefined, billingAddress?: AddressInput | undefined, shippingAddress?: AddressInput | undefined}; export type PublicCreate3dsRequest = PublicCreate3dsRequestWithMerchantAcceptor | PublicCreate3dsRequestWithMerchantInfo; export type CreateApi3dsArgs = {body: PublicCreate3dsRequest}; export type CreateApi3dsOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const threedsKey = z.string(); export const schemasAcceptorKey = z.string().min(5).max(120); export const version = z.number().int(); export const schemasAcceptorRef = z.object({key: schemasAcceptorKey, version: version}); export const merchantInfoResponse = z.object({acquirerBin: z.string().min(6).max(11).optional(), merchantId: z.string().min(1).max(20), mcc: z.string().min(4).max(4), merchantName: z.string(), merchantCountryCode: z.object({alpha3: z.string(), alpha2: z.string(), numeric: z.string()}), websiteUrl: z.string().max(2048), network: z.enum(["american-express", "bancontact", "diners", "mastercard", "visa"])}); export const amountValue = z.number().int().gte(0).lte(999999999999); export const schemasCurrencyCode = z.string(); export const amount = z.object({value: amountValue, currency: schemasCurrencyCode}); export const unknownAmount = z.object({value: z.literal(-1), currency: z.literal("unknown")}); export const responseAmount = z.union([amount, unknownAmount]); export const authenticationNetwork = z.enum(["american-express", "bancontact", "diners", "mastercard", "visa", "unknown"]); export const protocolVersion = z.enum(["2.1.0", "2.2.0"]); export const deviceChannel = z.enum(["browser", "app", "3ri"]); export const frictionlessFlow = z.literal("frictionless"); export const frictionlessResult = z.literal("authenticated"); export const activeProtocolVersion = z.literal("2.2.0"); export const sdkTransID = z.string(); export const messageExtension = z.object({name: z.string().min(1).max(64), id: z.string().min(1).max(64), criticalityIndicator: z.boolean(), data: z.unknown()}); export const messageExtensionList = z.array(messageExtension); export const dsTransID = z.string(); export const acsTransID = z.string(); export const transStatus = z.enum(["Y", "N", "U", "A", "C", "D", "R", "I"]); export const transStatusReason = z.string(); export const threeDSServerTransID = z.string(); export const cardHolderInfo = z.string(); export const acsChallengeMandated = z.string(); export const dsReferenceNumber = z.string(); export const acsReferenceNumber = z.string(); export const acsOperatorID = z.string(); export const acsDecConInd = z.string(); export const acsRenderingType = z.object({acsInterface: z.string(), acsUiTemplate: z.string()}); export const acsUrl = z.string(); export const authenticationType = z.string(); export const eci = z.string(); export const whiteListStatus = z.string(); export const whiteListStatusSource = z.string(); export const acsSignedContent = z.string().min(1).max(2560); export const authenticationValue = z.string(); export const aRes = z.object({messageVersion: activeProtocolVersion, sdkTransID: sdkTransID.optional(), messageExtension: messageExtensionList.optional(), messageType: z.literal("ARes"), dsTransID: dsTransID, acsTransID: acsTransID, transStatus: transStatus, transStatusReason: transStatusReason.optional(), threeDSServerTransID: threeDSServerTransID, cardholderInfo: cardHolderInfo.optional(), acsChallengeMandated: acsChallengeMandated.optional(), dsReferenceNumber: dsReferenceNumber, acsReferenceNumber: acsReferenceNumber, acsOperatorID: acsOperatorID.optional(), acsDecConInd: acsDecConInd.optional(), acsRenderingType: acsRenderingType.optional(), acsURL: acsUrl.optional(), authenticationType: authenticationType.optional(), eci: eci.optional(), whiteListStatus: whiteListStatus.optional(), whiteListStatusSource: whiteListStatusSource.optional(), acsSignedContent: acsSignedContent.optional(), authenticationValue: authenticationValue.optional()}); export const transactionReference = z.string().min(1).max(120); export const fraudLiability = z.enum(["acquirer", "issuer"]); export const order = z.enum(["checkout", "unspecified", "one-click", "recurring", "ucof", "installment", "standing-order"]); export const intent = z.enum(["purchase", "reservation", "account-status", "payout", "payout-status", "funding", "advice", "refund"]); export const schemasCreated = z.string(); export const threeDsFrictionlessAuthenticated = z.object({key: threedsKey, merchantAcceptorRef: schemasAcceptorRef.optional(), merchantInfo: merchantInfoResponse.optional(), amount: responseAmount, network: authenticationNetwork, protocolVersion: protocolVersion, deviceChannel: deviceChannel, flow: frictionlessFlow, result: frictionlessResult, ares: aRes, transactionReference: transactionReference.optional(), fraudLiability: fraudLiability.optional(), type: z.object({order: order.optional(), intent: intent.optional()}).optional(), created: schemasCreated, version: version}); export const threeDsChallenge = z.object({key: threedsKey, merchantAcceptorRef: schemasAcceptorRef.optional(), merchantInfo: merchantInfoResponse.optional(), amount: responseAmount, network: authenticationNetwork, protocolVersion: protocolVersion, deviceChannel: deviceChannel, flow: z.literal("challenge"), result: z.literal("challenge"), ares: aRes, transactionReference: transactionReference.optional(), type: z.object({order: order.optional(), intent: intent.optional()}).optional(), created: schemasCreated, version: version}); export const noAuthFlow = z.literal("none"); export const noAuthResult = z.enum(["attempt", "non-authenticated"]); export const threeDsNoFlowNoAuth = z.object({key: threedsKey, merchantAcceptorRef: schemasAcceptorRef.optional(), merchantInfo: merchantInfoResponse.optional(), amount: responseAmount, network: authenticationNetwork, protocolVersion: protocolVersion, deviceChannel: deviceChannel, flow: noAuthFlow, result: noAuthResult, ares: aRes, transactionReference: transactionReference.optional(), fraudLiability: fraudLiability.optional(), type: z.object({order: order.optional(), intent: intent.optional()}).optional(), created: schemasCreated, version: version}); export const dataOnlyResult = z.literal("informational"); export const threeDsDataOnly = z.object({key: threedsKey, merchantAcceptorRef: schemasAcceptorRef.optional(), merchantInfo: merchantInfoResponse.optional(), amount: responseAmount, network: authenticationNetwork, protocolVersion: protocolVersion, deviceChannel: deviceChannel, flow: z.literal("none"), result: dataOnlyResult, ares: aRes, transactionReference: transactionReference.optional(), fraudLiability: fraudLiability.optional(), type: z.object({order: order.optional(), intent: intent.optional()}).optional(), created: schemasCreated, version: version}); export const createApi3dsResponse = z.union([threeDsFrictionlessAuthenticated, threeDsChallenge, threeDsNoFlowNoAuth, threeDsDataOnly]); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create 3DS Authentication * * POST /3ds * * Also accepts auth: BearerToken */ export const createApi3ds = async (args: CreateApi3dsArgs, options?: CreateApi3dsOptions) => { const {baseUrl = "https://eu-west-1.api.silverflow.com/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/3ds${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApi3dsResponse, await res.json()) };