tcat 0.4.0 → 0.5.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5ed5fe975474cdb30f8d660719b0a59d0ea5f1813b4e86433c95cd2ee82c795e
4
- data.tar.gz: 025bf6aa6cfc46a4437d72e1d8abc966853606c1ba58b56ea5f6334a541b063e
3
+ metadata.gz: 33e61c6fc0aacf1483c733be09bc431229c1dec02978c3b3c95dbc7c8ab575fd
4
+ data.tar.gz: 668037fd822a935f4e46730008303e87675a98e0befe51b435011b84e074ff03
5
5
  SHA512:
6
- metadata.gz: b59a640cf706df074a2daa9bac89dfed2d96b1cfa1720278afe00b66ca8991cf64c096e4fca3701b05e7f43009b71f5f2e57186c902b339000d76db6098f4b13
7
- data.tar.gz: 4d678f18e49855e6faf85ac8f4b0969f7c3c6d7d8a176686cd31ecc875e871a36ac3452a19dc9e5c7cd02ef559fdccf4e727085984c52d0066456f1b8b27302c
6
+ metadata.gz: bd31d9873c4514a00e7ab7a29c4c499deee41cfeb69f52a573a631e67a1456ffc24b65f2d782b47d76aa9612b74d0757dfe7af084ae6d72a97ee403a8df0a39e
7
+ data.tar.gz: 05ba7daac7c9257ae4a5cc9f2db70789334e216a551b4b4d8a8c3ab79ba29f1cc4f06991a5220d6de7c84f8986250d963d23976133189566f672d9c6acd1d746
data/CHANGELOG.md ADDED
@@ -0,0 +1,102 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0
4
+
5
+ - **Breaking:** requires Ruby >= 3.3 (CI covers 3.3, 3.4 and 4.0)
6
+ - **Breaking:** removed the unused `Tcat::Error` constant (it was never raised)
7
+ - `Tcat::Query#status_code` now reflects the newest event; previously an earlier status (e.g. `配送中`) could mask the current one (e.g. `轉交超商配達`, `客樂得貨物退回中`)
8
+ - `Tcat::Query` parses T-Cat timestamps as Taiwan time (UTC+8) regardless of the host time zone
9
+ - `Tcat::Query` no longer drops the whole history when an item has no `<Office>`
10
+ - `Tcat::WorkerClient` wraps timeouts, refused connections and SSL errors in `NetworkError`, so `status_code`/`history`/`latest_status` return `nil`/`[]` as documented
11
+ - Worker: forwards every session cookie, uses `crypto.getRandomValues`, and times out upstream requests after 10s
12
+
13
+ ## 0.4.1
14
+
15
+ - Security hardening: `Tcat::Query` now uses `SecureRandom` (CSPRNG) instead of `rand` for the per-request freshness component embedded in the encrypted `secret` payload
16
+ - Encryption: `Tcat::EncryptionService` explicitly disables OpenSSL's built-in cipher padding so the manually applied PKCS#7 padding cannot be double-applied if the cipher pipeline ever changes
17
+ - `Tcat::WorkerClient` warns when `worker_url` uses `http://` against a non-localhost host so a misconfigured deployment cannot silently leak the Bearer token over plaintext
18
+ - Worker: added `[observability.logs]` (`enabled = false`, `invocation_logs = true`) to `wrangler.toml`
19
+
20
+ ## 0.4.0
21
+
22
+ - `Tcat::Query#status_code`, `#history`, `#latest_status` now accept an optional tracking-number argument, mirroring `Tcat::WorkerClient`'s shape
23
+ - `Tcat::Query.new` may be called without a tracking number for stateless reuse: `Tcat::Query.new.status_code('1234567890')`
24
+ - Existing one-shot construction (`Tcat::Query.new(tn).status_code`) is still supported
25
+
26
+ ## 0.3.5
27
+
28
+ - Added optional `worker_url` and `worker_token` to `Tcat.configure`; explicit `Tcat::WorkerClient.new(url, token:)` arguments still take precedence
29
+ - `Tcat::WorkerClient.new` now accepts no arguments when `worker_url` is set in configuration
30
+
31
+ ## 0.3.4
32
+
33
+ - Bundled the 0.3.3 fixes for release on RubyGems
34
+
35
+ ## 0.3.3
36
+
37
+ - Worker now subtracts the Taiwan UTC+8 offset when emitting ISO timestamps (previously every event was reported 8 hours later than reality)
38
+ - Worker forwards only the `name=value` portion of `Set-Cookie` to the upstream `Cookie:` header (RFC 6265)
39
+ - Worker rejects `/query` with HTTP 401 when `AUTH_TOKEN` is not configured (fail-closed)
40
+ - 5xx responses no longer leak `error.message`; details are written to `console.error` (visible via `wrangler tail`)
41
+
42
+ ## 0.3.2
43
+
44
+ - Added optional Bearer token auth to the Cloudflare Worker (`AUTH_TOKEN` secret)
45
+ - `Tcat::WorkerClient` accepts a `token:` keyword arg that is sent as `Authorization: Bearer <token>`
46
+ - Worker compares tokens in constant time; CORS allow-headers gain `Authorization`
47
+
48
+ ## 0.3.1
49
+
50
+ - Tightened `tcat.gemspec` so the published gem no longer bundles the `worker/` subproject or dev-only configs
51
+
52
+ ## 0.3.0
53
+
54
+ - Added `Tcat::WorkerClient` to query a Cloudflare Worker proxy instead of T-Cat directly
55
+ - Added new status mapping: `:store_delivery` for `轉交超商配達` (handed over to convenience store)
56
+ - Added the `worker/` Cloudflare Worker subproject (separate from the gem release)
57
+
58
+ ## 0.2.2
59
+
60
+ - Fixed status parsing to handle HTML tags in API responses
61
+
62
+ ## 0.2.1
63
+
64
+ - Updated base64 gem dependency to ~> 0.3
65
+ - Code formatting improvements
66
+
67
+ ## 0.2.0
68
+
69
+ - Fixed SSL certificate verification issues with T-Cat API
70
+ - Added session initialization to obtain cookies before queries
71
+ - Added cookie management for maintaining session state
72
+ - Added new status code mappings: `:rescheduled` (另約時間) and `:held` (暫置營業所)
73
+ - Removed Rails.logger dependency for better standalone gem compatibility
74
+ - Added base64 gem dependency for Ruby 3.4+ compatibility
75
+ - Updated HTTP headers to match latest BlackCat iOS app (version 3)
76
+ - Improved error handling with better debug output
77
+
78
+ ## 0.1.9
79
+
80
+ - Updated User-Agent and API version
81
+
82
+ ## 0.1.7
83
+
84
+ - Improved method naming, removed get_ prefix
85
+ - Added `latest_status` method to get latest status details
86
+ - Added `history` method to get full shipment history
87
+ - Used `DeliveryItem` struct to provide more complete shipment information
88
+ - Improved error handling and logging
89
+ - Supported UTF-8 encoding
90
+
91
+ ## 0.1.6
92
+
93
+ - Refactored query parsing method
94
+ - Improved error handling
95
+ - Added test coverage
96
+
97
+ ## 0.1.5
98
+
99
+ - Refactored HTTP request handling with new HttpClient class
100
+ - Refactored encryption logic with new EncryptionService class
101
+ - Improved error handling
102
+ - Updated documentation
data/README.md CHANGED
@@ -88,6 +88,8 @@ status = query.status_code('your_tracking_number')
88
88
  # :returning - In return process
