@payriff-sdk/node 0.1.3 → 0.3.0

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.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # Payriff Node.js SDK
2
2
 
3
- Node.js client for the Payriff merchant API: orders, direct (host-to-host) card payments, saved cards,
3
+ Node.js client for the Payriff merchant API: orders, saved-card payments, saved cards,
4
4
  transactions, payouts and invoices.
5
5
 
6
6
  - Node.js 20 or newer
7
7
  - No runtime dependencies
8
8
  - TypeScript types included
9
- - Talks to `https://api.payriff.com`
9
+ - Talks to `https://api.payriff.com` (Azerbaijan) or `https://api.gccpay.sa` (Saudi Arabia)
10
10
 
11
11
  ## Installation
12
12
 
@@ -21,7 +21,7 @@ Works with any Node.js framework (Express, NestJS, Fastify, Next.js).
21
21
  ```ts
22
22
  import { Payriff } from '@payriff-sdk/node';
23
23
 
24
- const payriff = new Payriff({ appKey: process.env.PAYRIFF_APP_KEY! });
24
+ const payriff = new Payriff({ secretKey: process.env.PAYRIFF_SECRET_KEY! });
25
25
 
26
26
  const order = await payriff.orders.create({
27
27
  amount: 10,
@@ -42,19 +42,36 @@ Create one `Payriff` instance and reuse it.
42
42
 
43
43
  | Option | Required | Default | Notes |
44
44
  |---|---|---|---|
45
- | `appKey` | yes | — | Application key from the Payriff dashboard. |
45
+ | `secretKey` | yes | — | Secret key from the Payriff dashboard. |
46
46
  | `merchantId` | for payouts and invoices | — | Merchant ID (e.g. `ES1000000`). |
47
47
  | `timeout` | no | `60000` | Request timeout in milliseconds. Bank operations can take tens of seconds. |
48
- | `cardEncryptionKey` | no | built-in Payriff key | Only if Payriff rotates the card-encryption key. Base64 or PEM. |
48
+ | `region` | no | `'azerbaijan'` | API region: `'azerbaijan'` or `'ksa'`. Sets the base URL and the default currency. |
49
+ | `baseUrl` | no | from `region` | Override the API URL, e.g. for testing. The currency still comes from `region`. |
49
50
 
50
- Keep the app key in an environment variable or secret store. Never commit it.
51
+ Keep the secret key in an environment variable or secret store. Never commit it.
52
+ Versions before 0.3.0 called it the app key; the `appKey` option still works but is deprecated.
53
+
54
+ ### Saudi Arabia (KSA)
55
+
56
+ ```ts
57
+ const payriff = new Payriff({ secretKey: process.env.PAYRIFF_SECRET_KEY!, region: 'ksa' });
58
+ ```
59
+
60
+ | Region | API | Default currency |
61
+ |---|---|---|
62
+ | `'azerbaijan'` | `https://api.payriff.com` | `AZN` |
63
+ | `'ksa'` | `https://api.gccpay.sa` | `SAR` |
64
+
65
+ Use the secret key from the dashboard of the same region (`dashboard.gccpay.sa` for KSA).
66
+ `'saudi'` still works but is deprecated; use `'ksa'`.
67
+ A `currency` passed on a request always wins over the region default.
51
68
 
52
69
  ## Orders
53
70
 
54
71
  ```ts
55
72
  const created = await payriff.orders.create({
56
73
  amount: 25,
57
- currency: 'AZN', // default AZN
74
+ currency: 'AZN', // default: the region currency
58
75
  operation: 'PRE_AUTH', // default PURCHASE
59
76
  language: 'AZ',
60
77
  description: 'Booking #77',
@@ -72,42 +89,16 @@ await payriff.orders.expire(created.orderId); // cancel an
72
89
  const receiptPdf: Buffer = await payriff.orders.downloadReceipt(created.orderId);
73
90
  ```
74
91
 
92
+ `created.clientSecret` is set only when the application has an active publishable key; otherwise it
93
+ is `undefined`. Pass it with the order ID to the Payriff web or mobile SDK, which takes the payment in
94
+ the customer's browser or app. Treat it as a secret: don't log it or put it in URLs.
95
+
75
96
  `paymentStatus` is a string such as `APPROVED`, `DECLINED`, `PREAUTH_APPROVED` or `REFUNDED`. Values that
76
97
  this SDK version does not know yet are passed through unchanged.
77
98
 
