@tonder.io/ionic-lite-sdk 1.0.1 → 1.0.2-beta.TEC-1207.53fb846

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.
Files changed (43) hide show
  1. package/README.md +38 -3
  2. package/dist/classes/3dsHandler.d.ts +26 -2
  3. package/dist/classes/BaseInlineCheckout.d.ts +12 -9
  4. package/dist/classes/liteCheckout.d.ts +1 -1
  5. package/dist/data/businessApi.d.ts +1 -1
  6. package/dist/data/coreApi.d.ts +15 -0
  7. package/dist/helpers/corePayment.d.ts +60 -0
  8. package/dist/helpers/safeUrl.d.ts +15 -0
  9. package/dist/helpers/sanitize3dsMarkup.d.ts +18 -0
  10. package/dist/helpers/utils.d.ts +1 -0
  11. package/dist/helpers/validations.d.ts +1 -0
  12. package/dist/index.js +1 -1
  13. package/dist/shared/constants/apiEndpoints.d.ts +2 -0
  14. package/dist/shared/utils/appError.d.ts +9 -0
  15. package/dist/types/commons.d.ts +5 -0
  16. package/dist/types/core.d.ts +28 -0
  17. package/jest.config.ts +11 -1
  18. package/package.json +1 -1
  19. package/src/classes/3dsHandler.ts +134 -30
  20. package/src/classes/BaseInlineCheckout.ts +128 -16
  21. package/src/classes/liteCheckout.ts +9 -2
  22. package/src/data/businessApi.ts +13 -6
  23. package/src/data/coreApi.ts +47 -0
  24. package/src/helpers/corePayment.ts +211 -0
  25. package/src/helpers/safeUrl.ts +26 -0
  26. package/src/helpers/sanitize3dsMarkup.ts +133 -0
  27. package/src/helpers/utils.ts +4 -0
  28. package/src/helpers/validations.ts +9 -0
  29. package/src/shared/constants/apiEndpoints.ts +2 -0
  30. package/src/shared/constants/messages.ts +4 -4
  31. package/src/shared/utils/appError.ts +28 -11
  32. package/src/types/commons.ts +5 -0
  33. package/src/types/core.ts +30 -0
  34. package/tests/coreBusinessConfig.test.ts +100 -0
  35. package/tests/corePayment.test.ts +393 -0
  36. package/tests/corePaymentCheckout.test.ts +668 -0
  37. package/tests/coreStartupFailure.test.ts +70 -0
  38. package/tests/redirectToChallenge.test.ts +149 -0
  39. package/tests/sanitize3dsMarkup.test.ts +248 -0
  40. package/tests/secureTokenBoundary.test.ts +81 -0
  41. package/tests/threeDsApiKey.test.ts +41 -0
  42. package/tests/threeDsCore.test.ts +444 -0
  43. package/tests/threeDsPolling.test.ts +45 -0