89
89
  # :store_delivery - At convenience store for pickup
90
90
  # :unknown - Unknown status
91
+ # :error - T-Cat returned an error response (Query only)
92
+ # nil - Request failed
91
93
 
92
94
  # Get latest status details
93
95
  latest = query.latest_status
@@ -177,9 +179,12 @@ client = Tcat::WorkerClient.new('https://your-worker.workers.dev', timeout: 60)
177
179
 
178
180
  **Error handling:**
179
181
 
182
+ `status_code`, `history` and `latest_status` swallow errors and return `nil` / `[]`.
183
+ Use `query` when you need the exception:
184
+
180
185
  ```ruby
181
186
  begin
182
- status = client.status_code('tracking_number')
187
+ result = client.query('tracking_number')
183
188
  rescue Tcat::WorkerClient::NetworkError => e
184
189
  puts "Network error: #{e.message}"
185
190
  rescue Tcat::WorkerClient::APIError => e
@@ -270,86 +275,4 @@ This gem is available as open source under the terms of the [MIT License](https:
270
275
 
271
276
  ## Changelog
272
277
 
273
- ### 0.4.0
274
-
275
- - `Tcat::Query#status_code`, `#history`, `#latest_status` now accept an optional tracking-number argument, mirroring `Tcat::WorkerClient`'s shape
276
- - `Tcat::Query.new` may be called without a tracking number for stateless reuse: `Tcat::Query.new.status_code('1234567890')`
277
- - Existing one-shot construction (`Tcat::Query.new(tn).status_code`) is still supported
278
-
279
- ### 0.3.5
280
-
281
- - Added optional `worker_url` and `worker_token` to `Tcat.configure`; explicit `Tcat::WorkerClient.new(url, token:)` arguments still take precedence
282
- - `Tcat::WorkerClient.new` now accepts no arguments when `worker_url` is set in configuration
283
-
284
- ### 0.3.4
285
-
286
- - Bundled the 0.3.3 fixes for release on RubyGems
287
-
288
- ### 0.3.3
289
-
290
- - Worker now subtracts the Taiwan UTC+8 offset when emitting ISO timestamps (previously every event was reported 8 hours later than reality)
291
- - Worker forwards only the `name=value` portion of `Set-Cookie` to the upstream `Cookie:` header (RFC 6265)
292
- - Worker rejects `/query` with HTTP 401 when `AUTH_TOKEN` is not configured (fail-closed)
293
- - 5xx responses no longer leak `error.message`; details are written to `console.error` (visible via `wrangler tail`)
294
-
295
- ### 0.3.2
296
-
297
- - Added optional Bearer token auth to the Cloudflare Worker (`AUTH_TOKEN` secret)
298
- - `Tcat::WorkerClient` accepts a `token:` keyword arg that is sent as `Authorization: Bearer <token>`
299
- - Worker compares tokens in constant time; CORS allow-headers gain `Authorization`
300
-
301
- ### 0.3.1
302
-
303
- - Tightened `tcat.gemspec` so the published gem no longer bundles the `worker/` subproject or dev-only configs
304
-
305
- ### 0.3.0
306
-
307
- - Added `Tcat::WorkerClient` to query a Cloudflare Worker proxy instead of T-Cat directly
308
- - Added new status mapping: `:store_delivery` for `轉交超商配達` (handed over to convenience store)
309
- - Added the `worker/` Cloudflare Worker subproject (separate from the gem release)
310
-
311
- ### 0.2.2
312
-
313
- - Fixed status parsing to handle HTML tags in API responses
314
-
315
- ### 0.2.1
316
-
317
- - Updated base64 gem dependency to ~> 0.3
318
- - Code formatting improvements
319
-
320
- ### 0.2.0
321
-
322
- - Fixed SSL certificate verification issues with T-Cat API
323
- - Added session initialization to obtain cookies before queries
324
- - Added cookie management for maintaining session state
325
- - Added new status code mappings: `:rescheduled` (另約時間) and `:held` (暫置營業所)
326
- - Removed Rails.logger dependency for better standalone gem compatibility
327
- - Added base64 gem dependency for Ruby 3.4+ compatibility
328
- - Updated HTTP headers to match latest BlackCat iOS app (version 3)
329
- - Improved error handling with better debug output
330
-
331
- ### 0.1.9
332
-
333
- - Updated User-Agent and API version
334
-
335
- ### 0.1.7
336
-
337
- - Improved method naming, removed get_ prefix
338
- - Added `latest_status` method to get latest status details
339
- - Added `history` method to get full shipment history
340
- - Used `DeliveryItem` struct to provide more complete shipment information
341
- - Improved error handling and logging
342
- - Supported UTF-8 encoding
343
-
344
- ### 0.1.6
345
-
346
- - Refactored query parsing method
347
- - Improved error handling
348
- - Added test coverage
349
-
350
- ### 0.1.5
351
-
352
- - Refactored HTTP request handling with new HttpClient class
353
- - Refactored encryption logic with new EncryptionService class
354
- - Improved error handling
355
- - Updated documentation
278
+ See [CHANGELOG.md](CHANGELOG.md).
@@ -34,6 +34,9 @@ module Tcat
34
34
  def setup_cipher
