cashfree_pg 0.1.0 → 0.1.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 601ea757a5ae5b368fb3c3937d12f3281ac35f2f8ab4128d288919cf81208f03
4
- data.tar.gz: 87e14bc708bc3d5def1eba63ecd2291d46a8c76d5f9c5dc8212bdb09c5a0de3e
3
+ metadata.gz: dce9439ab719105407dd0c0e4839cdf27f452920f53ed9e72708106e42982750
4
+ data.tar.gz: 831cb6fe317490de77d9d154e863f8d03a0703aaca4289f10e0c8e737210560b
5
5
  SHA512:
6
- metadata.gz: c64873b92386ffcf036a7c63e599aa3c05885fa8d53ee18ecd8ae3b679bc26cd84bd3129bae8651bd3a762eb9a32e90ae4c7e3db42e51433c29191c0a708eda1
7
- data.tar.gz: 595b54f8b913642cc8d2a4c91a790ad781607060c49d12e9aa5caa0f254244a98860d8df8587ddaa364aa17c55bb53f4bb2c5443b472f85ec226c540b91d2c91
6
+ metadata.gz: 778f4626c645a8cbd4759fcf6e3667da40877d2cce84cdd931ae0595dfdec317c4a633ee82627ea32f2a185e61502b7c065e87d5448b13f51ed5850fa61d05d6
7
+ data.tar.gz: cc9b7e71322993cf708569d5b5c60a15d8e2fab4dd414ace2d974b91d9d0f7d600816b0c3db9acd85c0b10a7210a106b2c13c0355abcd96bbad1443ecc723ec6
data/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ All notable changes to this project are documented in this file. The format is b
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.1.1] - 2026-12-06
8
+
9
+ ### Fixed
10
+
11
+ - `CashfreePg::Webhook.construct_event`: handle `ASCII-8BIT` raw bodies containing UTF-8 bytes without raising `Encoding::CompatibilityError`, and validate `tolerance` as a non-negative finite number.
12
+ - `CashfreePg::Response`: avoid reporting private `Kernel` or `Response` methods (such as `format` or `body`) as dynamic field readers via `respond_to?`.
13
+ - `CashfreePg::Payments#upi`: raise `ArgumentError` instead of `NoMethodError` for non-symbolizable channels, prevent `options` from overriding `channel` or `upi_id`, and reject whitespace-only `payment_session_id` strings.
14
+ - `CashfreePg::Client`: validate `environment` even when `base_url` is overridden, validate `base_url` as an HTTPS URI with a host, and require positive finite timeouts.
15
+ - `CashfreePg::Request`: scrub `client_secret` from `code` and `type` error fields, reject `..` / `%2e%2e` path traversal segments, and map `Errno::ETIMEDOUT`, `Errno::ECONNRESET`, and `EOFError` to `TimeoutError` / `ConnectionError`.
16
+ - `CashfreePg::Refunds#list`: raise `APIError` when Cashfree returns a non-array payload.
17
+
18
+ ### Changed
19
+
20
+ - `CashfreePg::Client` and `CashfreePg::Request`: cache frozen base headers on the client instead of rebuilding static header hashes on every request.
21
+ - `CashfreePg::Money`: avoid re-wrapping `BigDecimal` values during coercion.
22
+
7
23
  ## [0.1.0] - 2026-10-26
8
24
 
9
25
  ### Added
data/README.md CHANGED
@@ -1,15 +1,16 @@
1
1
  <div align="center">
2
2
 
3
- <img src="docs/assets/logo.png" alt="cashfree_pg: Unofficial Ruby Client for Cashfree Payments" width="360">
3
+ <img src="https://raw.githubusercontent.com/Shadbox-Infosystem/cashfree_pg/main/docs/assets/logo.png" alt="cashfree_pg: Unofficial Ruby Client for Cashfree Payments" width="360">
4
4
 
