import {z} from 'zod' export type Header = {service: string, issuerCode: string, subIssuerCode: string, requestId: string, keyTag?: string | undefined, iv?: string | undefined}; export type Principal = {type: string, value: string}; export type Expiry = {type: string, value: string}; export type SessionId = string; export type Merchant = {id?: string | undefined, name?: string | undefined, country?: string | undefined, url?: string | undefined}; export type Currency = {label: string, code: string}; export type DynamicLinking = {merchant?: Merchant | undefined, transactionAmount?: {amount: string, exponent: string, currency: Currency} | undefined, convertedAmount?: {amount: string, exponent: string, currency: Currency} | undefined, transactionDate?: unknown | undefined, xid: string, binAcquirer?: string | undefined, ua?: string | undefined, browserIP?: (string | string) | undefined, deviceChannel?: string | undefined, network?: string | undefined, messageCategory?: string | undefined, threeRIInd?: string | undefined, threeDSRequestorAuthenticationInd?: string | undefined, threeDSRequestorDecReqInd?: ('Y' | 'N') | undefined, threeDSRequestorDecMaxTime?: string | undefined, threeDSRequestorAppURL?: string | undefined, cardType?: ('CREDIT' | 'DEBIT') | undefined, deviceOs?: string | undefined, maskedPan?: string | undefined, maskedVPan?: string | undefined, amountInd?: string | undefined, frequencyInd?: string | undefined, recurringDate?: unknown | undefined, recurringExpiry?: unknown | undefined, recurringFrequency?: string | undefined, purchaseInstalData?: string | undefined, purchaseDate?: unknown | undefined, recurringAmount?: {amount: string, exponent: string, currency: Currency} | undefined}; export type AuthenticationMeansData = {generatedChallenges?: string | undefined, generatedOTP?: string | undefined, chosenDevice?: string | undefined, authenticationMethod?: string | undefined, oobAppLabel?: string | undefined, oobAppURL?: string | undefined, friendlyName?: string | undefined, idDevice?: string | undefined, deviceModel?: string | undefined}; export type FreeContext = {[key: string]: string}; export type InitiateRequest = {principal: Principal, expiry?: Expiry | undefined, sessionId: SessionId, cardholderId: string, dynamicLinking: DynamicLinking, authenticationMeans: string, authenticationMeansData?: AuthenticationMeansData | undefined, credentials?: {type: string, value: string} | undefined, callbackURL?: string | undefined, callbackSite?: ('VDM' | 'SCL') | undefined, trustedEnrollmentRequest?: boolean | undefined, freeContext?: FreeContext | undefined, oobAppURLInd?: string | undefined}; export type Signature = string; export type InitiateRequestMessage = {header: Header, body: InitiateRequest, signature?: Signature | undefined}; export type CreateApiInitiateAuthenticationArgs = {Authorization?: string | undefined, Date?: unknown | undefined, Digest?: string | undefined, Signature?: string | undefined, 'x-jws-signature'?: string | undefined, body: InitiateRequestMessage}; export type CreateApiInitiateAuthenticationOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const header = z.object({service: z.string().min(1).max(255), issuerCode: z.string().min(5).max(5), subIssuerCode: z.string().min(5).max(5), requestId: z.string(), keyTag: z.string().min(2).max(2).optional(), iv: z.string().min(24).max(32).optional()}); export const authenticationMeansData = z.object({generatedChallenges: z.string().optional(), generatedOTP: z.string().min(1).max(10).optional(), chosenDevice: z.string().min(1).max(255).optional(), authenticationMethod: z.string().min(2).max(2).optional(), oobAppLabel: z.string().min(1).max(45).optional(), oobAppURL: z.string().min(1).max(2048).optional(), friendlyName: z.string().optional(), idDevice: z.string().optional(), deviceModel: z.string().optional()}); export const transactionId = z.string().min(1).max(50); export const freeContext = z.record(z.string(), z.string().min(1).max(255)); export const device = z.object({id: z.string().min(1).max(50).optional(), value: z.string().min(1).max(255).optional()}); export const initiateResponse = z.object({authenticationMeansData: authenticationMeansData.optional(), trialLeft: z.number().int().optional(), transactionId: transactionId.optional(), freeContext: freeContext.optional(), devices: z.array(device).optional()}); export const signature = z.string(); export const initiateResponseMessage = z.object({header: header, body: initiateResponse, signature: signature.optional()}); 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 }; /** * Initiate the authentication * * POST /initiateAuthentication */ export const createApiInitiateAuthentication = async (args: CreateApiInitiateAuthenticationArgs, options: CreateApiInitiateAuthenticationOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.Date != null) headers.set("Date", String(args.Date)) if (args.Digest != null) headers.set("Digest", String(args.Digest)) if (args.Signature != null) headers.set("Signature", String(args.Signature)) if (args['x-jws-signature'] != null) headers.set("x-jws-signature", String(args['x-jws-signature'])) const url = `${baseUrl.replace(/\/+$/, '')}/initiateAuthentication${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(initiateResponseMessage, await res.json()) };