35
35
  cipher = OpenSSL::Cipher.new(CIPHER_ALGORITHM)
36
36
  cipher.encrypt
37
+ # PKCS#7 padding is applied manually in #pad_message; turn off OpenSSL's
38
+ # built-in padding so a future cipher.final call cannot double-pad.
39
+ cipher.padding = 0
37
40
  cipher.key = @secret_key
38
41
  cipher
39
42
  end
data/lib/tcat/query.rb CHANGED
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'net/http'
4
- require 'base64'
3
+ require 'securerandom'
5
4
  require 'ox'
6
5
  require_relative 'http_client'
7
6
  require_relative 'encryption_service'
@@ -36,7 +35,6 @@ module Tcat
36
35
  response_body = @http_client.post(data(tn))
37
36
  parse_status_code(response_body) if response_body
38
37
  rescue HttpClient::RequestError
39
- # Log error or handle it appropriately
40
38
  nil
41
39
  end
42
40
 
@@ -108,7 +106,8 @@ module Tcat
108
106
  end
109
107
 
110
108
  def random
111
- rand(10_000..99_999).to_s
109
+ # CSPRNG so the per-request freshness component is unpredictable.
110
+ (SecureRandom.random_number(90_000) + 10_000).to_s
112
111
  end
113
112
 