5
5
  **Orders, payments, UPI, refunds, payment links and webhook verification<br>for the Cashfree Payment Gateway, from plain Ruby or Rails.**
6
6
 
7
+ [![Gem Version](https://img.shields.io/gem/v/cashfree_pg?color=CC342D)](https://rubygems.org/gems/cashfree_pg)
7
8
  [![CI](https://github.com/Shadbox-Infosystem/cashfree_pg/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Shadbox-Infosystem/cashfree_pg/actions/workflows/ci.yml)
8
- [![Ruby](https://img.shields.io/badge/ruby-%E2%89%A5%203.3-CC342D?logo=ruby&logoColor=white)](cashfree_pg.gemspec)
9
- [![Cashfree API](https://img.shields.io/badge/x--api--version-2025--01--01-2F3B52)](docs/api.md)
10
- [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.txt)
9
+ [![Ruby](https://img.shields.io/badge/ruby-%E2%89%A5%203.3-CC342D?logo=ruby&logoColor=white)](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/cashfree_pg.gemspec)
10
+ [![Cashfree API](https://img.shields.io/badge/x--api--version-2025--01--01-2F3B52)](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/api.md)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/LICENSE.txt)
11
12
 
12
- [Quick start](#-quick-start) · [Payment flow](#-payment-flow) · [Rails](#-rails-integration) · [API reference](docs/api.md) · [Webhooks](docs/webhooks.md) · [Sandbox testing](#-sandbox-testing)
13
+ [Quick start](#-quick-start) · [Payment flow](#-payment-flow) · [Rails](#-rails-integration) · [API reference](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/api.md) · [Webhooks](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/webhooks.md) · [Sandbox testing](#-sandbox-testing)
13
14
 
14
15
  </div>
15
16
 
@@ -49,8 +50,8 @@ How one payment moves through your app, `cashfree_pg` and Cashfree:
49
50
 
50
51
  <p align="center">
51
52
  <picture>
52
- <source media="(prefers-color-scheme: dark)" srcset="docs/assets/payment-flow-dark.svg">
53
- <img src="docs/assets/payment-flow-light.svg" width="100%" alt="Payment flow: 1. create the order with orders.create on your server, 2. the customer pays on Cashfree checkout or UPI, 3. verify the webhook with Webhook.construct_event, 4. confirm with orders.fetch that order_status is PAID, 5. optionally refund with refunds.create">
53
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Shadbox-Infosystem/cashfree_pg/main/docs/assets/payment-flow-dark.svg">
54
+ <img src="https://raw.githubusercontent.com/Shadbox-Infosystem/cashfree_pg/main/docs/assets/payment-flow-light.svg" width="100%" alt="Payment flow: 1. create the order with orders.create on your server, 2. the customer pays on Cashfree checkout or UPI, 3. verify the webhook with Webhook.construct_event, 4. confirm with orders.fetch that order_status is PAID, 5. optionally refund with refunds.create">
54
55
  </picture>
55
56
  </p>
56
57
 
@@ -111,7 +112,7 @@ client.orders.fetch(order.order_id).order_status # => "ACTIVE", "PAID", ...
111
112
  | `open_timeout` | `30` | Seconds to wait for a connection. |
112
113
  | `read_timeout` | `60` | Seconds to wait for a response. |
113
114
 
114
- [`.env.example`](.env.example) lists the variable names this repository's tooling uses. Never commit real credentials; `.env` is git-ignored.
115
+ [`.env.example`](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/.env.example) lists the variable names this repository's tooling uses. Never commit real credentials; `.env` is git-ignored.
115
116
 
116
117
  To try unreleased changes, install from GitHub: `gem "cashfree_pg", github: "Shadbox-Infosystem/cashfree_pg", branch: "main"`.
117
118
 
@@ -128,7 +129,7 @@ order.dig(:customer_details, :customer_id) # use [] or dig for keys like hash o
128
129
  order.request_id # quote this to Cashfree support
129
130
  ```
130
131
 
131
- `payments.list` and `payment_links.orders` return an Array of `Response`. Every method and its Cashfree endpoint is listed in [docs/api.md](docs/api.md).
132
+ `payments.list` and `payment_links.orders` return an Array of `Response`. Every method and its Cashfree endpoint is listed in [docs/api.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/api.md).
132
133
 
133
134
  <details>
134
135
  <summary><b>UPI: intent, QR and collect</b></summary>
@@ -225,7 +226,7 @@ rescue CashfreePg::Error => e
225
226
  end
226
227
  ```
227
228
 
228
- HTTP 400, 401, 403, 404, 409, 422 and 429 each have their own class; 5xx raises `APIError`, and a missing response raises `ConnectionError` or `TimeoutError`. The full mapping is in [docs/api.md](docs/api.md#errors). Bad local input, such as a blank id or an unknown UPI channel, raises `ArgumentError` before any request is sent.
229
+ HTTP 400, 401, 403, 404, 409, 422 and 429 each have their own class; 5xx raises `APIError`, and a missing response raises `ConnectionError` or `TimeoutError`. The full mapping is in [docs/api.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/api.md#errors). Bad local input, such as a blank id or an unknown UPI channel, raises `ArgumentError` before any request is sent.
229
230
 
230
231
  ## 🚂 Rails integration
231
232
 
@@ -266,13 +267,13 @@ end
266
267
  ```
267
268
 
268
269
  > [!WARNING]
269
- > Pass `request.raw_post`, never parsed params. Re-encoding changes amounts like `10.10` and the signature will not match. See [docs/webhooks.md](docs/webhooks.md) for deduplication, the optional `tolerance:` window and Cashfree's IP allow-list.
270
+ > Pass `request.raw_post`, never parsed params. Re-encoding changes amounts like `10.10` and the signature will not match. See [docs/webhooks.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/docs/webhooks.md) for deduplication, the optional `tolerance:` window and Cashfree's IP allow-list.
270
271
 
271
272
  ## 🧪 Sandbox testing
272
273
 
273
- **Unit specs run on every push.** RSpec with WebMock (real network blocked) covers every resource method, headers, money handling, each HTTP status mapping, timeouts, secret redaction and webhook signatures. SimpleCov fails the run below 90% line coverage, and [CI](.github/workflows/ci.yml) runs on Ruby 3.3, 3.4 and latest, with `bundler-audit` and a `gitleaks` secret scan.
274
+ **Unit specs run on every push.** RSpec with WebMock (real network blocked) covers every resource method, headers, money handling, each HTTP status mapping, timeouts, secret redaction and webhook signatures. SimpleCov fails the run below 90% line coverage, and [CI](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/.github/workflows/ci.yml) runs on Ruby 3.3, 3.4 and latest, with `bundler-audit` and a `gitleaks` secret scan.
274
275
 
275
- **Integration specs hit the real sandbox.** [`spec/integration/sandbox_spec.rb`](spec/integration/sandbox_spec.rb) runs against `sandbox.cashfree.com/pg` when you provide credentials. It skips without them, refuses to run with `CASHFREE_ENVIRONMENT=production`, and does not run in CI.
276
+ **Integration specs hit the real sandbox.** [`spec/integration/sandbox_spec.rb`](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/spec/integration/sandbox_spec.rb) runs against `sandbox.cashfree.com/pg` when you provide credentials. It skips without them, refuses to run with `CASHFREE_ENVIRONMENT=production`, and does not run in CI.
276
277
 
277
278
  | Flow | Verified against the sandbox |
278
279
  | --- | --- |
@@ -307,15 +308,15 @@ bin/console # IRB with the gem loaded, sandbox only
307
308
  | :---: | --- |
308
309
  | ✅ | Orders, payments, pre-authorisation, UPI (intent, QR, collect), refunds, payment links |
309
310
  | ✅ | Webhook verification, typed errors, exact money, RBS signatures, idempotency keys |
310
- | 🚧 | First RubyGems release (v0.1.0) through the trusted-publishing [release workflow](.github/workflows/release.yml) |
311
+ | ✅ | Published on RubyGems through the trusted-publishing [release workflow](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/.github/workflows/release.yml) |
311
312
  | 📋 | Stabilise the public API for v1.0 |
312
313
  | 📋 | More PG endpoints, such as Order Pay for cards and netbanking, settlements and subscriptions |
313
314
 
314
- Until v1.0, a minor release may include breaking changes, listed in the [changelog](CHANGELOG.md). Pin with `~> 0.1.0` to get only patch updates. Missing something? [Open an issue](https://github.com/Shadbox-Infosystem/cashfree_pg/issues) before starting larger work.
315
+ Until v1.0, a minor release may include breaking changes, listed in the [changelog](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/CHANGELOG.md). Pin with `~> 0.1.0` to get only patch updates. Missing something? [Open an issue](https://github.com/Shadbox-Infosystem/cashfree_pg/issues) before starting larger work.
315
316
 
316
317
  ## 🤝 Contributing
317
318
 
318
- Bug reports and pull requests are welcome. This gem sits in payment flows, so correctness and security come before new features. Read [CONTRIBUTING.md](CONTRIBUTING.md) first.
319
+ Bug reports and pull requests are welcome. This gem sits in payment flows, so correctness and security come before new features. Read [CONTRIBUTING.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/CONTRIBUTING.md) first.
319
320
 
320
321
  ```bash
321
322
  git checkout dev && git checkout -b fix/short-description
@@ -323,11 +324,11 @@ bin/setup # install dependencies
323
324
  bundle exec rake # specs, RuboCop, RBS validation and gem contents check
324
325
  ```
325
326
 
326
- Match new endpoints to Cashfree's current API reference, cover them with RSpec and WebMock, never use `Float` for amounts, add a line under `[Unreleased]` in [CHANGELOG.md](CHANGELOG.md), and open the pull request against `dev`. Never put real credentials or customer data in code, fixtures or screenshots. Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md). Everyone taking part follows the [code of conduct](CODE_OF_CONDUCT.md).
327
+ Match new endpoints to Cashfree's current API reference, cover them with RSpec and WebMock, never use `Float` for amounts, add a line under `[Unreleased]` in [CHANGELOG.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/CHANGELOG.md), and open the pull request against `dev`. Never put real credentials or customer data in code, fixtures or screenshots. Report vulnerabilities privately as described in [SECURITY.md](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/SECURITY.md). Everyone taking part follows the [code of conduct](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/CODE_OF_CONDUCT.md).
327
328
 
328
329
  ## 📄 License
329
330
 
330
- Released under the [MIT License](LICENSE.txt). Copyright © 2026 Muballigh Faraz.
331
+ Released under the [MIT License](https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/LICENSE.txt). Copyright © 2026 Muballigh Faraz.
331
332
 
332
333
  "Cashfree" and "Cashfree Payments" are names of their respective owner, used here only to describe which API this library talks to. For official SDKs and support, see [cashfree.com](https://www.cashfree.com).
333
334
 
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "faraday"
4
+ require "uri"
4
5
  require_relative "request"
5
6
 
6
7
  module CashfreePg
@@ -15,8 +16,13 @@ module CashfreePg
15
16
  # environment: :sandbox
16
17
  # )
17
18
  class Client
19
+ # Cashfree sandbox Payment Gateway base URL.
18
20
  SANDBOX_URL = "https://sandbox.cashfree.com/pg"
21
+
22
+ # Cashfree production Payment Gateway base URL.
19
23
  PRODUCTION_URL = "https://api.cashfree.com/pg"
24
+
25
+ # Default Cashfree API version sent in `x-api-version`.
20
26
  DEFAULT_API_VERSION = "2025-01-01"
21
27
 
22
28
  # @return [String]
@@ -49,7 +55,10 @@ module CashfreePg
49
55
  @environment = environment
50
56
  @api_version = required_string(api_version, "api_version")
51
57
  @base_url = resolve_base_url(base_url, allow_custom_base_url)
52
- @connection = build_connection(open_timeout, read_timeout)
58
+ @public_headers = build_public_headers.freeze
59
+ @auth_headers = @public_headers.merge("x-client-id" => @client_id, "x-client-secret" => @client_secret).freeze
60
+ @connection = build_connection(positive_timeout(open_timeout, "open_timeout"),
61
+ positive_timeout(read_timeout, "read_timeout"))
53
62
  end
54
63
 
55
64
  # @param path [String] absolute path on the Cashfree host, such as `/orders`
@@ -109,6 +118,12 @@ module CashfreePg
109
118
  @payments ||= Payments.new(self)
110
119
  end
111
120
 
121
+ # @api private
122
+ # @return [Hash{String => String}]
123
+ def default_headers(skip_auth: false)
124
+ skip_auth ? @public_headers : @auth_headers
125
+ end
126
+
112
127
  # `pp` uses this too, so the secret stays hidden there as well.
113
128
  #
114
129
  # @return [String] client secret is always `[FILTERED]`
@@ -132,13 +147,38 @@ module CashfreePg
132
147
  end
133
148
 
134
149
  def resolve_base_url(custom, allowed)
135
- return environment_url if custom.nil?
150
+ env_url = environment_url
151
+ return env_url if custom.nil?
136
152
  raise ArgumentError, "base_url is only allowed when allow_custom_base_url: true" unless allowed
137
- raise ArgumentError, "base_url must use https" unless custom.start_with?("https://")
153
+ raise ArgumentError, "base_url must use https" unless valid_https_url?(custom)
138
154
 
139
155
  custom.chomp("/")
140
156
  end
141
157
 
158
+ def valid_https_url?(value)
159
+ return false unless value.is_a?(String)
160
+
161
+ uri = URI.parse(value)
162
+ uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty?
163
+ rescue URI::InvalidURIError
164
+ false
165
+ end
166
+
167
+ def positive_timeout(value, name)
168
+ return value if value.is_a?(Numeric) && value.finite? && value.positive?
169
+
170
+ raise ArgumentError, "#{name} must be a positive number"
171
+ end
172
+
173
+ def build_public_headers
174
+ {
175
+ "User-Agent" => "cashfree_pg/#{VERSION} ruby/#{RUBY_VERSION}",
176
+ "Accept" => "application/json",
177
+ "Content-Type" => "application/json",
178
+ "x-api-version" => @api_version
179
+ }
180
+ end
181
+
142
182
  def environment_url
143
183
  case environment
144
184
  when :sandbox then SANDBOX_URL
@@ -11,6 +11,7 @@ module CashfreePg
11
11
  #
12
12
  # @api private
13
13
  module Money
14
+ # Matches payload keys whose values must be serialized as two-decimal JSON numbers.
14
15
  AMOUNT_KEY = /(?:\A|_)amount\z/
15
16
 
16
17
  module_function
@@ -34,7 +35,8 @@ module CashfreePg
34
35
  # @return [BigDecimal] rounded half-up to two places
35
36
  def coerce(value)
36
37
  decimal = case value
37
- when Integer, BigDecimal then BigDecimal(value)
38
+ when BigDecimal then value
39
+ when Integer then BigDecimal(value)
38
40
  when String then decimal_from_string(value)
39
41
  when Float then decimal_from_float(value)
40
42
  else raise ArgumentError, "amount must be a String, Integer, or BigDecimal"
@@ -48,12 +48,11 @@ module CashfreePg
48
48
  # client.payments.upi(order, channel: :intent)
49
49
  # client.payments.upi(order, channel: :collect, upi_id: "testsuccess@gocash")
50
50
  def upi(order, channel:, upi_id: nil, **options)
51
- cashfree_channel = CHANNELS[channel.to_sym]
52
- raise ArgumentError, "channel must be one of #{CHANNELS.keys.join(", ")}" unless cashfree_channel
51
+ cashfree_channel = resolve_channel(channel)
53
52
  raise ArgumentError, "collect requires upi_id" if cashfree_channel == "collect" && upi_id.nil?
54
53
 
55
54
  check_vpa!(upi_id) if upi_id
56
- upi = { channel: cashfree_channel, upi_id: upi_id }.compact.merge(options)
55
+ upi = options.merge({ channel: cashfree_channel, upi_id: upi_id }.compact)
57
56
  pay(session_id(order), upi)
58
57
  end
59
58
 
@@ -92,11 +91,23 @@ module CashfreePg
92
91
  )
93
92
  end
94
93
 
94
+ def resolve_channel(channel)
95
+ key = channel.to_sym if channel.respond_to?(:to_sym)
96
+ cashfree_channel = CHANNELS[key]
97
+ return cashfree_channel if cashfree_channel
98
+
99
+ raise ArgumentError, "channel must be one of #{CHANNELS.keys.join(", ")}"
100
+ end
101
+
95
102
  def session_id(order)
96
- return order if order.is_a?(String) && !order.empty?
103
+ if order.is_a?(String)
104
+ raise ArgumentError, "payment_session_id is required" if order.strip.empty?
105
+
106
+ return order
107
+ end
97
108
 
98
109
  id = order["payment_session_id"] || order[:payment_session_id] if order.respond_to?(:[])
99
- raise ArgumentError, "payment_session_id is required" if id.nil? || id.to_s.empty?
110
+ raise ArgumentError, "payment_session_id is required" if id.nil? || id.to_s.strip.empty?
100
111
 
101
112
  id
102
113
  end
@@ -32,7 +32,10 @@ module CashfreePg
32
32
  # @example
33
33
  # client.refunds.list("order_123").to_h
34
34
  def list(order_id)
35
- @client.get("#{order_path(order_id)}/refunds")
35
+ response = @client.get("#{order_path(order_id)}/refunds")
36
+ return response if response.to_h.is_a?(Array)
37
+
38
+ raise APIError.new("refunds list was not an array", status: response.status, request_id: response.request_id)
36
39
  end
37
40
  end
38
41
  end
@@ -8,6 +8,7 @@ module CashfreePg
8
8
  #
9
9
  # @api private
10
10
  class Request
11
+ # HTTP status codes mapped to typed {CashfreePg::Error} subclasses.
11
12
  STATUS_ERRORS = {
12
13
  400 => InvalidRequestError,
13
14
  401 => AuthenticationError,
@@ -18,6 +19,14 @@ module CashfreePg
18
19
  429 => RateLimitError
19
20
  }.freeze
20
21
 
22
+ # Exceptions mapped to {TimeoutError}.
23
+ TIMEOUT_ERRORS = [Faraday::TimeoutError, Timeout::Error, Errno::ETIMEDOUT].freeze
24
+
25
+ # Exceptions mapped to {ConnectionError}.
26
+ CONNECTION_ERRORS = [
27
+ Faraday::ConnectionFailed, Faraday::SSLError, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError, SocketError
28
+ ].freeze
29
+
21
30
  # @param client [Client]
22
31
  # @param connection [Faraday::Connection]
23
32
  def initialize(client, connection)
@@ -36,9 +45,9 @@ module CashfreePg
36
45
  @method = method
37
46
  @request_id = SecureRandom.uuid
38
47
  handle(dispatch(request_path(path), body, request_headers(skip_auth, idempotency_key)))
39
- rescue Faraday::TimeoutError, Timeout::Error
48
+ rescue *TIMEOUT_ERRORS
40
49
  raise timeout_error
41
- rescue Faraday::ConnectionFailed, Faraday::SSLError, Errno::ECONNREFUSED, SocketError
50
+ rescue *CONNECTION_ERRORS
42
51
  raise ConnectionError.new("connection failed request_id=#{@request_id}", request_id: @request_id)
43
52
  end
44
53
 
@@ -52,17 +61,9 @@ module CashfreePg
52
61
  end
53
62
 
54
63
  def request_headers(skip_auth, idempotency_key)
55
- headers = {
56
- "User-Agent" => "cashfree_pg/#{VERSION} ruby/#{RUBY_VERSION}",
57
- "Accept" => "application/json",
58
- "Content-Type" => "application/json",
59
- "x-api-version" => @client.api_version,
60
- "x-request-id" => @request_id
61
- }
64
+ headers = @client.default_headers(skip_auth: skip_auth).merge("x-request-id" => @request_id)
62
65
  headers["x-idempotency-key"] = idempotency_key if idempotency_key
63
- return headers if skip_auth
64
-
65
- headers.merge("x-client-id" => @client.client_id, "x-client-secret" => @client.client_secret)
66
+ headers
66
67
  end
67
68
 
68
69
  def handle(response)
@@ -99,14 +100,18 @@ module CashfreePg
99
100
 
100
101
  def error_message(status, payload, request_id)
101
102
  parts = ["status=#{status}"]
102
- parts << "code=#{payload["code"]}" if payload["code"]
103
- parts << "type=#{payload["type"]}" if payload["type"]
104
- detail = payload["message"].to_s.gsub(@client.client_secret, "[FILTERED]")
103
+ parts << "code=#{redact(payload["code"])}" if payload["code"]
104
+ parts << "type=#{redact(payload["type"])}" if payload["type"]
105
+ detail = redact(payload["message"])
105
106
  parts << detail unless detail.empty?
106
107
  parts << "request_id=#{request_id}"
107
108
  parts.join(" ")
108
109
  end
109
110
 
111
+ def redact(value)
112
+ value.to_s.gsub(@client.client_secret, "[FILTERED]")
113
+ end
114
+
110
115
  # An empty body is `{}`. Invalid JSON is nil.
111
116
  def parse_json(raw)
112
117
  text = raw.to_s
@@ -129,9 +134,18 @@ module CashfreePg
129
134
  end
130
135
 
131
136
  def validate_path!(path)
132
- return if path.is_a?(String) && path.start_with?("/") && !path.start_with?("//")
137
+ return if valid_relative_path?(path)
133
138
 
134
139
  raise ArgumentError, "path must be a relative path starting with /"
135
140
  end
141
+
142
+ def valid_relative_path?(path)
143
+ path.is_a?(String) && path.start_with?("/") && !path.start_with?("//") && !path_traversal?(path)
144
+ end
145
+
146
+ def path_traversal?(path)
147
+ path_only = path.split("?", 2).first.to_s
148
+ path_only.split("/").any? { |segment| segment == ".." || segment.casecmp?("%2e%2e") }
149
+ end
136
150
  end
137
151
  end
@@ -41,7 +41,7 @@ module CashfreePg
41
41
  # @return [Object]
42
42
  def method_missing(name, *args)
43
43
  key = name.to_s
44
- if args.empty? && !name.end_with?("=") && body.key?(key) && !self.class.method_defined?(name)
44
+ if args.empty? && !name.end_with?("=") && body.key?(key) && !reserved_method?(name)
45
45
  body[key]
46
46
  else
47
47
  super
@@ -52,11 +52,15 @@ module CashfreePg
52
52
  # @param include_private [Boolean]
53
53
  # @return [Boolean]
54
54
  def respond_to_missing?(name, include_private = false)
55
- (body.key?(name.to_s) && !self.class.method_defined?(name)) || super
55
+ (body.key?(name.to_s) && !reserved_method?(name)) || super
56
56
  end
57
57
 
58
58
  private
59
59
 
60
+ def reserved_method?(name)
61
+ self.class.method_defined?(name) || self.class.private_method_defined?(name)
62
+ end
63
+
60
64
  # @return [Hash]
61
65
  def body
62
66
  @data.is_a?(Hash) ? @data : {}
@@ -2,5 +2,5 @@
2
2
 
3
3
  module CashfreePg
4
4
  # Gem version, following Semantic Versioning.
5
- VERSION = "0.1.0"
5
+ VERSION = "0.1.1"
6
6
  end
@@ -67,12 +67,23 @@ module CashfreePg
67
67
  raise SignatureVerificationError, "webhook body must be a string" unless @raw_body.is_a?(String)
68
68
  raise SignatureVerificationError, "webhook body is empty" if @raw_body.empty?
69
69
  raise SignatureVerificationError, "webhook headers are missing" unless @headers.respond_to?(:each)
70
+
71
+ check_tolerance!
72
+ end
73
+
74
+ def check_tolerance!
75
+ return if @tolerance.nil?
76
+ return if @tolerance.is_a?(Numeric) && @tolerance.finite? && @tolerance >= 0
77
+
78
+ raise ArgumentError, "tolerance must be a non-negative number"
70
79
  end
71
80
 
72
81
  def valid?(timestamp, signature)
73
- digest = OpenSSL::HMAC.digest("SHA256", @secret.to_s, "#{timestamp}#{@raw_body}")
82
+ payload = "#{timestamp.to_s.b}#{@raw_body.b}"
83
+ digest = OpenSSL::HMAC.digest("SHA256", @secret.to_s.b, payload)
74
84
  expected = [digest].pack("m0")
75
- signature.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(expected, signature)
85
+ sig = signature.b
86
+ sig.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(expected, sig)
76
87
  end
77
88
 
78
89
  def check_window!(timestamp)
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cashfree_pg
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Muballigh Faraz
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-26 00:00:00.000000000 Z
11
+ date: 2026-12-06 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: faraday
@@ -30,12 +30,13 @@ dependencies:
30
30
  - - "<"
31
31
  - !ruby/object:Gem::Version
32
32
  version: '3'
33
- description: 'A small, well-tested Ruby client for Cashfree Payment Gateway APIs:
34
- orders, payments, UPI, refunds, payment links and webhook verification. Instance-based,
35
- thread-safe, with API version pinning, exact money handling and secrets redacted
36
- by default. Not affiliated with or endorsed by Cashfree Payments.'
33
+ description: An unofficial, thread-safe Ruby client for the Cashfree Payment Gateway
34
+ API, supporting orders, payments, pre-authorisation, UPI, refunds, payment links,
35
+ and webhook verification. Built with per-instance credentials, pinned API versioning,
36
+ exact BigDecimal money handling, typed errors, and secret redaction. Not affiliated
37
+ with Cashfree Payments.
37
38
  email:
38
- - support@shadbox.com
39
+ - muballigh.shahid@gmail.com
39
40
  executables: []
40
41
  extensions: []
41
42
  extra_rdoc_files: []
@@ -64,6 +65,7 @@ metadata:
64
65
  allowed_push_host: https://rubygems.org
65
66
  homepage_uri: https://github.com/Shadbox-Infosystem/cashfree_pg
66
67
  source_code_uri: https://github.com/Shadbox-Infosystem/cashfree_pg
68
+ documentation_uri: https://rubydoc.info/gems/cashfree_pg
67
69
  changelog_uri: https://github.com/Shadbox-Infosystem/cashfree_pg/blob/main/CHANGELOG.md
68
70
  bug_tracker_uri: https://github.com/Shadbox-Infosystem/cashfree_pg/issues
69
71
  rubygems_mfa_required: 'true'