ksef-client-rails 0.1.0 → 1.0.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.
Files changed (73) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +161 -0
  3. data/NOTICE +40 -0
  4. data/README.md +524 -6
  5. data/examples/fa3_full.xml +143 -0
  6. data/examples/fa3_minimal.xml +65 -0
  7. data/examples/fa3_typical.xml +76 -0
  8. data/lib/generators/ksef/install/install_generator.rb +20 -0
  9. data/lib/generators/ksef/install/templates/ksef.rb +25 -0
  10. data/lib/ksef/auth/coordinator.rb +164 -0
  11. data/lib/ksef/auth/ksef_token_encryptor.rb +36 -0
  12. data/lib/ksef/batch/package_builder.rb +125 -0
  13. data/lib/ksef/batch/splitter.rb +99 -0
  14. data/lib/ksef/batch/uploader.rb +114 -0
  15. data/lib/ksef/client.rb +135 -0
  16. data/lib/ksef/configuration.rb +206 -0
  17. data/lib/ksef/crypto/cryptography_service.rb +136 -0
  18. data/lib/ksef/crypto/csr.rb +106 -0
  19. data/lib/ksef/crypto/public_keys.rb +125 -0
  20. data/lib/ksef/environments.rb +61 -0
  21. data/lib/ksef/errors.rb +187 -0
  22. data/lib/ksef/http/connection.rb +432 -0
  23. data/lib/ksef/http/error_parser.rb +194 -0
  24. data/lib/ksef/http/pagination.rb +80 -0
  25. data/lib/ksef/invoices/builder/checks.rb +127 -0
  26. data/lib/ksef/invoices/builder/number.rb +67 -0
  27. data/lib/ksef/invoices/builder/xml.rb +256 -0
  28. data/lib/ksef/invoices/builder.rb +251 -0
  29. data/lib/ksef/invoices/export.rb +241 -0
  30. data/lib/ksef/invoices/sample.rb +78 -0
  31. data/lib/ksef/invoices/schema_outline.rb +120 -0
  32. data/lib/ksef/invoices/validator.rb +200 -0
  33. data/lib/ksef/models/form_code.rb +49 -0
  34. data/lib/ksef/models/ksef_number.rb +74 -0
  35. data/lib/ksef/models/nip.rb +62 -0
  36. data/lib/ksef/polish_time.rb +49 -0
  37. data/lib/ksef/polling.rb +65 -0
  38. data/lib/ksef/qr/code.rb +104 -0
  39. data/lib/ksef/qr/verification_link.rb +215 -0
  40. data/lib/ksef/railtie.rb +20 -0
  41. data/lib/ksef/resources/auth.rb +116 -0
  42. data/lib/ksef/resources/base.rb +120 -0
  43. data/lib/ksef/resources/batch_sessions.rb +43 -0
  44. data/lib/ksef/resources/certificates.rb +82 -0
  45. data/lib/ksef/resources/collective_identifiers.rb +70 -0
  46. data/lib/ksef/resources/exports.rb +47 -0
  47. data/lib/ksef/resources/invoices.rb +67 -0
  48. data/lib/ksef/resources/limits.rb +33 -0
  49. data/lib/ksef/resources/online_sessions.rb +62 -0
  50. data/lib/ksef/resources/peppol.rb +21 -0
  51. data/lib/ksef/resources/permissions.rb +180 -0
  52. data/lib/ksef/resources/security.rb +18 -0
  53. data/lib/ksef/resources/sessions.rb +125 -0
  54. data/lib/ksef/resources/test_data.rb +178 -0
  55. data/lib/ksef/resources/tokens.rb +62 -0
  56. data/lib/ksef/sessions/online.rb +168 -0
  57. data/lib/ksef/sync/incremental.rb +169 -0
  58. data/lib/ksef/testing.rb +153 -0
  59. data/lib/ksef/token_manager.rb +130 -0
  60. data/lib/ksef/version.rb +11 -0
  61. data/lib/ksef/xades/auth_token_request.rb +135 -0
  62. data/lib/ksef/xades/external_signer.rb +58 -0
  63. data/lib/ksef/xades/signer.rb +312 -0
  64. data/lib/ksef-client-rails.rb +3 -2
  65. data/lib/ksef.rb +116 -0
  66. data/schemas/FA/schemat_FA(2)_v1-0E.xsd +3661 -0
  67. data/schemas/FA/schemat_FA(3)_v1-0E.xsd +3950 -0
  68. data/schemas/README.md +53 -0
  69. data/schemas/RR/schemat_FA_RR(1)_v1-1E.xsd +2188 -0
  70. data/schemas/bazowe/ElementarneTypyDanych_v10-0E.xsd +1 -0
  71. data/schemas/bazowe/KodyKrajow_v10-0E.xsd +1283 -0
  72. data/schemas/bazowe/StrukturyDanych_v10-0E.xsd +1 -0
  73. metadata +291 -9
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Ksef
6
+ module Sync
7
+ # Incremental invoice download by HWM on top of export: adjacent PermanentStorage windows, continuing
8
+ # from `lastPermanentStorageDate` (truncated) or `permanentStorageHwmDate` until caught up. A start
9
+ # more than {MAX_WINDOW} back is walked in closed windows of that length (`dateRange` allows 100 days).
10
+ class Incremental
11
+ # Subject types a sync can run as, each with its own instance and HWM (SubjectAuthorized is left out,
12
+ # as in the SDK examples).
13
+ SUBJECT_TYPES = %w[Subject1 Subject2 Subject3].freeze
14
+ # Longest closed window (s), kept under the 100-day `dateRange` limit.
15
+ MAX_WINDOW = 90 * 86_400
16
+ # Export status: `dateRange.from` is past `PermanentStorageHwmDate` — nothing to fetch yet.
17
+ CODE_FROM_AFTER_HWM = 420
18
+ # The zone a String `from` must end with (`Z` or an offset); without one KSeF assumes Warsaw time.
19
+ ZONE = /(?:Z|[+-]\d{2}:?\d{2})\z/i
20
+
21
+ # @return [String] where the next window starts, once every invoice yielded so far is stored — persist
22
+ # it and pass it as +from:+ next run. It is also safe to persist after an exception, as long as each
23
+ # invoice was stored before the block returned (not buffered, e.g. by `each_slice`).
24
+ attr_reader :hwm
25
+
26
+ # @param client [Ksef::Client]
27
+ # @param subject_type [String] role of the downloader (Subject1/2/3)
28
+ # @param from [String, Time, Date] initial HWM: ISO 8601 with a zone (`Z` or an offset), a Time, or a
29
+ # Date (midnight in Poland) — required, `dateRange.from` has no API default
30
+ # @param page_limit [Integer] the most windows (exports) per call; KSeF allows 20 exports an hour, shared
31
+ # by every sync of the context
32
+ # @param poll [Hash] polling options for each export (timeout:, interval:, ...)
33
+ # @param clock [#call] current time source (for tests)
34
+ # @raise [Ksef::ConfigurationError] when +from+ is missing or not a date-time with a zone
35
+ def initialize(client, from:, subject_type: "Subject2", page_limit: 1000, poll: {}, clock: -> { Time.now })
36
+ @client = client
37
+ @subject_type = subject_type
38
+ @hwm = normalize_from(from)
39
+ @page_limit = page_limit
40
+ @poll = poll
41
+ @clock = clock
42
+ @boundary = Set.new
43
+ end
44
+
45
+ # Iterates over invoices window by window. Boundaries are inclusive, so the previous window's
46
+ # invoices are skipped; the first window of a new run may repeat the previous run's last ones —
47
+ # store invoices idempotently by KSeF number. Calling it again resumes from {#hwm}.
48
+ #
49
+ # @yieldparam xml [String] invoice XML (UTF-8)
50
+ # @yieldparam metadata [Hash] its InvoiceMetadata entry from `_metadata.json` (only `ksefNumber`, taken
51
+ # from the file name, when absent)
52
+ # @return [Integer] number of (unique) invoices yielded
53
+ # @raise [Ksef::RateLimited] when the hourly export limit is spent — {#hwm} is where to resume
54
+ # @raise [Ksef::Error] when a truncated window cannot move forward
55
+ def each_invoice(&block)
56
+ return enum_for(:each_invoice) unless block_given?
57
+
58
+ emitted = 0
59
+ @page_limit.times do
60
+ to = window_end(@hwm)
61
+ result = export_window(@hwm, to)
62
+ break unless result
63
+
64
+ emitted += emit_entries(result, &block)
65
+ next_hwm = next_window_start(result.package || {}, to)
66
+ break unless next_hwm
67
+
68
+ @hwm = next_hwm
69
+ end
70
+ emitted
71
+ end
72
+
73
+ private
74
+
75
+ def normalize_from(value)
76
+ raise ConfigurationError, "from: is required (dateRange.from is mandatory in the API)" if value.nil?
77
+ return value.getutc.iso8601(3) if value.is_a?(Time)
78
+ return PolishTime.midnight(value).getutc.iso8601(3) if value.instance_of?(Date)
79
+ return value.to_time.getutc.iso8601(3) if value.respond_to?(:to_time) && !value.is_a?(String)
80
+
81
+ text = value.to_s
82
+ return text if text.match?(ZONE) && iso8601?(text)
83
+
84
+ raise ConfigurationError, "from: must be an ISO 8601 date-time with a zone (e.g. 2026-10-01T00:00:00Z), " \
85
+ "got #{value.inspect}"
86
+ end
87
+
88
+ def iso8601?(text)
89
+ Time.iso8601(text)
90
+ true
91
+ rescue ArgumentError
92
+ false
93
+ end
94
+
95
+ # nil leaves `dateRange.to` out (the API takes "now", capped at the HWM); a start older than
96
+ # {MAX_WINDOW} gets a closed window instead, because the API refuses ranges over 100 days.
97
+ def window_end(from)
98
+ limit = Time.iso8601(from) + MAX_WINDOW
99
+ limit < @clock.call ? limit.utc.iso8601(3) : nil
100
+ rescue ArgumentError # a server date in an unexpected format: leave the window open
101
+ nil
102
+ end
103
+
104
+ # @return [Ksef::Invoices::Export::Result, nil] nil when the HWM has not reached +from+ yet (420)
105
+ def export_window(from, to)
106
+ range = { "dateType" => "PermanentStorage", "from" => from, "restrictToPermanentStorageHwmDate" => true }
107
+ range["to"] = to if to
108
+ Invoices::Export.new(@client).call(filters: { "subjectType" => @subject_type, "dateRange" => range },
109
+ poll: @poll)
110
+ rescue ApiError => e
111
+ raise unless e.codes.include?(CODE_FROM_AFTER_HWM)
112
+
113
+ nil
114
+ end
115
+
116
+ # Yields the window's invoices with their metadata, one file at a time. Invoice files are named
117
+ # `{ksefNumber}.xml`; `_metadata.json` entries carry the `ksefNumber` they belong to.
118
+ def emit_entries(result)
119
+ metadata = result.metadata.to_h { |entry| [entry["ksefNumber"], entry] }
120
+ window = Set.new
121
+ count = 0
122
+ result.each_entry do |name, bytes|
123
+ next unless name.end_with?(".xml") # `_metadata.json` and anything else that is no invoice
124
+
125
+ ksef_number = File.basename(name, ".xml")
126
+ repeated = @boundary.include?(ksef_number) || window.include?(ksef_number)
127
+ window << ksef_number
128
+ next if repeated
129
+
130
+ count += 1
131
+ entry = metadata.fetch(ksef_number) { { "ksefNumber" => ksef_number } }
132
+ yield(bytes.force_encoding(Encoding::UTF_8), entry)
133
+ end
134
+ @boundary = window
135
+ count
136
+ end
137
+
138
+ # The next window's `from` per the isTruncated rule, or nil once the sync has caught up (an
139
+ # empty window, or an HWM that did not advance — the window then only repeated its boundary).
140
+ # A closed window continues where it ended, even when empty: at `to`, or at the HWM if lower.
141
+ def next_window_start(package, to)
142
+ if package["isTruncated"]
143
+ last = package["lastPermanentStorageDate"]
144
+ return last if later?(last, @hwm)
145
+
146
+ raise Error, "Export window truncated at #{last.inspect} without moving past #{@hwm.inspect}"
147
+ end
148
+
149
+ hwm = package["permanentStorageHwmDate"]
150
+ if to
151
+ ended = hwm && later?(to, hwm) ? hwm : to
152
+ return later?(ended, @hwm) ? ended : nil
153
+ end
154
+ return nil if hwm.nil? || Array(package["parts"]).empty? || package["invoiceCount"]&.zero?
155
+
156
+ hwm if later?(hwm, @hwm)
157
+ end
158
+
159
+ # Compares instants, not strings — the caller's `from` and the server's dates differ in format.
160
+ def later?(candidate, current)
161
+ return false if candidate.nil?
162
+
163
+ Time.iso8601(candidate) > Time.iso8601(current)
164
+ rescue ArgumentError
165
+ candidate.to_s > current.to_s
166
+ end
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+ require "openssl"
6
+ require "time"
7
+ require "ksef"
8
+
9
+ Ksef.require_optional("webmock", "Ksef::Testing")
10
+
11
+ module Ksef
12
+ # WebMock stubs of the endpoints behind the gem's flows, for an application's own tests: `require
13
+ # "ksef/testing"` and `include Ksef::Testing` where WebMock is enabled. Not loaded by `require "ksef"`.
14
+ # Responses follow the contract's schemas; the Ministry certificate is a real key the gem encrypts with.
15
+ module Testing
16
+ include WebMock::API
17
+
18
+ # Test value handed out by {#stub_ksef_authentication}.
19
+ ACCESS_TOKEN = "ksef-test-access-token"
20
+ # Test value handed out by {#stub_ksef_authentication}.
21
+ REFRESH_TOKEN = "ksef-test-refresh-token"
22
+ # Reference number of the session opened by {#stub_ksef_online_session}.
23
+ SESSION_REFERENCE = "20261012-SO-0000000000-0000000000-01"
24
+ # Reference number of each invoice sent through {#stub_ksef_online_session}.
25
+ INVOICE_REFERENCE = "20261012-EE-0000000000-0000000000-01"
26
+ # Validity of the stubbed Ministry certificate: fixed and wide, so that a test that travels in time
27
+ # (travel_to, Timecop) still finds it valid.
28
+ CERTIFICATE_VALIDITY = (Time.utc(2000, 1, 1)..Time.utc(2099, 12, 31))
29
+
30
+ # The Ministry public-key certificates (both encryption usages).
31
+ # @param config [Ksef::Configuration] whose environment is stubbed
32
+ # @return [WebMock::RequestStub]
33
+ def stub_ksef_public_keys(config: Ksef.config)
34
+ stub_request(:get, "#{config.api_url}/security/public-key-certificates")
35
+ .to_return(Testing.json(Testing.ministry_certificates))
36
+ end
37
+
38
+ # Sign-in with a KSeF token or an XAdES signature — challenge, submission, status 200, redemption —
39
+ # and the access token refresh. Stubs the public keys too (the token is encrypted with them).
40
+ # @param config [Ksef::Configuration]
41
+ # @param access_token [String] handed out on redemption and refresh
42
+ # @param refresh_token [String]
43
+ # @return [void]
44
+ def stub_ksef_authentication(config: Ksef.config, access_token: ACCESS_TOKEN, refresh_token: REFRESH_TOKEN)
45
+ api = config.api_url
46
+ stub_ksef_public_keys(config: config)
47
+ stub_request(:post, "#{api}/auth/challenge").to_return(Testing.json(Testing.challenge))
48
+ init = Testing.json({ referenceNumber: "20261012-AU-0000000000-0000000000-01",
49
+ authenticationToken: Testing.token("ksef-test-authentication-token") }, status: 202)
50
+ stub_request(:post, "#{api}/auth/ksef-token").to_return(init)
51
+ stub_request(:post, "#{api}/auth/xades-signature").with(query: hash_including({})).to_return(init)
52
+ stub_request(:get, %r{\A#{Regexp.escape(api)}/auth/\d{8}-AU-}).to_return(Testing.json(Testing.auth_status))
53
+ stub_request(:post, "#{api}/auth/token/redeem").to_return(
54
+ Testing.json({ accessToken: Testing.token(access_token),
55
+ refreshToken: Testing.token(refresh_token, 7 * 86_400) })
56
+ )
57
+ refreshed = Testing.json({ accessToken: Testing.token(access_token) })
58
+ stub_request(:post, "#{api}/auth/token/refresh").to_return(refreshed)
59
+ end
60
+
61
+ # An interactive session in which every invoice is accepted: open, send, close, the invoice status
62
+ # (200, with +ksef_number+) and its UPO. Stubs the public keys too.
63
+ # @param ksef_number [String] KSeF number of the accepted invoices; a valid one by default
64
+ # @param upo [String] UPO XML returned for them
65
+ # @param config [Ksef::Configuration]
66
+ # @return [void]
67
+ def stub_ksef_online_session(ksef_number: Testing.ksef_number, upo: "<Potwierdzenie/>", config: Ksef.config)
68
+ api = config.api_url
69
+ session = "#{api}/sessions/online/#{SESSION_REFERENCE}"
70
+ invoice = "#{api}/sessions/#{SESSION_REFERENCE}/invoices/#{INVOICE_REFERENCE}"
71
+ stub_ksef_public_keys(config: config)
72
+ stub_request(:post, "#{api}/sessions/online").to_return(
73
+ Testing.json({ referenceNumber: SESSION_REFERENCE, validUntil: (Time.now + 43_200).utc.iso8601 }, status: 201)
74
+ )
75
+ sent = Testing.json({ referenceNumber: INVOICE_REFERENCE }, status: 202)
76
+ stub_request(:post, "#{session}/invoices").to_return(sent)
77
+ stub_request(:post, "#{session}/close").to_return(status: 204)
78
+ stub_request(:get, invoice).to_return(Testing.json(Testing.accepted_invoice(ksef_number)))
79
+ stub_request(:get, "#{invoice}/upo").to_return(status: 200, headers: { "Content-Type" => "application/xml" },
80
+ body: upo)
81
+ end
82
+
83
+ class << self
84
+ # A KSeF number with a valid checksum.
85
+ # @param seller_nip [String] spaces, hyphens and a "PL" prefix are stripped
86
+ # @param date [Date]
87
+ # @return [String]
88
+ # @raise [Ksef::ConfigurationError] for an invalid NIP, or a date the KSeF number pattern refuses
89
+ def ksef_number(seller_nip: "5555555555", date: Date.new(2026, 10, 12))
90
+ data = "#{Nip.normalize!(seller_nip, name: 'seller_nip')}-#{date.strftime('%Y%m%d')}-0100001AF629"
91
+ KsefNumber.new("#{data}-#{format('%02X', KsefNumber.crc8(data))}").validate!.to_s
92
+ end
93
+
94
+ # @api private
95
+ def ministry_certificates
96
+ @ministry_certificates ||= begin
97
+ der = Base64.strict_encode64(ministry_certificate.to_der)
98
+ %w[SymmetricKeyEncryption KsefTokenEncryption].map do |usage|
99
+ { certificate: der, certificateId: Base64.strict_encode64("test-#{usage}"), usage: [usage],
100
+ publicKeyId: Base64.strict_encode64(usage.ljust(32, "0")),
101
+ validFrom: CERTIFICATE_VALIDITY.begin.iso8601, validTo: CERTIFICATE_VALIDITY.end.iso8601 }
102
+ end
103
+ end
104
+ end
105
+
106
+ # @api private
107
+ def json(body, status: 200)
108
+ { status: status, headers: { "Content-Type" => "application/json" }, body: JSON.generate(body) }
109
+ end
110
+
111
+ # @api private
112
+ def token(value, seconds = 900)
113
+ { token: value, validUntil: (Time.now + seconds).utc.iso8601 }
114
+ end
115
+
116
+ # @api private
117
+ def challenge
118
+ now = Time.now
119
+ { challenge: "20261012-CR-0000000000-0000000000-01", timestamp: now.utc.iso8601(3),
120
+ timestampMs: (now.to_f * 1000).to_i, clientIp: "127.0.0.1" }
121
+ end
122
+
123
+ # @api private
124
+ def auth_status
125
+ { startDate: Time.now.utc.iso8601, authenticationMethod: "Token",
126
+ authenticationMethodInfo: { category: "Token", code: "token", displayName: "Token KSeF" },
127
+ status: { code: 200, description: "Uwierzytelnianie zakończone sukcesem" } }
128
+ end
129
+
130
+ # @api private
131
+ def accepted_invoice(ksef_number)
132
+ { ordinalNumber: 1, referenceNumber: INVOICE_REFERENCE, ksefNumber: ksef_number,
133
+ invoiceHash: Base64.strict_encode64("0" * 32), invoicingDate: Time.now.utc.iso8601,
134
+ status: { code: 200, description: "Sukces" } }
135
+ end
136
+
137
+ private
138
+
139
+ def ministry_certificate
140
+ key = OpenSSL::PKey::RSA.new(2048)
141
+ cert = OpenSSL::X509::Certificate.new
142
+ cert.version = 2
143
+ cert.serial = 1
144
+ cert.subject = cert.issuer = OpenSSL::X509::Name.parse("/CN=KSeF test Ministry key")
145
+ cert.public_key = key.public_key
146
+ cert.not_before = CERTIFICATE_VALIDITY.begin
147
+ cert.not_after = CERTIFICATE_VALIDITY.end
148
+ cert.sign(key, OpenSSL::Digest.new("SHA256"))
149
+ cert
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Ksef
8
+ # Optional, thread-safe token manager: holds the access/refresh pair and refreshes the accessToken
9
+ # before it expires — at `validUntil`, or at the token's own JWT `exp` claim when that is not given.
10
+ # A refreshed token that already expires within the skew is used until it expires, so a skew longer
11
+ # than the token's lifetime does not turn into a refresh per request.
12
+ class TokenManager
13
+ # Default margin (s) before expiry at which the token is refreshed.
14
+ DEFAULT_SKEW = 60
15
+
16
+ # @param client [Ksef::Client]
17
+ # @param access_token [String]
18
+ # @param refresh_token [String]
19
+ # @param access_token_valid_until [String, Time, DateTime, nil] accessToken expiry time; nil reads the
20
+ # `exp` claim of the access token (a JWT)
21
+ # @param skew [Integer] safety margin before expiry (s)
22
+ # @param on_refresh [#call, nil] called with the new access token and its expiry (Time, nil when
23
+ # unknown) after every refresh — e.g. to persist them. It runs outside the manager's lock, so it may
24
+ # use the manager or its client; an exception it raises propagates, and the callback runs again on
25
+ # the next {#access_token}
26
+ def initialize(client, access_token:, refresh_token:, access_token_valid_until: nil, skew: DEFAULT_SKEW,
27
+ on_refresh: nil)
28
+ @client = client
29
+ @access_token = access_token
30
+ @refresh_token = refresh_token
31
+ @valid_until = parse_time(access_token_valid_until) || jwt_expiry(access_token)
32
+ @skew = skew
33
+ @skew_active = true
34
+ @on_refresh = on_refresh
35
+ @mutex = Mutex.new
36
+ end
37
+
38
+ # Returns a valid accessToken, refreshing it when needed (thread-safe).
39
+ # @return [String]
40
+ def access_token
41
+ token, pending = @mutex.synchronize do
42
+ refresh_locked! if expired?
43
+ [@access_token, @pending_callback]
44
+ end
45
+ notify(pending) if pending
46
+ token
47
+ end
48
+
49
+ # @return [String] the current refreshToken
50
+ attr_reader :refresh_token
51
+
52
+ # @return [Time, nil] expiry of the current accessToken, nil when unknown
53
+ def access_token_valid_until
54
+ @mutex.synchronize { @valid_until }
55
+ end
56
+
57
+ # Forces an accessToken refresh.
58
+ # @return [String] the new accessToken
59
+ def force_refresh!
60
+ token, pending = @mutex.synchronize { [refresh_locked!, @pending_callback] }
61
+ notify(pending) if pending
62
+ token
63
+ end
64
+
65
+ # Keeps both tokens out of error pages, `pp` output and exception reports.
66
+ # @return [String]
67
+ def inspect
68
+ "#<#{self.class.name} valid_until=#{@valid_until.inspect} access_token=[REDACTED] refresh_token=[REDACTED]>"
69
+ end
70
+
71
+ private
72
+
73
+ def expired?
74
+ return true if @access_token.nil?
75
+ return false if @valid_until.nil?
76
+
77
+ Time.now >= (@skew_active ? @valid_until - @skew : @valid_until)
78
+ end
79
+
80
+ # A response without a token keeps the current one.
81
+ def refresh_locked!
82
+ response = @client.auth.refresh(refresh_token: @refresh_token)
83
+ token = response["accessToken"].is_a?(Hash) ? response["accessToken"]["token"] : nil
84
+ raise ApiError, "POST /auth/token/refresh: KSeF's response lacks accessToken.token" if token.to_s.empty?
85
+
86
+ @access_token = token
87
+ @valid_until = parse_time(response.dig("accessToken", "validUntil")) || jwt_expiry(@access_token)
88
+ @skew_active = @valid_until.nil? || @valid_until - Time.now > @skew
89
+ @pending_callback = [@access_token, @valid_until] if @on_refresh
90
+ @access_token
91
+ end
92
+
93
+ # Claims the pending callback (one thread runs it), and puts it back when it fails.
94
+ def notify(pending)
95
+ @mutex.synchronize do
96
+ return unless @pending_callback.equal?(pending)
97
+
98
+ @pending_callback = nil
99
+ end
100
+ begin
101
+ @on_refresh.call(*pending)
102
+ rescue StandardError
103
+ @mutex.synchronize { @pending_callback ||= pending }
104
+ raise
105
+ end
106
+ end
107
+
108
+ def parse_time(value)
109
+ return nil if value.nil?
110
+ return value if value.is_a?(Time)
111
+ return value.to_time if value.respond_to?(:to_time) && !value.is_a?(String)
112
+
113
+ Time.iso8601(value.to_s)
114
+ rescue ArgumentError, TypeError
115
+ nil
116
+ end
117
+
118
+ # The `exp` claim (seconds since the epoch) of a JWT, read without verifying the signature — it
119
+ # only decides when to refresh.
120
+ def jwt_expiry(token)
121
+ payload = token.to_s.split(".")[1]
122
+ return nil if payload.nil? || payload.empty?
123
+
124
+ exp = JSON.parse(Base64.urlsafe_decode64(payload))["exp"]
125
+ exp.is_a?(Numeric) ? Time.at(exp) : nil
126
+ rescue ArgumentError, TypeError, JSON::ParserError
127
+ nil
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ksef
4
+ # Gem version. Tracks compatibility with the KSeF API contract version below.
5
+ VERSION = "1.0.0"
6
+
7
+ # KSeF API contract version this gem targets — the OpenAPI document in spec/fixtures/openapi/,
8
+ # which the contract suite checks every request against. Bumped together with that file (see
9
+ # api-changelog.md in CIRFMF/ksef-api).
10
+ API_VERSION = "2.8.1"
11
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nokogiri"
4
+ require "ksef/errors"
5
+ require "ksef/models/nip"
6
+
7
+ module Ksef
8
+ module Xades
9
+ # Builder for the `AuthTokenRequest` XML document (schemat_auth_v2-0.xsd).
10
+ # Element order per the XSD: Challenge, ContextIdentifier, SubjectIdentifierType,
11
+ # optional AuthorizationPolicy → AllowedIps (up to 10 entries of each type).
12
+ class AuthTokenRequest
13
+ NAMESPACE = "http://ksef.mf.gov.pl/auth/token/2.0"
14
+
15
+ # Allowed context types → XSD element name.
16
+ CONTEXT_ELEMENTS = {
17
+ nip: "Nip",
18
+ internal_id: "InternalId",
19
+ nip_vat_ue: "NipVatUe",
20
+ peppol_id: "PeppolId"
21
+ }.freeze
22
+
23
+ # Allowed ways of identifying the subject → XSD element value.
24
+ SUBJECT_IDENTIFIER_TYPES = {
25
+ certificate_subject: "certificateSubject",
26
+ certificate_fingerprint: "certificateFingerprint"
27
+ }.freeze
28
+
29
+ # `allowed_ips` keys → AllowedIps element names, in XSD order.
30
+ ALLOWED_IP_ELEMENTS = { addresses: "Ip4Address", ranges: "Ip4Range", masks: "Ip4Mask" }.freeze
31
+ # Most entries of one AllowedIps type (`maxOccurs`).
32
+ MAX_ALLOWED_IPS = 10
33
+
34
+ # @return [String, nil] value from POST /auth/challenge — may be set after the other inputs were checked
35
+ attr_accessor :challenge
36
+
37
+ # @param challenge [String, nil] value from POST /auth/challenge (36 characters); required by {#to_xml}
38
+ # @param context [Hash] exactly one of: {nip:}, {internal_id:}, {nip_vat_ue:}, {peppol_id:}; a NIP
39
+ # is normalized ({Ksef::Nip.normalize!})
40
+ # @param subject_identifier_type [Symbol] :certificate_subject or :certificate_fingerprint
41
+ # @param allowed_ips [Hash, nil] optional: {addresses:[], ranges:[], masks:[]} (symbol or string
42
+ # keys); no entries means no AuthorizationPolicy
43
+ # @raise [Ksef::ConfigurationError] for an unknown or malformed context, an invalid NIP, subject type,
44
+ # allowed_ips key or more than {MAX_ALLOWED_IPS} entries of one type
45
+ def initialize(context:, challenge: nil, subject_identifier_type: :certificate_subject, allowed_ips: nil)
46
+ @challenge = challenge
47
+ @context = normalize_context(context)
48
+ @subject_identifier_type = fetch_subject_type(subject_identifier_type)
49
+ @allowed_ips = normalize_allowed_ips(allowed_ips)
50
+ end
51
+
52
+ # @return [String] XML document (unsigned; to be passed to {Signer})
53
+ # @raise [Ksef::ConfigurationError] without a challenge
54
+ def to_xml
55
+ build_document.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
56
+ end
57
+
58
+ # @return [Nokogiri::XML::Document]
59
+ # @raise [Ksef::ConfigurationError] without a challenge
60
+ def to_document
61
+ build_document
62
+ end
63
+
64
+ private
65
+
66
+ def build_document
67
+ raise ConfigurationError, "AuthTokenRequest needs the challenge" if @challenge.to_s.empty?
68
+
69
+ Nokogiri::XML::Builder.new(encoding: "UTF-8") do |xml|
70
+ xml.AuthTokenRequest(xmlns: NAMESPACE) do
71
+ xml.Challenge(@challenge)
72
+ xml.ContextIdentifier do
73
+ xml.send(@context[:element], @context[:value])
74
+ end
75
+ xml.SubjectIdentifierType(@subject_identifier_type)
76
+ build_authorization_policy(xml) unless @allowed_ips.empty?
77
+ end
78
+ end.doc
79
+ end
80
+
81
+ def build_authorization_policy(xml)
82
+ xml.AuthorizationPolicy do
83
+ xml.AllowedIps do
84
+ @allowed_ips.each { |element, ip| xml.send(element, ip) }
85
+ end
86
+ end
87
+ end
88
+
89
+ # @return [Array<Array(String, String)>] [element, value] pairs in XSD order
90
+ def normalize_allowed_ips(allowed_ips)
91
+ unless allowed_ips.nil? || allowed_ips.is_a?(Hash)
92
+ raise ConfigurationError, "allowed_ips must be a Hash ({addresses:, ranges:, masks:})"
93
+ end
94
+
95
+ ips = (allowed_ips || {}).transform_keys(&:to_sym)
96
+ unknown = ips.keys - ALLOWED_IP_ELEMENTS.keys
97
+ unless unknown.empty?
98
+ raise ConfigurationError,
99
+ "allowed_ips accepts only #{ALLOWED_IP_ELEMENTS.keys.join(', ')} (got #{unknown.join(', ')})"
100
+ end
101
+
102
+ ALLOWED_IP_ELEMENTS.flat_map do |key, element|
103
+ list = Array(ips[key])
104
+ raise ConfigurationError, "allowed_ips #{key}: at most #{MAX_ALLOWED_IPS} entries" if
105
+ list.size > MAX_ALLOWED_IPS
106
+
107
+ list.map { |ip| [element, ip.to_s] }
108
+ end
109
+ end
110
+
111
+ def normalize_context(context)
112
+ unless context.is_a?(Hash)
113
+ raise ConfigurationError, "context must be a Hash with exactly one of: #{CONTEXT_ELEMENTS.keys.join(', ')}"
114
+ end
115
+
116
+ pairs = context.transform_keys(&:to_sym)
117
+ key, value = pairs.first
118
+ unless pairs.size == 1 && CONTEXT_ELEMENTS.key?(key)
119
+ raise ConfigurationError,
120
+ "context must contain exactly one of: #{CONTEXT_ELEMENTS.keys.join(', ')}"
121
+ end
122
+
123
+ value = key == :nip ? Nip.normalize!(value, name: "context nip") : value.to_s
124
+ { element: CONTEXT_ELEMENTS.fetch(key), value: value }
125
+ end
126
+
127
+ def fetch_subject_type(type)
128
+ SUBJECT_IDENTIFIER_TYPES.fetch(type.respond_to?(:to_sym) ? type.to_sym : nil) do
129
+ raise ConfigurationError,
130
+ "subject_identifier_type must be one of: #{SUBJECT_IDENTIFIER_TYPES.keys.join(', ')}"
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ksef
4
+ module Xades
5
+ # Replaces the ENTIRE XAdES signature with a lambda or object — qualified signature, HSM,
6
+ # EU DSS sidecar. A signer responds to +#sign(xml)+ or +#call(xml)+;
7
+ # {.wrap} normalizes both.
8
+ class ExternalSigner
9
+ # @param callable [#call] object/lambda taking XML and returning signed XML
10
+ # @raise [Ksef::ConfigurationError] when it does not respond to #call
11
+ def initialize(callable)
12
+ unless callable.respond_to?(:call)
13
+ raise ConfigurationError, "ExternalSigner requires an object responding to #call"
14
+ end
15
+
16
+ @callable = callable
17
+ end
18
+
19
+ # @param xml [String] document to sign
20
+ # @return [String] the signed document
21
+ # @raise [Ksef::CryptoError] when the callable returns anything but a non-empty String
22
+ def sign(xml)
23
+ self.class.signed!(@callable.call(xml))
24
+ end
25
+
26
+ # Normalizes a signer into an object responding to +#sign(xml)+.
27
+ # @param signer [#sign, #call]
28
+ # @return [#sign]
29
+ # @raise [Ksef::ConfigurationError] when it responds to neither, or is a key (OpenSSL::PKey#sign signs a
30
+ # digest, not a document — pass a {Signer})
31
+ def self.wrap(signer)
32
+ if signer.is_a?(OpenSSL::PKey::PKey)
33
+ raise ConfigurationError, "signer is a key — wrap it with its certificate in Ksef::Xades::Signer"
34
+ end
35
+ return signer if signer.respond_to?(:sign) && one_argument?(signer.method(:sign))
36
+ return new(signer) if signer.respond_to?(:call)
37
+
38
+ raise ConfigurationError, "signer must respond to #sign(xml) or #call(xml)"
39
+ end
40
+
41
+ # @api private
42
+ # @param result [Object] what a signer returned
43
+ # @return [String]
44
+ # @raise [Ksef::CryptoError] unless it is a non-empty String
45
+ def self.signed!(result)
46
+ return result if result.is_a?(String) && !result.strip.empty?
47
+
48
+ raise CryptoError, "the signer returned #{result.nil? ? 'nil' : "a #{result.class}"} instead of the signed XML"
49
+ end
50
+
51
+ def self.one_argument?(method)
52
+ required = method.parameters.count { |type, _| type == :req }
53
+ required == 1 || (required.zero? && method.parameters.any? { |type, _| %i[opt rest].include?(type) })
54
+ end
55
+ private_class_method :one_argument?
56
+ end
57
+ end
58
+ end