78
- Amounts are JavaScript numbers in major units (`10.5` = 10.50 AZN).
79
-
80
- ## Direct payments (host-to-host)
81
-
82
- You collect the card details yourself, and the SDK encrypts them before sending
83
- (AES-256-GCM + RSA-OAEP). Raw card data never leaves your server in clear text, but your
84
- systems still handle card data, so PCI DSS requirements apply to you.
85
-
86
- ```ts
87
- const result = await payriff.payments.directPay({
88
- amount: 1,
89
- description: 'Order #1002',
90
- callbackUrl: 'https://shop.example/payriff/callback',
91
- requestRrn: 'order-1002',
92
- card: {
93
- pan: '4169 7413 3015 1979',
94
- cardHolder: 'JOHN DOE',
95
- expiryMonth: '11',
96
- expiryYear: '27',
97
- cvv: '123',
98
- },
99
- });
100
-
101
- if (result.redirect) {
102
- // 3-D Secure: send the customer's browser to result.redirectUrl.
103
- // The final status arrives via your callback or payriff.orders.get(result.orderId).
104
- }
105
- ```
106
-
107
- The SDK strips spaces and dashes from the card number, pads the month (`1` → `01`), expands a 2-digit
108
- year (`27` → `2027`) and rejects malformed values before any network call.
99
+ Amounts are JavaScript numbers in major units (`10.5` = 10.50 AZN or SAR).
109
100
 
110
- ### Charging a saved card
101
+ ## Charging a saved card
111
102
 
112
103
  ```ts
113
104
  const charge = await payriff.payments.autoPay({
@@ -161,7 +152,7 @@ Payouts require `merchantId` on the client.
161
152
 
162
153
  ```ts
163
154
  const payriff = new Payriff({
164
- appKey: process.env.PAYRIFF_APP_KEY!,
155
+ secretKey: process.env.PAYRIFF_SECRET_KEY!,
165
156
  merchantId: process.env.PAYRIFF_MERCHANT_ID,
166
157
  });
167
158
 
@@ -227,7 +218,7 @@ and `responseId` (quote it when contacting support).
227
218
 
228
219
  | Error | When |
229
220
  |---|---|
230
- | `AuthenticationError` | App key rejected (`14010`, `14013`, `14014`, `14015`) |
221
+ | `AuthenticationError` | Secret key rejected (`14010`, `14013`, `14014`, `14015`) |
231
222
  | `ValidationError` | Invalid request (`15400` or HTTP 400) |
232
223
  | `RequestRejectedError` | Business refusal (`01000`), e.g. application under review |
233
224
  | `InsufficientBalanceError` | Not enough wallet balance for a payout (`01200`) |
package/dist/client.d.ts CHANGED
@@ -4,11 +4,14 @@ import { OrdersApi } from './resources/orders';
4
4
  import { PaymentsApi } from './resources/payments';
5
5
  import { PayoutsApi } from './resources/payouts';
6
6
  import { TransactionsApi } from './resources/transactions';
7
+ import type { Region } from './types';
7
8
  export interface PayriffOptions {
8
- appKey: string;
9
+ secretKey?: string;
10
+ /** @deprecated Use secretKey. */
11
+ appKey?: string;
9
12
  merchantId?: string;
10
13
  timeout?: number;
11
- cardEncryptionKey?: string;
14
+ region?: Region;
12
15
  baseUrl?: string;
13
16
  }