114
113
  def source_string
@@ -118,7 +117,6 @@ module Tcat
118
117
  def generate_secret
119
118
  @encryption_service.encrypt(source_string)
120
119
  rescue EncryptionService::EncryptionError => e
121
- # Log error or handle it appropriately
122
120
  raise "Failed to generate secret: #{e.message}"
123
121
  end
124
122
 
@@ -127,10 +125,9 @@ module Tcat
127
125
  result = Ox.load(xml, mode: :hash, with_cdata: true)
128
126
  return :error unless result.dig(:Result, :Status) == '0'
129
127
 
130
- delivery_items = result.dig(:Result, :Content, :Item)
131
- delivery_statuses = extract_delivery_statuses(delivery_items)
132
-
133
- parse_status_message(delivery_statuses.uniq)
128
+ # The newest event is the current state; matching across the whole
129
+ # history let early events (e.g. 配送中) mask later ones (e.g. 轉交超商配達).
130
+ extract_delivery_history(result).first&.status_code || :unknown
134
131
  rescue StandardError => e
135
132
  warn "Error parsing T-Cat response: #{e.message}" if $DEBUG
136
133
  :error
@@ -146,7 +143,7 @@ module Tcat
146
143
  items.map { |item| parse_delivery_item(item) }
147
144
  else
148
145
  []
149
- end.compact.sort_by(&:time).reverse
146
+ end.compact.sort_by { |item| item.time || Time.at(0) }.reverse
150
147
  rescue StandardError => e
151
148
  warn "Error parsing delivery history: #{e.message}" if $DEBUG
152
149
  []
@@ -159,9 +156,9 @@ module Tcat
159
156
 
160
157
  DeliveryItem.new(
161
158
  status: status_text,
162
- status_code: parse_status_message([status_text]),
159
+ status_code: STATUS_MAPPINGS.fetch(status_text, :unknown),
163
160
  time: parse_time(item[:Time]),
164
- office: item[:Office].to_s.force_encoding('UTF-8'),
161
+ office: item[:Office].to_s.dup.force_encoding('UTF-8'),
165
162
  last_update: parse_last_update(item[:LastUPDateTime])
166
163
  )
167
164
  end
@@ -169,7 +166,7 @@ module Tcat
169
166
  def parse_time(time_str)
170
167
  return nil unless time_str
171
168
 
172
- Time.strptime(time_str.to_s, '%Y/%m/%d %H:%M')
169
+ Time.strptime("#{time_str} #{TAIWAN_OFFSET}", '%Y/%m/%d %H:%M %z')
173
170
  rescue
174
171
  nil
175
172
  end
@@ -177,27 +174,18 @@ module Tcat
177
174
  def parse_last_update(datetime_str)
178
175
  return nil unless datetime_str
179
176
 
180
- Time.strptime(datetime_str.to_s, '%Y%m%d%H%M%S')
177
+ Time.strptime("#{datetime_str} #{TAIWAN_OFFSET}", '%Y%m%d%H%M%S %z')
181
178
  rescue
182
179
  nil
183
180
  end
184
181
 
185
- def extract_delivery_statuses(items)
186
- statuses = case items
187
- when Hash
188
- [items[:Status].force_encoding('UTF-8')]
189
- when Array
190
- items.map { |item| item[:Status].force_encoding('UTF-8') }
191
- else
192
- []
193
- end
194
- statuses.map { |status| strip_html_tags(status) }
195
- end
196
-
197
182
  def strip_html_tags(text)
198
183
  text.gsub(/<[^>]+>/, '').strip
199
184
  end
200
185
 
