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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +161 -0
- data/NOTICE +40 -0
- data/README.md +524 -6
- data/examples/fa3_full.xml +143 -0
- data/examples/fa3_minimal.xml +65 -0
- data/examples/fa3_typical.xml +76 -0
- data/lib/generators/ksef/install/install_generator.rb +20 -0
- data/lib/generators/ksef/install/templates/ksef.rb +25 -0
- data/lib/ksef/auth/coordinator.rb +164 -0
- data/lib/ksef/auth/ksef_token_encryptor.rb +36 -0
- data/lib/ksef/batch/package_builder.rb +125 -0
- data/lib/ksef/batch/splitter.rb +99 -0
- data/lib/ksef/batch/uploader.rb +114 -0
- data/lib/ksef/client.rb +135 -0
- data/lib/ksef/configuration.rb +206 -0
- data/lib/ksef/crypto/cryptography_service.rb +136 -0
- data/lib/ksef/crypto/csr.rb +106 -0
- data/lib/ksef/crypto/public_keys.rb +125 -0
- data/lib/ksef/environments.rb +61 -0
- data/lib/ksef/errors.rb +187 -0
- data/lib/ksef/http/connection.rb +432 -0
- data/lib/ksef/http/error_parser.rb +194 -0
- data/lib/ksef/http/pagination.rb +80 -0
- data/lib/ksef/invoices/builder/checks.rb +127 -0
- data/lib/ksef/invoices/builder/number.rb +67 -0
- data/lib/ksef/invoices/builder/xml.rb +256 -0
- data/lib/ksef/invoices/builder.rb +251 -0
- data/lib/ksef/invoices/export.rb +241 -0
- data/lib/ksef/invoices/sample.rb +78 -0
- data/lib/ksef/invoices/schema_outline.rb +120 -0
- data/lib/ksef/invoices/validator.rb +200 -0
- data/lib/ksef/models/form_code.rb +49 -0
- data/lib/ksef/models/ksef_number.rb +74 -0
- data/lib/ksef/models/nip.rb +62 -0
- data/lib/ksef/polish_time.rb +49 -0
- data/lib/ksef/polling.rb +65 -0
- data/lib/ksef/qr/code.rb +104 -0
- data/lib/ksef/qr/verification_link.rb +215 -0
- data/lib/ksef/railtie.rb +20 -0
- data/lib/ksef/resources/auth.rb +116 -0
- data/lib/ksef/resources/base.rb +120 -0
- data/lib/ksef/resources/batch_sessions.rb +43 -0
- data/lib/ksef/resources/certificates.rb +82 -0
- data/lib/ksef/resources/collective_identifiers.rb +70 -0
- data/lib/ksef/resources/exports.rb +47 -0
- data/lib/ksef/resources/invoices.rb +67 -0
- data/lib/ksef/resources/limits.rb +33 -0
- data/lib/ksef/resources/online_sessions.rb +62 -0
- data/lib/ksef/resources/peppol.rb +21 -0
- data/lib/ksef/resources/permissions.rb +180 -0
- data/lib/ksef/resources/security.rb +18 -0
- data/lib/ksef/resources/sessions.rb +125 -0
- data/lib/ksef/resources/test_data.rb +178 -0
- data/lib/ksef/resources/tokens.rb +62 -0
- data/lib/ksef/sessions/online.rb +168 -0
- data/lib/ksef/sync/incremental.rb +169 -0
- data/lib/ksef/testing.rb +153 -0
- data/lib/ksef/token_manager.rb +130 -0
- data/lib/ksef/version.rb +11 -0
- data/lib/ksef/xades/auth_token_request.rb +135 -0
- data/lib/ksef/xades/external_signer.rb +58 -0
- data/lib/ksef/xades/signer.rb +312 -0
- data/lib/ksef-client-rails.rb +3 -2
- data/lib/ksef.rb +116 -0
- data/schemas/FA/schemat_FA(2)_v1-0E.xsd +3661 -0
- data/schemas/FA/schemat_FA(3)_v1-0E.xsd +3950 -0
- data/schemas/README.md +53 -0
- data/schemas/RR/schemat_FA_RR(1)_v1-1E.xsd +2188 -0
- data/schemas/bazowe/ElementarneTypyDanych_v10-0E.xsd +1 -0
- data/schemas/bazowe/KodyKrajow_v10-0E.xsd +1283 -0
- data/schemas/bazowe/StrukturyDanych_v10-0E.xsd +1 -0
- metadata +291 -9
data/lib/ksef/qr/code.rb
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ksef
|
|
4
|
+
module Qr
|
|
5
|
+
# Renders a QR code from a verification link; the SVG carries the label KSeF prescribes below
|
|
6
|
+
# the code. Requires the optional `rqrcode` gem, loaded lazily.
|
|
7
|
+
class Code
|
|
8
|
+
# Quiet zone (modules of white border) required by ISO/IEC 18004.
|
|
9
|
+
QUIET_ZONE = 4
|
|
10
|
+
# Height of the label band below the quiet zone, in modules.
|
|
11
|
+
LABEL_BAND = 6
|
|
12
|
+
# Largest label font size, in modules; a long label (a KSeF number) shrinks to the code's width.
|
|
13
|
+
LABEL_MAX_FONT = 3
|
|
14
|
+
# Advance of one monospace glyph, in em — what sizes the label to fit.
|
|
15
|
+
MONOSPACE_ADVANCE = 0.6
|
|
16
|
+
# Colours the SVG accepts: hex digits without "#" (String) or a colour name (Symbol).
|
|
17
|
+
HEX_COLOR = /\A(?:\h{3}|\h{4}|\h{6}|\h{8})\z/
|
|
18
|
+
NAMED_COLOR = /\A[a-z]+\z/i
|
|
19
|
+
|
|
20
|
+
# @return [String] the encoded link
|
|
21
|
+
attr_reader :data
|
|
22
|
+
# @return [String, nil] label below the code — the KSeF number or "OFFLINE" (CODE I),
|
|
23
|
+
# "CERTYFIKAT" (CODE II); KSeF prescribes these Polish labels
|
|
24
|
+
attr_reader :label
|
|
25
|
+
|
|
26
|
+
# @param data [String] verification link to encode
|
|
27
|
+
# @param label [String, nil] label printed below the code
|
|
28
|
+
def initialize(data, label: nil)
|
|
29
|
+
@data = data
|
|
30
|
+
@label = label
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# @return [RQRCode::QRCode]
|
|
34
|
+
# @raise [Ksef::ConfigurationError] when rqrcode is not installed
|
|
35
|
+
def qrcode
|
|
36
|
+
@qrcode ||= begin
|
|
37
|
+
Ksef.require_optional("rqrcode", "QR rendering")
|
|
38
|
+
RQRCode::QRCode.new(@data, level: :m)
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Scalable by CSS (`viewBox`, no fixed width/height — a fixed-size SVG squeezed by CSS gets
|
|
43
|
+
# cropped, not scaled, and no phone can read it), with the 4-module white quiet zone the QR
|
|
44
|
+
# standard requires and the {#label} centred below it.
|
|
45
|
+
# @param module_size [Integer] user units per module (the coordinate scale; CSS sets the size)
|
|
46
|
+
# @param color [String, Symbol] colour of the modules and the label: hex without "#", or a name
|
|
47
|
+
# @return [String] QR code as SVG
|
|
48
|
+
# @raise [Ksef::ConfigurationError] for any other colour (it is written into SVG attributes)
|
|
49
|
+
def as_svg(module_size: 11, color: "000")
|
|
50
|
+
validate_color!(color)
|
|
51
|
+
size = (qrcode.modules.length + (2 * QUIET_ZONE)) * module_size
|
|
52
|
+
height = label? ? size + (LABEL_BAND * module_size) : size
|
|
53
|
+
modules = qrcode.as_svg(standalone: false, use_path: true, module_size: module_size,
|
|
54
|
+
offset: QUIET_ZONE * module_size, color: color)
|
|
55
|
+
root = %(xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 #{size} #{height}")
|
|
56
|
+
[
|
|
57
|
+
%(<svg #{root} shape-rendering="crispEdges">),
|
|
58
|
+
%(<rect width="#{size}" height="#{height}" fill="#fff"/>),
|
|
59
|
+
modules,
|
|
60
|
+
label_svg(size, module_size, color),
|
|
61
|
+
"</svg>"
|
|
62
|
+
].join
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# @param options [Hash] passed to rqrcode (e.g. size, border_modules)
|
|
66
|
+
# @return [String] the code alone (no label) as binary PNG data
|
|
67
|
+
def as_png(**)
|
|
68
|
+
qrcode.as_png(size: 300, **).to_s
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# @return [String] the code alone (no label) as an ANSI terminal preview
|
|
72
|
+
def as_ascii
|
|
73
|
+
qrcode.as_ansi
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def label?
|
|
79
|
+
!label.to_s.empty?
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def validate_color!(color)
|
|
83
|
+
valid = color.is_a?(Symbol) ? color.to_s.match?(NAMED_COLOR) : color.is_a?(String) && color.match?(HEX_COLOR)
|
|
84
|
+
return if valid
|
|
85
|
+
|
|
86
|
+
raise ConfigurationError, "color must be hex digits without \"#\" or a Symbol colour name, got #{color.inspect}"
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def label_svg(size, module_size, color)
|
|
90
|
+
return "" unless label?
|
|
91
|
+
|
|
92
|
+
text = label.to_s
|
|
93
|
+
font = [LABEL_MAX_FONT * module_size, (size - (2 * module_size)) / (text.length * MONOSPACE_ADVANCE)].min
|
|
94
|
+
baseline = size + (((LABEL_BAND * module_size) + (0.7 * font)) / 2)
|
|
95
|
+
fill = color.is_a?(Symbol) ? color : "##{color}"
|
|
96
|
+
attributes = [
|
|
97
|
+
%(x="#{size / 2.0}"), %(y="#{baseline.round(2)}"), 'text-anchor="middle"', 'font-family="monospace"',
|
|
98
|
+
%(font-size="#{font.round(2)}"), 'font-weight="bold"', %(fill="#{fill}")
|
|
99
|
+
].join(" ")
|
|
100
|
+
"<text #{attributes}>#{text.encode(xml: :text)}</text>"
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "base64"
|
|
5
|
+
require "digest"
|
|
6
|
+
require "date"
|
|
7
|
+
require "nokogiri"
|
|
8
|
+
require "ksef/errors"
|
|
9
|
+
require "ksef/models/nip"
|
|
10
|
+
|
|
11
|
+
module Ksef
|
|
12
|
+
module Qr
|
|
13
|
+
# Builds KSeF verification links for QR codes. CODE I is
|
|
14
|
+
# `{qr}/invoice/{nip}/{DD-MM-YYYY}/{hash}`; CODE II appends a signature over the path fragment
|
|
15
|
+
# taken WITHOUT the `https://` prefix and trailing `/` (RSASSA-PSS or ECDSA P-256, Base64URL).
|
|
16
|
+
class VerificationLink
|
|
17
|
+
# Context identifier type → the pattern of its value in the contract.
|
|
18
|
+
CONTEXT_TYPES = {
|
|
19
|
+
"Nip" => Nip::PATTERN,
|
|
20
|
+
"InternalId" => /\A[1-9]((\d[1-9])|([1-9]\d))\d{7}-\d{5}\z/,
|
|
21
|
+
"NipVatUe" => /\A[1-9]((\d[1-9])|([1-9]\d))\d{7}-[A-Z]{2}[A-Z0-9+*]{2,12}\z/,
|
|
22
|
+
"PeppolId" => /\AP[A-Z]{2}\d{6}\z/
|
|
23
|
+
}.freeze
|
|
24
|
+
# The authentication API's context keys ({Ksef::Auth::Coordinator::CONTEXT_TYPES}).
|
|
25
|
+
CONTEXT_KEYS = { nip: "Nip", internal_id: "InternalId", nip_vat_ue: "NipVatUe", peppol_id: "PeppolId" }.freeze
|
|
26
|
+
DATE_SEGMENT = /\A\d{2}-\d{2}-\d{4}\z/
|
|
27
|
+
# A KSeF certificate serial number: 16 uppercase hex digits.
|
|
28
|
+
SERIAL_SEGMENT = /\A[0-9A-F]{16}\z/
|
|
29
|
+
|
|
30
|
+
# @param qr_base_url [String] environment QR host (e.g. "https://qr-test.ksef.mf.gov.pl")
|
|
31
|
+
def initialize(qr_base_url:)
|
|
32
|
+
@qr_base_url = qr_base_url.chomp("/")
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Builds one from the client configuration.
|
|
36
|
+
# @param client [Ksef::Client]
|
|
37
|
+
# @return [VerificationLink]
|
|
38
|
+
def self.from_client(client)
|
|
39
|
+
new(qr_base_url: client.config.qr_url)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# CODE I — link to an online invoice.
|
|
43
|
+
#
|
|
44
|
+
# @param seller_nip [String, Ksef::Nip] seller tax ID; separators and a "PL" prefix are stripped
|
|
45
|
+
# @param issue_date [Date, String, nil] issue date (P_1): a Date, "YYYY-MM-DD" or "DD-MM-YYYY"; nil reads
|
|
46
|
+
# `Fa/P_1` from invoice_xml. A Time is refused — its calendar day depends on its zone.
|
|
47
|
+
# @param invoice_xml [String, nil] invoice content (to compute the digest)
|
|
48
|
+
# @param invoice_hash [String, nil] precomputed SHA-256 digest, Base64URL or Base64 (as KSeF's
|
|
49
|
+
# `invoiceHash`), instead of invoice_xml — then with issue_date, as there is no P_1 to read
|
|
50
|
+
# @return [String] full URL
|
|
51
|
+
# @raise [Ksef::ConfigurationError] for an invalid NIP, a date missing, invalid or differing from P_1, or
|
|
52
|
+
# a hash that is not a SHA-256 digest or differs from invoice_xml's
|
|
53
|
+
def online(seller_nip:, issue_date: nil, invoice_xml: nil, invoice_hash: nil)
|
|
54
|
+
hash = invoice_digest(invoice_xml, invoice_hash)
|
|
55
|
+
nip = Nip.normalize!(seller_nip, name: "seller_nip")
|
|
56
|
+
date = link_date(issue_date, invoice_xml)
|
|
57
|
+
"#{@qr_base_url}/invoice/#{nip}/#{date}/#{hash}"
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# CODE II — offline link signed with a KSeF Offline certificate.
|
|
61
|
+
#
|
|
62
|
+
# @param context_type [String, Symbol] "Nip", "InternalId", "NipVatUe" or "PeppolId" — or the
|
|
63
|
+
# authentication API's :nip, :internal_id, :nip_vat_ue, :peppol_id
|
|
64
|
+
# @param context_value [String] context value (a NIP is normalized like seller_nip)
|
|
65
|
+
# @param seller_nip [String, Ksef::Nip] seller tax ID; separators and a "PL" prefix are stripped
|
|
66
|
+
# @param certificate_serial [String, OpenSSL::BN, Integer] the KSeF Offline certificate's serial number:
|
|
67
|
+
# 16 hex digits (`certificateSerialNumber`), or `certificate.serial`
|
|
68
|
+
# @param private_key [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] signing key: RSA of at least 2048 bits, or
|
|
69
|
+
# EC P-256
|
|
70
|
+
# @param invoice_xml [String, nil]
|
|
71
|
+
# @param invoice_hash [String, nil] precomputed SHA-256 digest, Base64URL or Base64
|
|
72
|
+
# @return [String] full URL including the signature
|
|
73
|
+
# @raise [Ksef::ConfigurationError] for an invalid NIP, context, serial or hash
|
|
74
|
+
# @raise [Ksef::CryptoError] for a key without its private part, an RSA key under 2048 bits or another curve
|
|
75
|
+
def offline(context_type:, context_value:, seller_nip:, certificate_serial:, private_key:,
|
|
76
|
+
invoice_xml: nil, invoice_hash: nil)
|
|
77
|
+
hash = invoice_digest(invoice_xml, invoice_hash)
|
|
78
|
+
type = context_type!(context_type)
|
|
79
|
+
base_path = [
|
|
80
|
+
"certificate",
|
|
81
|
+
type,
|
|
82
|
+
context_segment(type, context_value),
|
|
83
|
+
Nip.normalize!(seller_nip, name: "seller_nip"),
|
|
84
|
+
serial!(certificate_serial),
|
|
85
|
+
hash
|
|
86
|
+
].join("/")
|
|
87
|
+
host_path = "#{host}/#{base_path}" # without the https:// prefix and without a trailing /
|
|
88
|
+
signature = sign_base64url(host_path, private_key)
|
|
89
|
+
"#{@qr_base_url}/#{base_path}/#{signature}"
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
private
|
|
93
|
+
|
|
94
|
+
def context_type!(value)
|
|
95
|
+
type = value.is_a?(Symbol) ? CONTEXT_KEYS.fetch(value, value.to_s) : value.to_s
|
|
96
|
+
return type if CONTEXT_TYPES.key?(type)
|
|
97
|
+
|
|
98
|
+
raise ConfigurationError, "context_type must be one of #{CONTEXT_TYPES.keys.join(', ')}, got #{value.inspect}"
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# A NIP context is normalized like seller_nip; other identifiers must match the contract's pattern.
|
|
102
|
+
def context_segment(type, value)
|
|
103
|
+
return Nip.normalize!(value, name: "context_value") if type == "Nip"
|
|
104
|
+
|
|
105
|
+
segment!("context_value", value, CONTEXT_TYPES.fetch(type))
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def serial!(value)
|
|
109
|
+
text = value.is_a?(OpenSSL::BN) || value.is_a?(Integer) ? value.to_s(16).rjust(16, "0") : value.to_s.strip
|
|
110
|
+
segment!("certificate_serial", text.upcase, SERIAL_SEGMENT)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# The SHA-256 digest as Base64URL without padding: computed from the XML, or decoded from the given
|
|
114
|
+
# hash (Base64 or Base64URL) and re-encoded; both must agree when both are given.
|
|
115
|
+
def invoice_digest(xml, hash)
|
|
116
|
+
computed = xml && Base64.urlsafe_encode64(Digest::SHA256.digest(xml.b), padding: false)
|
|
117
|
+
return computed || raise(ConfigurationError, "Provide invoice_xml or invoice_hash") if hash.nil?
|
|
118
|
+
|
|
119
|
+
given = Base64.urlsafe_encode64(decode_hash(hash), padding: false)
|
|
120
|
+
return given if computed.nil? || computed == given
|
|
121
|
+
|
|
122
|
+
raise ConfigurationError, "invoice_hash does not match the SHA-256 of invoice_xml"
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def decode_hash(hash)
|
|
126
|
+
text = hash.to_s.strip.tr("+/", "-_").delete("=")
|
|
127
|
+
bytes = Base64.urlsafe_decode64(text + ("=" * ((4 - (text.length % 4)) % 4)))
|
|
128
|
+
return bytes if bytes.bytesize == 32 && Base64.urlsafe_encode64(bytes, padding: false) == text
|
|
129
|
+
|
|
130
|
+
raise ArgumentError
|
|
131
|
+
rescue ArgumentError
|
|
132
|
+
raise ConfigurationError, "invoice_hash is not a Base64 SHA-256 digest: #{hash.to_s.inspect}"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# @return [String] the value, once it is known to be exactly one path segment
|
|
136
|
+
def segment!(name, value, pattern)
|
|
137
|
+
text = value.to_s
|
|
138
|
+
return text if text.match?(pattern)
|
|
139
|
+
|
|
140
|
+
raise ConfigurationError, "#{name} is not a valid link segment: #{text.inspect}"
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def host
|
|
144
|
+
@qr_base_url.sub(%r{\Ahttps?://}, "")
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# The verifier looks the invoice up by the link's date, so it must be P_1: a wrong day reads
|
|
148
|
+
# "Faktura nie została znaleziona w KSeF".
|
|
149
|
+
def link_date(issue_date, invoice_xml)
|
|
150
|
+
from_xml = invoice_xml && invoice_p1(invoice_xml)
|
|
151
|
+
given = issue_date && format_date(issue_date)
|
|
152
|
+
if from_xml && given && from_xml != given
|
|
153
|
+
raise ConfigurationError, "issue_date #{given} differs from the invoice's P_1 #{from_xml}"
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
given || from_xml || raise(ConfigurationError, "issue_date is required: no Fa/P_1 to read it from")
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def invoice_p1(xml)
|
|
160
|
+
text = Nokogiri::XML(xml).at_xpath("/*[local-name()='Faktura']/*[local-name()='Fa']/*[local-name()='P_1']")&.text
|
|
161
|
+
text && format_date(text.strip)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def format_date(date)
|
|
165
|
+
if date.is_a?(Time) || date.is_a?(DateTime) # TimeWithZone reports itself as a Time
|
|
166
|
+
raise ConfigurationError, "issue_date must be a Date or a date string, not a #{date.class} — pass P_1"
|
|
167
|
+
end
|
|
168
|
+
return date.strftime("%d-%m-%Y") if date.is_a?(Date)
|
|
169
|
+
|
|
170
|
+
text = date.to_s
|
|
171
|
+
return Date.iso8601(text).strftime("%d-%m-%Y") if text.match?(/\A\d{4}-\d{2}-\d{2}\z/)
|
|
172
|
+
return Date.strptime(text, "%d-%m-%Y").strftime("%d-%m-%Y") if text.match?(DATE_SEGMENT)
|
|
173
|
+
|
|
174
|
+
raise Date::Error
|
|
175
|
+
rescue Date::Error
|
|
176
|
+
raise ConfigurationError, "issue_date is not a valid date (YYYY-MM-DD or DD-MM-YYYY): #{date.inspect}"
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# Signs the string according to the key type; result in Base64URL (no padding).
|
|
180
|
+
def sign_base64url(data, key)
|
|
181
|
+
check_key!(key)
|
|
182
|
+
signature = case key
|
|
183
|
+
when OpenSSL::PKey::RSA
|
|
184
|
+
key.sign_pss("SHA256", data, salt_length: 32, mgf1_hash: "SHA256")
|
|
185
|
+
when OpenSSL::PKey::EC
|
|
186
|
+
ecdsa_p1363(key.sign(OpenSSL::Digest.new("SHA256"), data), key)
|
|
187
|
+
else
|
|
188
|
+
raise CryptoError, "Unsupported QR signing key: #{key.class}"
|
|
189
|
+
end
|
|
190
|
+
Base64.urlsafe_encode64(signature, padding: false)
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# The keys a KSeF Offline certificate can carry (kody-qr.md): RSA of 2048 bits or more, EC P-256.
|
|
194
|
+
def check_key!(key)
|
|
195
|
+
return unless key.is_a?(OpenSSL::PKey::RSA) || key.is_a?(OpenSSL::PKey::EC)
|
|
196
|
+
raise CryptoError, "the QR signing key has no private part" unless key.private?
|
|
197
|
+
if key.is_a?(OpenSSL::PKey::RSA) && key.n.num_bits < 2048
|
|
198
|
+
raise CryptoError, "the QR signing key has #{key.n.num_bits} bits; at least 2048 are required"
|
|
199
|
+
end
|
|
200
|
+
return unless key.is_a?(OpenSSL::PKey::EC) && key.group.curve_name != "prime256v1"
|
|
201
|
+
|
|
202
|
+
raise CryptoError, "the QR signing key is on #{key.group.curve_name}; KSeF requires P-256"
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
# ECDSA DER → IEEE P1363 (R‖S) conversion — the recommended form for CODE II.
|
|
206
|
+
def ecdsa_p1363(der, key)
|
|
207
|
+
asn1 = OpenSSL::ASN1.decode(der)
|
|
208
|
+
byte_len = (key.group.degree + 7) / 8
|
|
209
|
+
r = asn1.value[0].value.to_s(2).rjust(byte_len, "\x00")
|
|
210
|
+
s = asn1.value[1].value.to_s(2).rjust(byte_len, "\x00")
|
|
211
|
+
r + s
|
|
212
|
+
end
|
|
213
|
+
end
|
|
214
|
+
end
|
|
215
|
+
end
|
data/lib/ksef/railtie.rb
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/railtie"
|
|
4
|
+
|
|
5
|
+
module Ksef
|
|
6
|
+
# Rails integration, loaded only when Rails is defined: configures the gem from `config.ksef.*` (any
|
|
7
|
+
# {Ksef::Configuration::OPTIONS} key) and logs to `Rails.logger` by default, before the app's
|
|
8
|
+
# initializers run, so `config/initializers/ksef.rb` always has the last word.
|
|
9
|
+
class Railtie < ::Rails::Railtie
|
|
10
|
+
config.ksef = ActiveSupport::OrderedOptions.new if defined?(ActiveSupport::OrderedOptions)
|
|
11
|
+
|
|
12
|
+
initializer "ksef.configure", before: :load_config_initializers do |app|
|
|
13
|
+
options = app.config.respond_to?(:ksef) ? app.config.ksef.to_h : {}
|
|
14
|
+
Ksef.configure do |ksef|
|
|
15
|
+
ksef.logger = ::Rails.logger # `config.ksef.logger` overrides it (nil turns logging off)
|
|
16
|
+
ksef.apply(options)
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
end
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ksef
|
|
4
|
+
module Resources
|
|
5
|
+
# Authentication resource — /auth/* endpoints. Each endpoint names the token it
|
|
6
|
+
# expects in its argument list, so anonymous / authenticationToken / refreshToken / accessToken
|
|
7
|
+
# calls cannot be confused.
|
|
8
|
+
class Auth < Base
|
|
9
|
+
CHALLENGE = "/auth/challenge"
|
|
10
|
+
XADES_SIGNATURE = "/auth/xades-signature"
|
|
11
|
+
KSEF_TOKEN = "/auth/ksef-token"
|
|
12
|
+
TOKEN_REDEEM = "/auth/token/redeem"
|
|
13
|
+
TOKEN_REFRESH = "/auth/token/refresh"
|
|
14
|
+
SESSIONS = "/auth/sessions"
|
|
15
|
+
SESSIONS_CURRENT = "/auth/sessions/current"
|
|
16
|
+
|
|
17
|
+
# POST /auth/challenge — fetches the challenge and timestamp (ms). Anonymous.
|
|
18
|
+
# @return [Hash] { "challenge", "timestamp", "timestampMs", "clientIp" }
|
|
19
|
+
def challenge
|
|
20
|
+
post(CHALLENGE, bearer: nil, json: {}, returns: %w[challenge timestampMs])
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# POST /auth/xades-signature — submits the signed XAdES AuthTokenRequest. Anonymous.
|
|
24
|
+
# @param signed_xml [String] signed document (application/xml)
|
|
25
|
+
# @param verify_certificate_chain [Boolean] whether to verify the certificate chain
|
|
26
|
+
# @return [Hash] { "referenceNumber", "authenticationToken" => { "token", "validUntil" } }
|
|
27
|
+
def submit_xades(signed_xml, verify_certificate_chain: false)
|
|
28
|
+
post(
|
|
29
|
+
XADES_SIGNATURE,
|
|
30
|
+
bearer: nil,
|
|
31
|
+
body: signed_xml,
|
|
32
|
+
headers: { "Content-Type" => "application/xml" },
|
|
33
|
+
query: { "verifyCertificateChain" => verify_certificate_chain },
|
|
34
|
+
returns: %w[referenceNumber authenticationToken]
|
|
35
|
+
)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# POST /auth/ksef-token — authentication with an encrypted KSeF token. Anonymous.
|
|
39
|
+
# @param challenge [String]
|
|
40
|
+
# @param context_type [String] context type: "Nip", "InternalId", "NipVatUe" or "PeppolId"
|
|
41
|
+
# @param context_value [String]
|
|
42
|
+
# @param encrypted_token [String] Base64 RSA-OAEP("token|timestampMs")
|
|
43
|
+
# @param public_key_id [String, nil]
|
|
44
|
+
# @return [Hash] init response (referenceNumber + authenticationToken)
|
|
45
|
+
def submit_ksef_token(challenge:, context_type:, context_value:, encrypted_token:, public_key_id: nil)
|
|
46
|
+
body = {
|
|
47
|
+
"challenge" => challenge,
|
|
48
|
+
"contextIdentifier" => { "type" => context_type, "value" => context_value },
|
|
49
|
+
"encryptedToken" => encrypted_token
|
|
50
|
+
}
|
|
51
|
+
body["publicKeyId"] = public_key_id if public_key_id
|
|
52
|
+
post(KSEF_TOKEN, bearer: nil, json: body, returns: %w[referenceNumber authenticationToken])
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# GET /auth/{referenceNumber} — status of the authentication operation. Bearer: authenticationToken.
|
|
56
|
+
# @param reference_number [String]
|
|
57
|
+
# @param authentication_token [String]
|
|
58
|
+
# @return [Hash] AuthenticationOperationStatusResponse (including "status" => {code, description, details})
|
|
59
|
+
def status(reference_number, authentication_token:)
|
|
60
|
+
get(path("auth", reference_number), bearer: authentication_token, returns: %w[status])
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# POST /auth/token/redeem — issues the accessToken and refreshToken. Bearer: authenticationToken.
|
|
64
|
+
# @param authentication_token [String]
|
|
65
|
+
# @return [Hash] { "accessToken" => {token, validUntil}, "refreshToken" => {token, validUntil} }
|
|
66
|
+
def redeem(authentication_token:)
|
|
67
|
+
post(TOKEN_REDEEM, bearer: authentication_token, json: {}, returns: %w[accessToken refreshToken])
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# POST /auth/token/refresh — refreshes the accessToken. Bearer: refreshToken.
|
|
71
|
+
# @param refresh_token [String]
|
|
72
|
+
# @return [Hash] { "accessToken" => {token, validUntil} }
|
|
73
|
+
# @raise [Ksef::ReauthenticationRequired] when the refresh token can no longer be used (a 401, or a
|
|
74
|
+
# 400 with 21301/21304)
|
|
75
|
+
def refresh(refresh_token:)
|
|
76
|
+
post(TOKEN_REFRESH, bearer: refresh_token, json: {}, returns: %w[accessToken])
|
|
77
|
+
rescue Unauthorized => e
|
|
78
|
+
raise ReauthenticationRequired.new("the refresh token can no longer be used",
|
|
79
|
+
status: e.status, codes: e.codes, trace_id: e.trace_id,
|
|
80
|
+
details: e.details, body: e.body)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# GET /auth/sessions — list of active authentication sessions (continuation pagination).
|
|
84
|
+
# @param access_token [String, nil] defaults to the client token, read for every page
|
|
85
|
+
# @param page_size [Integer]
|
|
86
|
+
# @return [Enumerator::Lazy<Hash>] session entries
|
|
87
|
+
def sessions(access_token: nil, page_size: 20)
|
|
88
|
+
Http::Pagination.by_continuation(page_size: page_size) do |token, size|
|
|
89
|
+
query = { "pageSize" => size }
|
|
90
|
+
headers = token ? { "x-continuation-token" => token } : {}
|
|
91
|
+
body = get(SESSIONS, bearer: access_token || default_bearer, query: query, headers: headers, returns: [])
|
|
92
|
+
Http::Pagination::ContinuationPage.new(
|
|
93
|
+
items: body["items"] || body["authenticationTokens"] || [],
|
|
94
|
+
continuation_token: body["continuationToken"]
|
|
95
|
+
)
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# DELETE /auth/sessions/current — revokes the current auth session (refresh token).
|
|
100
|
+
# Accepts a refreshToken OR an accessToken; already-issued accessTokens work until expiry.
|
|
101
|
+
# @param token [String]
|
|
102
|
+
# @return [nil]
|
|
103
|
+
def revoke_current_session(token:)
|
|
104
|
+
delete(SESSIONS_CURRENT, bearer: token)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# DELETE /auth/sessions/{referenceNumber} — revokes the given auth session. Bearer: accessToken.
|
|
108
|
+
# @param reference_number [String]
|
|
109
|
+
# @param access_token [String, nil] defaults to the client token
|
|
110
|
+
# @return [nil]
|
|
111
|
+
def revoke_session(reference_number, access_token: nil)
|
|
112
|
+
delete(path("auth", "sessions", reference_number), bearer: access_token || default_bearer)
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ksef
|
|
4
|
+
module Resources
|
|
5
|
+
# Base class for domain resources: wraps one API area and delegates to
|
|
6
|
+
# {Ksef::Http::Connection} with the client's access token, overridable per call. Endpoint
|
|
7
|
+
# paths live as constants in the subclasses, so contract changes are easy to diff.
|
|
8
|
+
class Base
|
|
9
|
+
# @param client [Ksef::Client]
|
|
10
|
+
def initialize(client)
|
|
11
|
+
@client = client
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
private
|
|
15
|
+
|
|
16
|
+
# @return [Ksef::Http::Connection]
|
|
17
|
+
def connection
|
|
18
|
+
@client.connection
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# @return [Ksef::Configuration]
|
|
22
|
+
def config
|
|
23
|
+
@client.config
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# @return [String, nil] the client's default access token
|
|
27
|
+
def access_token
|
|
28
|
+
@client.access_token
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The client's token, read when each request attempt is sent (a callable token can change between
|
|
32
|
+
# a 429 and its retry).
|
|
33
|
+
# @return [Proc]
|
|
34
|
+
def default_bearer
|
|
35
|
+
-> { @client.access_token }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Verb shortcuts: parsed body, access token by default, overridable per call via `bearer:`. With
|
|
39
|
+
# `returns:` (the keys the caller needs, possibly none) the 2xx body must be a JSON object holding them.
|
|
40
|
+
def get(path, bearer: default_bearer, returns: nil, **)
|
|
41
|
+
checked(connection.get(path, bearer: bearer, **).body, "GET", path, returns)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def post(path, bearer: default_bearer, returns: nil, **)
|
|
45
|
+
checked(connection.post(path, bearer: bearer, **).body, "POST", path, returns)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def delete(path, bearer: default_bearer, returns: nil, **)
|
|
49
|
+
checked(connection.delete(path, bearer: bearer, **).body, "DELETE", path, returns)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def put(path, bearer: default_bearer, returns: nil, **)
|
|
53
|
+
checked(connection.put(path, bearer: bearer, **).body, "PUT", path, returns)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def checked(body, verb, path, returns)
|
|
57
|
+
returns.nil? ? body : object!(body, "#{verb} #{path}", required: returns)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# A call whose 2xx response is a JSON object: an empty body, `null` or an array raises instead of
|
|
61
|
+
# reaching the caller as nil, and so does an object without one of the +required+ keys.
|
|
62
|
+
# @param body [Object] the parsed response body
|
|
63
|
+
# @param operation [String] e.g. "POST /tokens", for the error message
|
|
64
|
+
# @param required [Array<String>] keys the caller needs
|
|
65
|
+
# @return [Hash]
|
|
66
|
+
# @raise [Ksef::ApiError]
|
|
67
|
+
def object!(body, operation, required: [])
|
|
68
|
+
processed = operation.start_with?("GET ") ? "" : " — the request may have been processed"
|
|
69
|
+
unless body.is_a?(Hash)
|
|
70
|
+
raise ApiError, "#{operation}: KSeF returned #{body.nil? ? 'an empty body' : "a JSON #{body.class}"} " \
|
|
71
|
+
"instead of an object#{processed}"
|
|
72
|
+
end
|
|
73
|
+
missing = required.reject { |key| body.key?(key) && !body[key].nil? }
|
|
74
|
+
return body if missing.empty?
|
|
75
|
+
|
|
76
|
+
raise ApiError, "#{operation}: KSeF's response lacks #{missing.join(', ')}#{processed}"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# GET returning an XML document (invoice, UPO) unparsed. Faraday hands back BINARY bytes; KSeF
|
|
80
|
+
# serves these documents as UTF-8, so the string is tagged UTF-8 — otherwise combining it with
|
|
81
|
+
# any other text raises Encoding::CompatibilityError on the first Polish character. A 2xx that is
|
|
82
|
+
# no XML document raises, and so do bytes that do not match the `x-ms-meta-hash` KSeF sends.
|
|
83
|
+
def get_raw(path, bearer: default_bearer, **)
|
|
84
|
+
response = connection.get(path, bearer: bearer, raw: :xml, **)
|
|
85
|
+
verify_hash!(response)
|
|
86
|
+
response.raw_body.dup.force_encoding(Encoding::UTF_8)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def verify_hash!(response)
|
|
90
|
+
expected = response.header("x-ms-meta-hash").to_s.strip
|
|
91
|
+
return if expected.empty?
|
|
92
|
+
|
|
93
|
+
require "digest"
|
|
94
|
+
require "base64"
|
|
95
|
+
return if Base64.strict_encode64(Digest::SHA256.digest(response.raw_body)) == expected
|
|
96
|
+
|
|
97
|
+
raise ApiError.new("the downloaded document does not match its x-ms-meta-hash (SHA-256)",
|
|
98
|
+
status: response.status)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Builds a path from segments, escaping the variable values.
|
|
102
|
+
# @return [String]
|
|
103
|
+
# @raise [Ksef::ConfigurationError] for a blank segment, "." or ".." — URI resolution would drop
|
|
104
|
+
# or climb it, and the request would reach another endpoint
|
|
105
|
+
def path(*segments)
|
|
106
|
+
"/#{segments.map { |s| encode_segment(s) }.join('/')}"
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def encode_segment(segment)
|
|
110
|
+
text = segment.to_s
|
|
111
|
+
if text.strip.empty? || text.match?(/\A\.{1,2}\z/)
|
|
112
|
+
raise ConfigurationError, "Invalid path segment: #{segment.inspect}"
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
require "erb"
|
|
116
|
+
ERB::Util.url_encode(text)
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
end
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ksef
|
|
4
|
+
module Resources
|
|
5
|
+
# Batch session resource — POST /sessions/batch*.
|
|
6
|
+
#
|
|
7
|
+
# Low-level 1:1 methods; package building, splitting and uploading live in {Ksef::Batch::Uploader}.
|
|
8
|
+
class BatchSessions < Base
|
|
9
|
+
OPEN = "/sessions/batch"
|
|
10
|
+
|
|
11
|
+
# POST /sessions/batch — declares a batch session (package + parts).
|
|
12
|
+
#
|
|
13
|
+
# @param form_code [Ksef::FormCode, Hash]
|
|
14
|
+
# @param batch_file [Hash] package metadata: { "fileSize", "fileHash", "compressionType"?, "fileParts" => [...] }
|
|
15
|
+
# where fileParts is [{ "ordinalNumber", "fileSize", "fileHash" }] (no fileName) and
|
|
16
|
+
# compressionType is "Zip" (the default) or "TarGz"
|
|
17
|
+
# @param encryption_info [Ksef::Crypto::CryptographyService::EncryptionInfo, Hash]
|
|
18
|
+
# @param offline_mode [Boolean]
|
|
19
|
+
# @return [Hash] { "referenceNumber", "partUploadRequests" => [ {url, method, headers, ...} ] }
|
|
20
|
+
def open(form_code:, batch_file:, encryption_info:, offline_mode: false)
|
|
21
|
+
post(OPEN, json: {
|
|
22
|
+
"formCode" => to_hash(form_code),
|
|
23
|
+
"batchFile" => batch_file,
|
|
24
|
+
"encryption" => to_hash(encryption_info),
|
|
25
|
+
"offlineMode" => offline_mode
|
|
26
|
+
}, returns: %w[referenceNumber partUploadRequests])
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# POST /sessions/batch/{referenceNumber}/close — closes the batch session once parts are uploaded.
|
|
30
|
+
# @param reference_number [String]
|
|
31
|
+
# @return [nil] (204)
|
|
32
|
+
def close(reference_number)
|
|
33
|
+
post(path("sessions", "batch", reference_number, "close"), json: {})
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
def to_hash(value)
|
|
39
|
+
value.respond_to?(:to_h) ? value.to_h : value
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|