14
17
  export declare class Payriff {
package/dist/client.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Payriff = void 0;
4
- const card_1 = require("./card");
5
4
  const cards_1 = require("./resources/cards");
6
5
  const invoices_1 = require("./resources/invoices");
7
6
  const orders_1 = require("./resources/orders");
@@ -9,7 +8,11 @@ const payments_1 = require("./resources/payments");
9
8
  const payouts_1 = require("./resources/payouts");
10
9
  const transactions_1 = require("./resources/transactions");
11
10
  const transport_1 = require("./transport");
12
- const PRODUCTION_URL = 'https://api.payriff.com';
11
+ const REGIONS = {
12
+ azerbaijan: { baseUrl: 'https://api.payriff.com', currency: 'AZN' },
13
+ ksa: { baseUrl: 'https://api.gccpay.sa', currency: 'SAR' },
14
+ saudi: { baseUrl: 'https://api.gccpay.sa', currency: 'SAR' },
15
+ };
13
16
  class Payriff {
14
17
  orders;
15
18
  payments;
@@ -18,25 +21,29 @@ class Payriff {
18
21
  payouts;
19
22
  invoices;
20
23
  constructor(options) {
21
- if (!options || typeof options.appKey !== 'string' || options.appKey.trim() === '') {
22
- throw new TypeError('appKey is required');
24
+ const secretKey = options?.secretKey ?? options?.appKey;
25
+ if (typeof secretKey !== 'string' || secretKey.trim() === '') {
26
+ throw new TypeError('secretKey is required');
23
27
  }
24
28
  const timeout = options.timeout ?? 60_000;
25
29
  if (!Number.isFinite(timeout) || timeout <= 0)
26
30
  throw new RangeError('timeout must be a positive number of milliseconds');
31
+ const regionName = options.region ?? 'azerbaijan';
32
+ if (!Object.hasOwn(REGIONS, regionName))
33
+ throw new RangeError(`unknown region: ${regionName}`);
34
+ const region = REGIONS[regionName];
27
35
  const transport = new transport_1.Transport({
28
- baseUrl: options.baseUrl ?? PRODUCTION_URL,
29
- appKey: options.appKey,
36
+ baseUrl: options.baseUrl ?? region.baseUrl,
37
+ secretKey,
30
38
  merchantId: options.merchantId,
31
39
  timeout,
32
40
  });
33
- const cardEncryptor = new card_1.CardEncryptor((0, card_1.parsePublicKey)(options.cardEncryptionKey ?? card_1.PRODUCTION_CARD_ENCRYPTION_KEY));
34
- this.orders = new orders_1.OrdersApi(transport);
35
- this.payments = new payments_1.PaymentsApi(transport, cardEncryptor);
41
+ this.orders = new orders_1.OrdersApi(transport, region.currency);
42
+ this.payments = new payments_1.PaymentsApi(transport, region.currency);
36
43
  this.cards = new cards_1.CardsApi(transport);
37
44
  this.transactions = new transactions_1.TransactionsApi(transport);
38
45
  this.payouts = new payouts_1.PayoutsApi(transport);
39
- this.invoices = new invoices_1.InvoicesApi(transport);
46
+ this.invoices = new invoices_1.InvoicesApi(transport, region.currency);
40
47
  }
41
48
  }
42
49
  exports.Payriff = Payriff;
@@ -1,8 +1,9 @@
1
1
  import type { Transport } from '../transport';
2
- import type { Invoice, InvoiceCreateParams, InvoiceDetails } from '../types';
2
+ import type { Currency, Invoice, InvoiceCreateParams, InvoiceDetails } from '../types';
3
3
  export declare class InvoicesApi {
4
4
  private readonly transport;
5
- constructor(transport: Transport);
5
+ private readonly defaultCurrency;
6
+ constructor(transport: Transport, defaultCurrency: Currency);
6
7
  create(params: InvoiceCreateParams): Promise<Invoice>;
7
8
  get(invoiceUuid: string): Promise<InvoiceDetails>;
8
9
  }
@@ -4,8 +4,10 @@ exports.InvoicesApi = void 0;
4
4
  const util_1 = require("../util");
5
5
  class InvoicesApi {
6
6
  transport;
7
- constructor(transport) {
7
+ defaultCurrency;
8
+ constructor(transport, defaultCurrency) {
8
9
  this.transport = transport;
10
+ this.defaultCurrency = defaultCurrency;
9
11
  }
10
12
  async create(params) {
11
13
  (0, util_1.required)(params, 'params');
@@ -19,7 +21,7 @@ class InvoicesApi {
19
21
  body: (0, util_1.compact)({
20
22
  amount: params.amount,
21
23
  amountDynamic: params.amountDynamic,
22
- currencyType: params.currency ?? 'AZN',
24
+ currencyType: params.currency ?? this.defaultCurrency,
23
25
  languageType: params.language,
24
26
  fullName: params.fullName,
25
27
  email: params.email,
@@ -1,8 +1,9 @@
1
1
  import type { Transport } from '../transport';
2
- import type { CompleteParams, CreateOrderParams, CreateOrderResponse, OrderInfo, RefundParams } from '../types';
2
+ import type { CompleteParams, CreateOrderParams, CreateOrderResponse, Currency, OrderInfo, RefundParams } from '../types';
3
3
  export declare class OrdersApi {
4
4
  private readonly transport;
5
- constructor(transport: Transport);
5
+ private readonly defaultCurrency;
6
+ constructor(transport: Transport, defaultCurrency: Currency);
6
7
  create(params: CreateOrderParams): Promise<CreateOrderResponse>;
7
8
  get(orderId: string): Promise<OrderInfo>;
8
9
  getStatus(orderId: string): Promise<OrderInfo>;
@@ -4,14 +4,16 @@ exports.OrdersApi = void 0;
4
4
  const util_1 = require("../util");
5
5
  class OrdersApi {
6
6
  transport;
7
- constructor(transport) {
7
+ defaultCurrency;
8
+ constructor(transport, defaultCurrency) {
8
9
  this.transport = transport;
10
+ this.defaultCurrency = defaultCurrency;
9
11
  }
10
12
  async create(params) {
11
13
  (0, util_1.required)(params, 'params');
12
14
  const body = (0, util_1.compact)({
13
15
  amount: (0, util_1.required)(params.amount, 'amount'),
14
- currency: params.currency ?? 'AZN',
16
+ currency: params.currency ?? this.defaultCurrency,
15
17
  language: params.language,
16
18
  operation: params.operation ?? 'PURCHASE',
17
19
  description: params.description,
@@ -1,10 +1,8 @@
1
- import { type CardEncryptor } from '../card';
2
1
  import type { Transport } from '../transport';
3
- import type { AutoPayParams, AutoPayResponse, DirectPayParams, DirectPayResponse } from '../types';
2
+ import type { AutoPayParams, AutoPayResponse, Currency } from '../types';
4
3
  export declare class PaymentsApi {
5
4
  private readonly transport;
6
- private readonly cardEncryptor;
7
- constructor(transport: Transport, cardEncryptor: CardEncryptor);
8
- directPay(params: DirectPayParams): Promise<DirectPayResponse>;
5
+ private readonly defaultCurrency;
6
+ constructor(transport: Transport, defaultCurrency: Currency);
9
7
  autoPay(params: AutoPayParams): Promise<AutoPayResponse>;
10
8
  }
@@ -1,38 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PaymentsApi = void 0;
4
- const card_1 = require("../card");
5
4
  const util_1 = require("../util");
6
5
  class PaymentsApi {
7
6
  transport;
8
- cardEncryptor;
9
- constructor(transport, cardEncryptor) {
7
+ defaultCurrency;
8
+ constructor(transport, defaultCurrency) {
10
9
  this.transport = transport;
11
- this.cardEncryptor = cardEncryptor;
12
- }
13
- async directPay(params) {
14
- (0, util_1.required)(params, 'params');
15
- const body = (0, util_1.compact)({
16
- amount: (0, util_1.required)(params.amount, 'amount'),
17
- operation: params.operation ?? 'PURCHASE',
18
- currency: params.currency ?? 'AZN',
19
- description: (0, util_1.required)(params.description, 'description'),
20
- callbackUrl: params.callbackUrl,
21
- threeDS: params.threeDS,
22
- customFields: (0, util_1.nonEmpty)(params.customFields),
23
- });
24
- const encrypted = this.cardEncryptor.encrypt((0, card_1.normalizeCard)(params.card));
25
- body.paymentData = {
26
- paymentWay: 'DIRECT',
27
- encryptedMessage: encrypted.encryptedMessage,
28
- cardSave: params.cardSave ?? false,
29
- };
30
- return this.transport.execute({
31
- method: 'POST',
32
- path: '/api/v3/directPay',
33
- headers: { 'X-REQUEST-RRN': params.requestRrn, 'x-secret-key': encrypted.secretKey },
34
- body,
35
- });
10
+ this.defaultCurrency = defaultCurrency;
36
11
  }
37
12
  async autoPay(params) {
38
13
  (0, util_1.required)(params, 'params');
@@ -44,7 +19,7 @@ class PaymentsApi {
44
19
  cardUuid: (0, util_1.required)(params.cardUuid, 'cardUuid'),
45
20
  amount: (0, util_1.required)(params.amount, 'amount'),
46
21
  operation: params.operation ?? 'PURCHASE',
47
- currency: params.currency ?? 'AZN',
22
+ currency: params.currency ?? this.defaultCurrency,
48
23
  description: (0, util_1.required)(params.description, 'description'),
49
24
  callbackUrl: params.callbackUrl,
50
25
  threeDS: params.threeDS,
@@ -9,7 +9,7 @@ export interface ApiRequest {
9
9
  }
10
10
  export interface TransportOptions {
11
11
  baseUrl: string;
12
- appKey: string;
12
+ secretKey: string;
13
13
  merchantId?: string;
14
14
  timeout: number;
15
15
  }
package/dist/transport.js CHANGED
@@ -33,7 +33,7 @@ class Transport {
33
33
  const headers = {
34
34
  Accept: accept,
35
35
  'User-Agent': USER_AGENT,
36
- Authorization: this.options.appKey,
36
+ Authorization: this.options.secretKey,
37
37
  };
38
38
  for (const [name, value] of Object.entries(request.headers ?? {})) {
39
39
  if (value !== undefined)
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export type Currency = 'AZN' | 'USD' | 'EUR' | 'PKR' | 'AED' | 'SAR';
2
+ export type Region = 'azerbaijan' | 'ksa' | 'saudi';
2
3
  export type Language = 'AZ' | 'EN' | 'RU' | 'AR';
3
4
  export type Operation = 'PURCHASE' | 'PRE_AUTH' | 'COMPLETE' | 'REFUND' | 'REVERSE';
4
5
  export type AutoPaymentType = 'NONE' | 'DEFAULT' | 'RECURRING';
@@ -13,13 +14,6 @@ export interface Installment {
13
14
  type: InstallmentProductType;
14
15
  period: InstallmentPeriod;
15
16
  }
16
- export interface CardData {
17
- pan: string;
18
- cardHolder: string;
19
- expiryMonth: string | number;
20
- expiryYear: string | number;
21
- cvv: string;
22
- }
23
17
  export interface CreateOrderParams {
24
18
  amount: number;
25
19
  currency?: Currency;
@@ -49,18 +43,6 @@ export interface CompleteParams {
49
43
  amount?: number;
50
44
  callbackUrl?: string;
51
45
  }
52
- export interface DirectPayParams {
53
- amount: number;
54
- description: string;
55
- card: CardData;
56
- operation?: Operation;
57
- currency?: Currency;
58
- callbackUrl?: string;
59
- threeDS?: boolean;
60
- customFields?: Record<string, string>;
61
- cardSave?: boolean;
62
- requestRrn?: string;
63
- }
64
46
  export interface AutoPayParams {
65
47
  cardUuid: string;
66
48
  amount: number;
@@ -212,6 +194,7 @@ export interface CreateOrderResponse {
212
194
  amount?: number;
213
195
  fee?: number;
214
196
  totalAmount?: number;
197
+ clientSecret?: string;
215
198
  }
216
199
  export interface DirectPayResponse {
217
200
  orderId: string;
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.3";
1
+ export declare const VERSION = "0.3.0";
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '0.1.3';
4
+ exports.VERSION = '0.3.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payriff-sdk/node",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "Node.js client for the Payriff merchant API",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -12,8 +12,8 @@
12
12
  "node": ">=20"
13
13
  },
14
14
  "scripts": {
15
- "build": "tsc -p tsconfig.build.json",
16
- "test": "tsc -p tsconfig.json && node --test \"build/test/**/*.test.js\"",
15
+ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
16
+ "test": "node -e \"require('fs').rmSync('build', { recursive: true, force: true })\" && tsc -p tsconfig.json && node --test build/test/*.test.js",
17
17
  "prepare": "npm run build"
18
18
  },
19
19
  "publishConfig": {
package/dist/card.d.ts DELETED
@@ -1,21 +0,0 @@
1
- import { type KeyObject } from 'node:crypto';
2
- import type { CardData } from './types';
3
- export declare const PRODUCTION_CARD_ENCRYPTION_KEY: string;
4
- export interface NormalizedCard {
5
- pan: string;
6
- cardHolder: string;
7
- expiryYear: string;
8
- expiryMonth: string;
9
- cvv: string;
10
- }
11
- export interface EncryptedCard {
12
- encryptedMessage: string;
13
- secretKey: string;
14
- }
15
- export declare function parsePublicKey(base64OrPem: string): KeyObject;
16
- export declare function normalizeCard(card: CardData): NormalizedCard;
17
- export declare class CardEncryptor {
18
- private readonly publicKey;
19
- constructor(publicKey: KeyObject);
20
- encrypt(card: NormalizedCard): EncryptedCard;
21
- }
package/dist/card.js DELETED
@@ -1,86 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CardEncryptor = exports.PRODUCTION_CARD_ENCRYPTION_KEY = void 0;
4
- exports.parsePublicKey = parsePublicKey;
5
- exports.normalizeCard = normalizeCard;
6
- const node_crypto_1 = require("node:crypto");
7
- const util_1 = require("./util");
8
- exports.PRODUCTION_CARD_ENCRYPTION_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxRq5a+44T6Dac60XmVRQ/7cpPyFsBnamXbJlRVJk8CnES5Re5tVMohyD0hZr'
9
- + '3zcQj+bxodYB4zZpQTPlrXvFBC3zz+rXnGlevxBQ6W2d3QC9q8vWH8p3ZOwTO3qVvDSHH9o+hMMRNbJ7kueq/KZlX/F+bjZ23CZw7iXE'
10
- + 'GQT3HYVYnnHsvpaguYDteWBag2sPPLLsVjeB3zhTfQ7OsWp5XTkDuRwLugHPvs6RHLcwGCnodukWyvwUaEUQR/kMGC+RbMsAIVkcLMP5'
11
- + 'csfR3Xo7Gi98+i44iLN00f7gE8QvEmvv8xDspyTAjDEL1a5gK7TijJ3yLG/Bwa1rr1uskYy7lwIDAQAB';
12
- const AES_KEY_BYTES = 32;
13
- const IV_BYTES = 12;
14
- function parsePublicKey(base64OrPem) {
15
- const body = base64OrPem
16
- .replace('-----BEGIN PUBLIC KEY-----', '')
17
- .replace('-----END PUBLIC KEY-----', '')
18
- .replace(/\s/g, '');
19
- try {
20
- const key = (0, node_crypto_1.createPublicKey)({ key: Buffer.from(body, 'base64'), format: 'der', type: 'spki' });
21
- if (key.asymmetricKeyType !== 'rsa')
22
- throw new Error('not an RSA key');
23
- return key;
24
- }
25
- catch (e) {
26
- throw new TypeError('Invalid RSA public key', { cause: e });
27
- }
28
- }
29
- function normalizeCard(card) {
30
- (0, util_1.required)(card, 'card');
31
- const pan = digits(card.pan, 'pan');
32
- if (pan.length < 12 || pan.length > 19)
33
- throw new TypeError('pan must contain 12-19 digits');
34
- const cardHolder = (0, util_1.required)(card.cardHolder, 'cardHolder').trim();
35
- const expiryMonth = month(card.expiryMonth);
36
- const expiryYear = year(card.expiryYear);
37
- const cvv = digits(card.cvv, 'cvv');
38
- if (cvv.length < 3 || cvv.length > 4)
39
- throw new TypeError('cvv must contain 3-4 digits');
40
- return { pan, cardHolder, expiryYear, expiryMonth, cvv };
41
- }
42
- function digits(value, field) {
43
- const v = String((0, util_1.required)(value, field)).replace(/[\s-]/g, '');
44
- if (!/^\d+$/.test(v))
45
- throw new TypeError(`${field} must contain digits only`);
46
- return v;
47
- }
48
- function month(value) {
49
- const m = Number(digits(value, 'expiryMonth'));
50
- if (m < 1 || m > 12)
51
- throw new TypeError('expiryMonth must be 1-12');
52
- return String(m).padStart(2, '0');
53
- }
54
- function year(value) {
55
- const y = digits(value, 'expiryYear');
56
- if (y.length === 2)
57
- return `20${y}`;
58
- if (y.length !== 4)
59
- throw new TypeError('expiryYear must have 2 or 4 digits');
60
- return y;
61
- }
62
- class CardEncryptor {
63
- publicKey;
64
- constructor(publicKey) {
65
- this.publicKey = publicKey;
66
- }
67
- encrypt(card) {
68
- const aesKey = (0, node_crypto_1.randomBytes)(AES_KEY_BYTES);
69
- const iv = (0, node_crypto_1.randomBytes)(IV_BYTES);
70
- const keyAndIv = Buffer.concat([aesKey, iv]);
71
- const plaintext = Buffer.from(JSON.stringify(card), 'utf8');
72
- try {
73
- const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', aesKey, iv);
74
- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);
75
- const secret = (0, node_crypto_1.publicEncrypt)({ key: this.publicKey, padding: node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, keyAndIv);
76
- return { encryptedMessage: ciphertext.toString('base64'), secretKey: secret.toString('base64') };
77
- }
78
- finally {
79
- aesKey.fill(0);
80
- iv.fill(0);
81
- keyAndIv.fill(0);
82
- plaintext.fill(0);
83
- }
84
- }
85
- }
86
- exports.CardEncryptor = CardEncryptor;