186
+ # T-Cat reports times in Taiwan local time regardless of the host's TZ.
187
+ TAIWAN_OFFSET = '+0800'
188
+
201
189
  STATUS_MAPPINGS = {
202
190
  '順利送達' => :done,
203
191
  '配送中' => :delivering,
@@ -214,12 +202,5 @@ module Tcat
214
202
  '客樂得貨物退回中' => :returning,
215
203
  '轉交超商配達' => :store_delivery
216
204
  }.freeze
217
-
218
- def parse_status_message(statuses)
219
- STATUS_MAPPINGS.each do |status_text, status_symbol|
220
- return status_symbol if statuses.include?(status_text)
221
- end
222
- :unknown
223
- end
224
205
  end
225
206
  end
data/lib/tcat/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Tcat
4
- VERSION = '0.4.0'
4
+ VERSION = '0.5.0'
5
5
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'net/http'
4
4
  require 'json'
5
+ require 'openssl'
5
6
  require 'uri'
6
7
 
7
8
  module Tcat
@@ -44,7 +45,8 @@ module Tcat
44
45
 
45
46
  response = make_request(uri)
46
47
  parse_response(response)
47
- rescue SocketError, Net::HTTPError => e
48
+ rescue SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError, Net::HTTPError => e
49
+ # SystemCallError: ECONNREFUSED/ECONNRESET; Timeout::Error: Net::OpenTimeout/ReadTimeout
48
50
  raise NetworkError, "Network error: #{e.message}"
49
51
  rescue JSON::ParserError => e
50
52
  raise APIError, "Invalid JSON response: #{e.message}"
@@ -99,15 +101,29 @@ module Tcat
99
101
 
100
102
  private
101
103
 
104
+ LOCAL_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
105
+ private_constant :LOCAL_HOSTS
106
+
102
107
  def validate_url!
103
108
  uri = URI.parse(@worker_url)
104
109
  unless %w[http https].include?(uri.scheme)
105
110
  raise ArgumentError, 'Invalid Worker URL: must be http or https'
106
111
  end
112
+
113
+ warn_if_insecure(uri)
107
114
  rescue URI::InvalidURIError => e
108
115
  raise ArgumentError, "Invalid Worker URL: #{e.message}"
109
116
  end
110
117
 
118
+ def warn_if_insecure(uri)
119
+ return if uri.scheme == 'https'
120
+ return if LOCAL_HOSTS.include?(uri.host)
121
+
122
+ warn '[Tcat::WorkerClient] WARNING: worker_url uses http://; ' \
123
+ 'requests and any Authorization token will be sent in plaintext. ' \
124
+ 'Use https:// in production.'
125
+ end
126
+
111
127
  def make_request(uri)
112
128
  response = setup_http(uri).request(build_request(uri))
113
129
  raise APIError, "HTTP #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
data/lib/tcat.rb CHANGED
@@ -22,7 +22,4 @@ module Tcat
22
22
  def self.reset
23
23
  @configuration = Configuration.new
24
24
  end
25
-
26
- class Error < StandardError; end
27
- # Your code goes here...
28
25
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tcat
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Zac
@@ -60,6 +60,7 @@ executables: []
60
60
  extensions: []
61
61
  extra_rdoc_files: []
62
62
  files:
63
+ - CHANGELOG.md
63
64
  - LICENSE.txt
64
65
  - README.md
65
66
  - lib/tcat.rb
@@ -75,6 +76,7 @@ licenses:
75
76
  - MIT
76
77
  metadata:
77
78
  homepage_uri: https://rubygems.org/gems/tcat
79
+ changelog_uri: https://github.com/7a6163/tcat/blob/main/CHANGELOG.md
78
80
  rdoc_options: []
79
81
  require_paths:
80
82
  - lib
@@ -82,14 +84,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
82
84
  requirements:
83
85
  - - ">="
84
86
  - !ruby/object:Gem::Version
85
- version: 2.7.0
87
+ version: 3.3.0
86
88
  required_rubygems_version: !ruby/object:Gem::Requirement
87
89
  requirements:
88
90
  - - ">="
89
91
  - !ruby/object:Gem::Version
90
92
  version: '0'
91
93
  requirements: []
92
- rubygems_version: 4.0.6
94
+ rubygems_version: 4.0.20
93
95
  specification_version: 4
94
96
  summary: A Ruby gem for tracking packages using the Tcat system.
95
97
  test_files: []