@@ -0,0 +1,211 @@
1
+ import { get } from "./get";
2
+ import { IItem } from "../types/checkout";
3
+ import { ICoreTransactionResponse } from "../types/core";
4
+
5
+ const GUARDIAN_DECLINE_CODE = "FH01";
6
+
7
+ const RESOLVED_STATUSES = ["Success", "Authorized", "Pending", "Processing"];
8
+
9
+ const CARD_FIELDS = [
10
+ "card_number",
11
+ "cvv",
12
+ "expiration_month",
13
+ "expiration_year",
14
+ "cardholder_name",
15
+ ] as const;
16
+
17
+ export type CoreCheckoutInput = {
18
+ amount: number;
19
+ currency?: string;
20
+ reference: string | number;
21
+ customer: Record<string, any> | undefined;
22
+ /** The vault field tokens of a new card, or `{ skyflow_id }` for a saved one. */
23
+ card: Record<string, any>;
24
+ metadata?: Record<string, any>;
25
+ returnUrl?: string;
26
+ items?: IItem[];
27
+ browserInfo?: Record<string, any>;
28
+ };
29
+
30
+ export type CoreResultContext = { coreBaseUrl: string };
31
+
32
+ export type RebuiltResult = {
33
+ outcome: "resolve" | "reject";
34
+ /** The HTTP status `checkout-router` answered with. */
35
+ status: number;
36
+ statusText?: string;
37
+ body: Record<string, any>;
38
+ };
39
+
40
+ export function newRequestId(): string {
41
+ const webCrypto = globalThis.crypto;
42
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
43
+ return `req_${Date.now()}_${Math.random().toString(36).slice(2, 12)}`;
44
+ }
45
+
46
+ /** The `/process` body Direct API takes, from what the legacy flow put in orders, payments and checkout-router. */
47
+ export function buildCoreProcessBody(input: CoreCheckoutInput) {
48
+ const { card, customer } = input;
49
+ const name = [
50
+ get(customer, "firstName", get(customer, "name", "")),
51
+ get(customer, "lastName", get(customer, "lastname", "")),
52
+ ]
53
+ .filter(Boolean)
54
+ .join(" ");
55
+
56
+ const paymentMethod = card.card_number
57
+ ? {
58
+ type: "CARD",
59
+ ...Object.fromEntries(CARD_FIELDS.map((field) => [field, card[field]])),
60
+ }
61
+ : { type: "CARD", token: card.skyflow_id };
62
+
63
+ return {
64
+ operation_type: "payment",
65
+ amount: input.amount,
66
+ currency: input.currency,
67
+ client_reference: String(input.reference),
68
+ customer: {
69
+ name,
70
+ email: get(customer, "email", ""),
71
+ phone: get(customer, "phone", undefined),
72
+ identification: get(customer, "identification", undefined),
73
+ },
74
+ payment_method: paymentMethod,
75
+ metadata: input.metadata,
76
+ return_url: input.returnUrl,
77
+ items: input.items,
78
+ browser_info: input.browserInfo,
79
+ };
80
+ }
81
+
82
+ function legacyId(id: string | undefined): string | number | undefined {
83
+ return id !== undefined && /^\d+$/.test(id) ? Number(id) : id;
84
+ }
85
+
86
+ // A core payment is verified and refunded through the core, by the payment's public id.
87
+ function buildActions(transaction: ICoreTransactionResponse, ctx: CoreResultContext) {
88
+ return [
89
+ {
90
+ name: "verify_transaction_status",
91
+ url: `${ctx.coreBaseUrl}/transactions/v1/${transaction.id}`,
92
+ method: "GET",
93
+ },
94
+ {
95
+ name: "refund_transaction",
96
+ url: `${ctx.coreBaseUrl}/transactions/v1/process`,
97
+ method: "POST",
98
+ body: { operation_type: "refund", original_transaction_id: transaction.id },
99
+ },
100
+ ];
101
+ }
102
+
103
+ function declinedBody(transaction: ICoreTransactionResponse, ctx: CoreResultContext) {
104
+ const routing = transaction.routing;
105
+ const rejected = routing?.rejected_psp_responses ?? [];
106
+ const hard = routing?.decline_type === "Hard";
107
+ return {
108
+ status: "404",
109
+ message: hard ? "Hard decline" : transaction.decline_reason ?? "Transaction declined",
110
+ checkout_id: routing?.checkout_id,
111
+ is_route_finished: routing?.is_route_finished,
112
+ transaction_status: transaction.status,
113
+ transaction_id: legacyId(transaction.transaction_id),
114
+ payment_id: transaction.payment_id,
115
+ provider: transaction.provider,
116
+ decline_code: transaction.decline_code,
117
+ psp_response: hard ? rejected[rejected.length - 1] : rejected,
118
+ actions: buildActions(transaction, ctx),
119
+ };
120
+ }
121
+
122
+ function guardianBody(transaction: ICoreTransactionResponse) {
123
+ return {
124
+ status: "200",
125
+ message: transaction.decline_reason ?? "High risk transaction blocked",
126
+ checkout_id: transaction.routing?.checkout_id,
127
+ transaction_status: "Declined",
128
+ transaction_id: transaction.transaction_id,
129
+ payment_id: transaction.payment_id,
130
+ provider: transaction.provider,
131
+ amount: transaction.amount,
132
+ currency: transaction.currency,
133
+ psp_response: transaction.psp_response,
134
+ decline_code: transaction.decline_code,
135
+ };
136
+ }
137
+
138
+ function approvedBody(transaction: ICoreTransactionResponse, ctx: CoreResultContext) {
139
+ return {
140
+ status: "200",
141
+ message: "Success",
142
+ checkout_id: transaction.routing?.checkout_id,
143
+ is_route_finished: transaction.routing?.is_route_finished,
144
+ transaction_status: transaction.status,
145
+ transaction_id: legacyId(transaction.transaction_id),
146
+ payment_id: transaction.payment_id,
147
+ provider: transaction.provider,
148
+ next_action: transaction.next_action ?? {},
149
+ psp_response: transaction.psp_response,
150
+ actions: buildActions(transaction, ctx),
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Rebuilds what `checkout-router` answered for the same payment, from the core's answer:
156
+ * a body to resolve `payment()` with, or the 4xx body it rejected with.
157
+ */
158
+ export function rebuildCheckoutResult(
159
+ httpStatus: number,
160
+ body: any,
161
+ ctx: CoreResultContext,
162
+ statusText?: string,
163
+ ): RebuiltResult {
164
+ if (httpStatus === 402 && body?.error?.code === "payment_declined") {
165
+ return {
166
+ outcome: "reject",
167
+ status: 404,
168
+ body: { status: "404", message: "Error", psp_response: [], is_route_finished: true },
169
+ };
170
+ }
171
+ // Every other refusal of the core, in the shape and with the status text checkout-router used.
172
+ if (httpStatus >= 400) {
173
+ return {
174
+ outcome: "reject",
175
+ status: httpStatus,
176
+ statusText,
177
+ body: buildCheckoutRouterErrorBody(httpStatus, body),
178
+ };
179
+ }
180
+
181
+ const transaction = body as ICoreTransactionResponse;
182
+ // Only a status the SDK knows to be good resolves; Declined, Failed and any other
183
+ // (Cancelled, Expired, a status added later) answer as a decline.
184
+ if (RESOLVED_STATUSES.includes(transaction.status)) {
185
+ return { outcome: "resolve", status: 200, body: approvedBody(transaction, ctx) };
186
+ }
187
+ if (transaction.status === "Declined" && transaction.decline_code === GUARDIAN_DECLINE_CODE) {
188
+ return { outcome: "resolve", status: 200, body: guardianBody(transaction) };
189
+ }
190
+ return { outcome: "reject", status: 404, body: declinedBody(transaction, ctx) };
191
+ }
192
+
193
+ /** What support needs to match a refusal with the core's own log; it never reaches the merchant. */
194
+ export function describeCoreRefusal(httpStatus: number, body: any) {
195
+ return {
196
+ status: httpStatus,
197
+ code: body?.error?.code,
198
+ type: body?.error?.type,
199
+ request_id: body?.request_id,
200
+ };
201
+ }
202
+
203
+ /** The body checkout-router answered on a failed start: its own shape, never the core's raw error. */
204
+ function buildCheckoutRouterErrorBody(status: number, body: any) {
205
+ return {
206
+ status: String(status),
207
+ message: body?.error?.message ?? "Error",
208
+ psp_response: [],
209
+ is_route_finished: false,
210
+ };
211
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Scheme check shared by every sink a URL from the 3DS payload can reach: the
3
+ * attributes of the ACS markup and the challenge redirect.
4
+ *
5
+ * Resolution goes through the platform's URL parser rather than a prefix match. The
6
+ * parser strips the leading whitespace and the embedded tabs and newlines a crafted
7
+ * string uses to hide its scheme, and lowercases the result, so "JavaScript:" and a
8
+ * scheme followed by a comment that merely contains the word http are both classified
9
+ * on what they actually are.
10
+ *
11
+ * https only. A production ACS is always https — the card schemes require it — so
12
+ * allowing http would only add a downgrade path for someone on the network to serve
13
+ * the challenge. If a local sandbox over http is ever needed, widen this deliberately.
14
+ */
15
+
16
+ const ALLOWED_SCHEMES = new Set(["https:"]);
17
+
18
+ export function isHttpsUrl(value: unknown): boolean {
19
+ if (typeof value !== "string") return false;
20
+
21
+ try {
22
+ return ALLOWED_SCHEMES.has(new URL(value, document.baseURI).protocol);
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The 3DS Method step cannot be rendered as text: the ACS sends back a hidden form
3
+ * and the iframe it targets, and the flow submits that form by id. So the markup has
4
+ * to reach the DOM as markup, and the only safe handling is to strip what the step
5
+ * never needs — script execution, event handlers, CSS, beacons and non-https URLs —
6
+ * before insertion.
7
+ *
8
+ * Parsing happens in a document with no browsing context, so nothing loads, navigates
9
+ * or executes while the markup is being inspected. That inertness does not survive the
10
+ * move: a script carried out of a parsed document into a live one has not been marked
11
+ * already-started, so insertion runs it. Removal is the protection, never inertness.
12
+ */
13
+
14
+ import { isHttpsUrl } from "./safeUrl";
15
+
16
+ const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
17
+
18
+ /**
19
+ * Compared against localName, which is lowercase in every namespace. tagName is not:
20
+ * the parser only uppercases it for HTML elements, so an SVG script reports "script"
21
+ * and slips past an uppercase set.
22
+ */
23
+ const FORBIDDEN_ELEMENTS = new Set([
24
+ "script",
25
+ "object",
26
+ "embed",
27
+ "applet",
28
+ "link",
29
+ "meta",
30
+ "base",
31
+ // A style block is not scoped to the fragment it arrived in. Its selectors reach the
32
+ // merchant's own card fields, and url() in a matched rule turns an attribute value
33
+ // into a request to wherever the ACS payload chose.
34
+ "style",
35
+ // A template's content is a separate fragment that querySelectorAll never descends
36
+ // into, so its markup would travel into the page unsanitized. The step has no use
37
+ // for one.
38
+ "template",
39
+ ]);
40
+
41
+ /**
42
+ * Dropped outright, because no value of theirs is one this step has a use for and
43
+ * none of them is a plain URL the scheme check could judge.
44
+ */
45
+ const FORBIDDEN_ATTRIBUTES = new Set([
46
+ "srcdoc",
47
+ // The caller hides its own container, so the step needs no CSS of its own. Left in,
48
+ // a style attribute still positions an element over the merchant's card fields.
49
+ "style",
50
+ // A space-separated list of URLs the browser POSTs to on click. https tells us
51
+ // nothing here: exfiltration to an attacker's origin is https too, so the scheme
52
+ // check would pass the attack and reject only the benign multi-URL form.
53
+ "ping",
54
+ // A candidate list ("a.png 1x, b.png 2x"), not a URL. The parser folds the whole
55
+ // string into one path and calls it https, so a scheme check reads as a guarantee
56
+ // while inspecting none of the candidates.
57
+ "srcset",
58
+ ]);
59
+
60
+ // Single-URL attributes, each judged on its own resolved scheme.
61
+ const URL_ATTRIBUTES = new Set([
62
+ "src",
63
+ "href",
64
+ "action",
65
+ "formaction",
66
+ "data",
67
+ "poster",
68
+ "background",
69
+ ]);
70
+
71
+ // An attribute may legitimately hold nothing, or point an iframe at the blank page;
72
+ // neither carries anywhere to navigate to. Everything else goes through the shared
73
+ // scheme check.
74
+ function isSafeAttributeUrl(value: string): boolean {
75
+ const candidate = value.trim();
76
+ if (candidate === "") return true;
77
+ if (candidate.toLowerCase() === "about:blank") return true;
78
+
79
+ return isHttpsUrl(candidate);
80
+ }
81
+
82
+ /**
83
+ * Matches on localName and removes by node, so a prefixed attribute is judged on what
84
+ * it does rather than on how it was spelled: in foreign content the parser keeps the
85
+ * prefix, and "xlink:href" as a qualified name matches neither the handler test nor the
86
+ * URL set. The element walk below already keeps foreign content out of the fragment —
87
+ * this does not lean on it, so relaxing that rule cannot silently reopen the hole.
88
+ */
89
+ function sanitizeElement(element: Element): void {
90
+ for (const attribute of Array.from(element.attributes)) {
91
+ const name = attribute.localName.toLowerCase();
92
+
93
+ if (name.startsWith("on") || FORBIDDEN_ATTRIBUTES.has(name)) {
94
+ element.removeAttributeNode(attribute);
95
+ continue;
96
+ }
97
+
98
+ if (URL_ATTRIBUTES.has(name) && !isSafeAttributeUrl(attribute.value)) {
99
+ element.removeAttributeNode(attribute);
100
+ }
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Parses 3DS markup and returns a fragment owned by the current document, with every
106
+ * executable construct removed. Throws nothing: unparseable markup yields an empty
107
+ * fragment, which the caller treats as a missing redirection.
108
+ */
109
+ export function sanitize3dsMarkup(markup: string): DocumentFragment {
110
+ const parsed = new DOMParser().parseFromString(markup, "text/html");
111
+
112
+ for (const element of Array.from(parsed.body.querySelectorAll("*"))) {
113
+ // Foreign content goes entirely. SVG and MathML are where the parser's exceptions
114
+ // live — case-preserving names, prefixed attributes, SMIL animating an href into a
115
+ // javascript: URL, integration points that switch parsing back to HTML mid-subtree
116
+ // — and each one is a separate way past a rule written for HTML. The step this
117
+ // sanitizer exists for is a hidden form and its hidden target iframe, so nothing it
118
+ // needs is out there to lose.
119
+ if (element.namespaceURI !== HTML_NAMESPACE || FORBIDDEN_ELEMENTS.has(element.localName)) {
120
+ element.remove();
121
+ continue;
122
+ }
123
+
124
+ sanitizeElement(element);
125
+ }
126
+
127
+ const fragment = document.createDocumentFragment();
128
+ for (const node of Array.from(parsed.body.childNodes)) {
129
+ fragment.appendChild(document.importNode(node, true));
130
+ }
131
+
132
+ return fragment;
133
+ }
@@ -23,6 +23,10 @@ export const getBusinessId = (merchantData: any) => {
23
23
  : "";
24
24
  };
25
25
 
26
+ // The backends take a card payment method in any case; a card payment is the one with none.
27
+ export const isCardPaymentMethod = (paymentMethod?: string) =>
28
+ !paymentMethod || paymentMethod.toLowerCase() === "card";
29
+
26
30
  const clearSpace = (text: string) => {
27
31
  return text.trim().replace(/\s+/g, "");
28
32
  };
@@ -1,3 +1,12 @@
1
+ // The secure token crosses into the SDK straight from an HTTP response body and is
2
+ // reused verbatim as an Authorization header value on every authenticated call. Only
3
+ // visible ASCII can travel in a header value, so anything else - whitespace, control
4
+ // characters, CR/LF, non-ASCII - is rejected here rather than deep inside fetch. The
5
+ // token format itself is deliberately not constrained, so it can change server-side.
6
+ export function validateSecureToken(secureToken: unknown): secureToken is string {
7
+ return typeof secureToken === "string" && /^[\x21-\x7E]+$/.test(secureToken);
8
+ }
9
+
1
10
  export function validateCardNumber(cardNumber: string) {
2
11
  const regex = /^\d{12,19}$/;
3
12
  return regex.test(cardNumber) && luhnCheck(cardNumber);
@@ -15,6 +15,8 @@ export const API_ENDPOINTS = Object.freeze({
15
15
  TELEMETRY: "/telemetry/v1/events",
16
16
  ACQ_SUBSCRIPTION_TOKEN: "/acq-kushki/subscription/token",
17
17
  ACQ_SUBSCRIPTION_CREATE: "/acq-kushki/subscription/create",
18
+ CORE_BUSINESS_CONFIG: "/transactions/v1/business/config",
19
+ CORE_PROCESS: "/transactions/v1/process",
18
20
  });
19
21
 
20
22
  /**
@@ -72,9 +72,9 @@ export const MESSAGES_EN: Record<string, string> = {
72
72
  [ErrorKeyEnum.CREATE_ERROR]: 'Error creating the SDK.',
73
73
  [ErrorKeyEnum.FETCH_TRANSACTION_ERROR]: 'Error retrieving the transaction.',
74
74
  [ErrorKeyEnum.THREEDS_REDIRECTION_ERROR]:
75
- 'Ocurrió un error durante la redirección de 3DS.',
75
+ 'An error occurred during the 3DS redirection.',
76
76
  [ErrorKeyEnum.REMOVE_SDK_ERROR]:
77
- 'Ocurrió un error removiendo la instancia del SDK.',
77
+ 'An error occurred while removing the SDK instance.',
78
78
  };
79
79
 
80
80
  export const MESSAGES_ES = {
@@ -135,7 +135,7 @@ export const MESSAGES_ES = {
135
135
  [ErrorKeyEnum.CREATE_ERROR]: 'Error creando el SDK.',
136
136
  [ErrorKeyEnum.FETCH_TRANSACTION_ERROR]: 'Error obteniendo la transacción',
137
137
  [ErrorKeyEnum.THREEDS_REDIRECTION_ERROR]:
138
- 'An error occurred during the 3DS redirection.',
138
+ 'Ocurrió un error durante la redirección de 3DS.',
139
139
  [ErrorKeyEnum.REMOVE_SDK_ERROR]:
140
- 'An error occurred while removing the SDK instance.',
140
+ 'Ocurrió un error removiendo la instancia del SDK.',
141
141
  };
@@ -252,27 +252,33 @@ function buildPublicAppErrorSync(
252
252
  });
253
253
  }
254
254
 
255
- async function buildPublicAppErrorFromHttpResponse(
256
- data: IBuildPublicAppErrorInput & { response: Response },
257
- ): Promise<AppError> {
258
- const body = await parseResponseBody(data.response);
259
-
255
+ /**
256
+ * Builds the error of an HTTP answer that was already read, or rebuilt by the SDK from
257
+ * another backend's answer, with the same shape a failed `fetch` produces.
258
+ */
259
+ export function buildPublicAppErrorFromAnswer(
260
+ data: IBuildPublicAppErrorInput & {
261
+ status: number;
262
+ statusText?: string;
263
+ body?: unknown;
264
+ },
265
+ ): AppError {
260
266
  const originalError: Record<string, unknown> = {
261
- status: data.response.status,
267
+ status: data.status,
262
268
  };
263
269
 
264
- if (data.response.statusText) {
265
- originalError.statusText = data.response.statusText;
270
+ if (data.statusText) {
271
+ originalError.statusText = data.statusText;
266
272
  }
267
273
 
268
- if (body !== undefined) {
269
- originalError.body = body;
274
+ if (data.body !== undefined) {
275
+ originalError.body = data.body;
270
276
  }
271
277
 
272
278
  return new AppError({
273
279
  errorCode: data.errorCode,
274
280
  message: data.message,
275
- statusCode: data.statusCode ?? data.response.status,
281
+ statusCode: data.statusCode ?? data.status,
276
282
  details:
277
283
  data.details?.systemError !== undefined
278
284
  ? { systemError: data.details.systemError }
@@ -282,6 +288,17 @@ async function buildPublicAppErrorFromHttpResponse(
282
288
  });
283
289
  }
284
290
 
291
+ async function buildPublicAppErrorFromHttpResponse(
292
+ data: IBuildPublicAppErrorInput & { response: Response },
293
+ ): Promise<AppError> {
294
+ return buildPublicAppErrorFromAnswer({
295
+ ...data,
296
+ status: data.response.status,
297
+ statusText: data.response.statusText,
298
+ body: await parseResponseBody(data.response),
299
+ });
300
+ }
301
+
285
302
  export function buildPublicAppError(
286
303
  data: IBuildPublicAppErrorInput & { response: Response },
287
304
  error?: unknown,
@@ -46,6 +46,11 @@ export type Business = {
46
46
  reference: number;
47
47
  is_installments_available: boolean;
48
48
  cardonfile_keys?: CardOnFileKeys;
49
+ /**
50
+ * The merchant's switch already evaluated with the kill switch: when true, card
51
+ * payments are charged by the core instead of the legacy flow.
52
+ */
53
+ core_payments_enabled?: boolean;
49
54
  };
50
55
 
51
56
  export type Customer = {
@@ -0,0 +1,30 @@
1
+ /** Which backend charges and finishes one payment. It is chosen once and never changes. */
2
+ export type PaymentEngine = "core" | "legacy";
3
+
4
+ export interface ICoreRouting {
5
+ checkout_id?: string;
6
+ is_route_finished?: boolean;
7
+ decline_type?: "Hard" | "Soft" | null;
8
+ rejected_psp_responses?: Record<string, any>[];
9
+ }
10
+
11
+ /**
12
+ * What the core answers to `/transactions/v1/process` and `/transactions/v1/{id}` for a
13
+ * first-party (`sdk/ionic`) payment: Direct API's body plus the fields the SDK needs to
14
+ * rebuild the result merchants get today.
15
+ */
16
+ export interface ICoreTransactionResponse {
17
+ id: string;
18
+ status: string;
19
+ amount?: number | string;
20
+ currency?: string;
21
+ provider?: string | null;
22
+ next_action?: Record<string, any>;
23
+ decline_code?: string;
24
+ decline_reason?: string;
25
+ payment_id?: number;
26
+ transaction_id?: string;
27
+ routing?: ICoreRouting;
28
+ transaction_status?: string;
29
+ psp_response?: Record<string, any>;
30
+ }
@@ -0,0 +1,100 @@
1
+ import { LiteCheckout } from "../src/classes/liteCheckout";
2
+ import { fetchBusiness } from "../src/data/businessApi";
3
+ import { AppError } from "../src/shared/utils/appError";
4
+ import { ErrorKeyEnum } from "../src/shared/enum/ErrorKeyEnum";
5
+
6
+ const API_KEY = "merchant-api-key";
7
+ const CORE_STAGE = "https://api-stage.tonder.io";
8
+ const CORE_PRODUCTION = "https://api.tonder.io";
9
+
10
+ const CONFIG_BODY = {
11
+ business: { pk: 7, name: "Shop" },
12
+ openpay_keys: { merchant_id: "", public_key: "" },
13
+ vault_id: "vault",
14
+ vault_url: "https://vault.example.com",
15
+ reference: "TNDR-1",
16
+ core_payments_enabled: true,
17
+ };
18
+
19
+ function okJson(body: unknown) {
20
+ return { ok: true, status: 200, json: async () => body };
21
+ }
22
+
23
+ describe("business configuration read from the core", () => {
24
+ let fetchMock: jest.Mock;
25
+
26
+ beforeEach(() => {
27
+ fetchMock = jest.fn().mockResolvedValue(okJson(CONFIG_BODY));
28
+ (global as any).fetch = fetchMock;
29
+ });
30
+
31
+ it("calls the core's business config route with the API key in the header only", async () => {
32
+ const signal = new AbortController().signal;
33
+
34
+ const business = await fetchBusiness(CORE_STAGE, API_KEY, signal);
35
+
36
+ expect(business).toEqual(CONFIG_BODY);
37
+ const [url, init] = fetchMock.mock.calls[0];
38
+ expect(url).toBe(`${CORE_STAGE}/transactions/v1/business/config`);
39
+ expect(url).not.toContain(API_KEY);
40
+ expect(init.method ?? "GET").toBe("GET");
41
+ expect(init.headers.Authorization).toBe(`Token ${API_KEY}`);
42
+ expect(init.signal).toBe(signal);
43
+ });
44
+
45
+ it("rejects instead of handing an error body over as the configuration", async () => {
46
+ fetchMock.mockResolvedValue({
47
+ ok: false,
48
+ status: 403,
49
+ statusText: "Forbidden",
50
+ clone() {
51
+ return this;
52
+ },
53
+ json: async () => ({ error: { code: "business_not_active" } }),
54
+ });
55
+
56
+ await expect(
57
+ fetchBusiness(CORE_STAGE, API_KEY, new AbortController().signal),
58
+ ).rejects.toMatchObject({
59
+ code: ErrorKeyEnum.FETCH_BUSINESS_ERROR,
60
+ statusCode: 403,
61
+ });
62
+ });
63
+
64
+ it.each([
65
+ ["stage", CORE_STAGE],
66
+ ["production", CORE_PRODUCTION],
67
+ ] as const)("LiteCheckout starts up against the %s core", async (mode, base) => {
68
+ const checkout = new LiteCheckout({ mode, apiKey: API_KEY });
69
+
70
+ const merchant = await checkout._fetchMerchantData();
71
+
72
+ expect(merchant).toEqual(CONFIG_BODY);
73
+ expect(fetchMock.mock.calls[0][0]).toBe(`${base}/transactions/v1/business/config`);
74
+ expect(fetchMock).toHaveBeenCalledTimes(1);
75
+ });
76
+
77
+ it("getBusiness() answers the configuration of the core", async () => {
78
+ const checkout = new LiteCheckout({ mode: "stage", apiKey: API_KEY });
79
+
80
+ await expect(checkout.getBusiness()).resolves.toEqual(CONFIG_BODY);
81
+ expect(fetchMock.mock.calls[0][0]).toBe(`${CORE_STAGE}/transactions/v1/business/config`);
82
+ });
83
+
84
+ it("getBusiness() keeps its public error code when the core refuses", async () => {
85
+ fetchMock.mockResolvedValue({
86
+ ok: false,
87
+ status: 500,
88
+ clone() {
89
+ return this;
90
+ },
91
+ json: async () => ({}),
92
+ });
93
+ const checkout = new LiteCheckout({ mode: "stage", apiKey: API_KEY });
94
+
95
+ const failure = await checkout.getBusiness().catch((e) => e);
96
+
97
+ expect(failure).toBeInstanceOf(AppError);
98
+ expect(failure.code).toBe(ErrorKeyEnum.FETCH_BUSINESS_ERROR);
99
+ });
100
+ });