gamba 2.1.0 → 2.2.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.
@@ -0,0 +1,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Gamba
6
+ # An invoice as data: what its Factur-X XML says and what its pages show, from one source. Amounts are exact
7
+ # Rationals, given as Strings such as "12.50", Integers, Rationals or BigDecimals, never Floats; totals and the
8
+ # VAT breakdown are computed with EN 16931's rounding, each amount to the cent.
9
+ Invoice = Data.define(:number, :type, :issued_on, :currency, :seller, :buyer, :lines, :allowances, :charges, :due_on,
10
+ :delivered_on, :deliver_to, :period, :buyer_reference, :order_reference, :preceding_invoice, :notes, :payment,
11
+ :payment_terms, :exemptions, :paid)
12
+
13
+ class Invoice
14
+ TYPE_CODE_BY_NAME = {invoice: "380", credit_note: "381"}.freeze
15
+ # EN 16931's VAT category codes (UNTDID 5305).
16
+ VAT_CATEGORY_CODE_BY_NAME = {
17
+ standard: "S", zero_rated: "Z", exempt: "E", reverse_charge: "AE", intra_community: "K", export: "G",
18
+ outside_scope: "O", canary_islands: "L", ceuta_melilla: "M"
19
+ }.freeze
20
+ RATED_VAT_CATEGORIES = %i[standard canary_islands ceuta_melilla].freeze
21
+ # UNTDID 4461.
22
+ PAYMENT_MEANS_CODE_BY_NAME = {cash: "10", cheque: "20", credit_transfer: "30", card: "48", sepa_credit_transfer: "58"}.freeze
23
+ DECIMAL = /\A-?\d+(?:\.\d+)?\z/
24
+
25
+ def self.decimal(value, name)
26
+ case value
27
+ when Float then raise ArgumentError, "#{name} is the Float #{value}: give a String such as \"12.50\", an Integer, a Rational or a BigDecimal"
28
+ when String
29
+ raise ArgumentError, "#{name} is #{value.inspect}: give a decimal such as \"12.50\"" unless value.match?(DECIMAL)
30
+
31
+ Rational(value)
32
+ when Integer, Rational then value.to_r
33
+ else
34
+ raise ArgumentError, "#{name} is #{value.inspect}: give a String such as \"12.50\", an Integer, a Rational or a BigDecimal" unless value.respond_to?(:to_r)
35
+
36
+ value.to_r
37
+ end
38
+ end
39
+
40
+ def self.cents(value)
41
+ value.round(2, half: :up)
42
+ end
43
+
44
+ def self.text(value, name, required: false)
45
+ return if value.nil? && !required
46
+ raise ArgumentError, "#{name} is #{value.inspect}: give a non-empty String" unless value.is_a?(String) && !value.strip.empty?
47
+
48
+ value
49
+ end
50
+
51
+ def self.date(value, name, required: false)
52
+ return if value.nil? && !required
53
+ raise ArgumentError, "#{name} is #{value.inspect}: give a Date" unless value.is_a?(Date)
54
+
55
+ value
56
+ end
57
+
58
+ def self.build(type, value, name)
59
+ return value if value.is_a?(type)
60
+ raise ArgumentError, "#{name} is #{value.inspect}: give a Hash" unless value.is_a?(Hash)
61
+
62
+ type.new(**value)
63
+ end
64
+
65
+ def self.list(type, values, name)
66
+ raise ArgumentError, "#{name} is #{values.inspect}: give an Array" unless values.is_a?(Array)
67
+
68
+ values.each_with_index.map { |value, index| build(type, value, "#{name}[#{index}]") }.freeze
69
+ end
70
+
71
+ def self.choice(value, choices, name)
72
+ return value if choices.key?(value)
73
+
74
+ raise ArgumentError, "#{name} is #{value.inspect}: #{choices.keys.map(&:inspect).join(", ")}"
75
+ end
76
+
77
+ # A VAT category and its rate: the rated categories need one, the others have none or 0.
78
+ def self.vat(category, rate, name)
79
+ choice(category, VAT_CATEGORY_CODE_BY_NAME, "#{name} vat_category")
80
+ if RATED_VAT_CATEGORIES.include?(category)
81
+ raise ArgumentError, "#{name} is #{category.inspect}: give its vat_rate" if rate.nil?
82
+
83
+ decimal(rate, "#{name} vat_rate")
84
+ elsif category == :outside_scope
85
+ raise ArgumentError, "#{name} is outside the scope of VAT: it takes no vat_rate" unless rate.nil?
86
+ else
87
+ raise ArgumentError, "#{name} is #{category.inspect}: its vat_rate is 0" unless rate.nil? || decimal(rate, "#{name} vat_rate").zero?
88
+
89
+ 0r
90
+ end
91
+ end
92
+
93
+ Identifier = Data.define(:id, :scheme) do
94
+ def initialize(id:, scheme: nil)
95
+ super(id: Invoice.text(id, "id", required: true), scheme: Invoice.text(scheme, "scheme"))
96
+ end
97
+ end
98
+
99
+ Address = Data.define(:lines, :postcode, :city, :subdivision, :country) do
100
+ def initialize(country:, lines: [], postcode: nil, city: nil, subdivision: nil)
101
+ lines = Array(lines)
102
+ raise ArgumentError, "an address has at most three lines, not #{lines.size}" if lines.size > 3
103
+ raise ArgumentError, "country is #{country.inspect}: give its ISO 3166 code, such as \"FR\"" unless country.is_a?(String) && country.match?(/\A[A-Z]{2}\z/)
104
+
105
+ super(lines: lines.map { Invoice.text(_1, "address line", required: true) }.freeze, postcode: Invoice.text(postcode, "postcode"),
106
+ city: Invoice.text(city, "city"), subdivision: Invoice.text(subdivision, "subdivision"), country:)
107
+ end
108
+ end
109
+
110
+ # vat is the VAT identifier; tax_registration, the local one a seller without it gives (BT-32).
111
+ Party = Data.define(:name, :trading_name, :legal_id, :vat, :tax_registration, :address, :electronic_address) do
112
+ def initialize(name:, address:, trading_name: nil, legal_id: nil, vat: nil, tax_registration: nil, electronic_address: nil)
113
+ legal_id = {id: legal_id} if legal_id.is_a?(String)
114
+ super(name: Invoice.text(name, "name", required: true), trading_name: Invoice.text(trading_name, "trading_name"),
115
+ legal_id: legal_id && Invoice.build(Identifier, legal_id, "legal_id"), vat: Invoice.text(vat, "vat"),
116
+ tax_registration: Invoice.text(tax_registration, "tax_registration"),
117
+ address: Invoice.build(Address, address, "address"),
118
+ electronic_address: electronic_address && Invoice.build(Identifier, electronic_address, "electronic_address"))
119
+ raise ArgumentError, "electronic_address needs its scheme, such as \"0225\" or \"EM\"" if self.electronic_address && !self.electronic_address.scheme
120
+ end
121
+ end
122
+
123
+ # Where the goods go (BG-13), when not to the buyer.
124
+ Delivery = Data.define(:name, :address) do
125
+ def initialize(address:, name: nil)
126
+ super(name: Invoice.text(name, "deliver_to name"), address: Invoice.build(Address, address, "deliver_to address"))
127
+ end
128
+ end
129
+
130
+ # An allowance or a charge: on a line, or on the whole invoice with the VAT category it falls in.
131
+ Adjustment = Data.define(:amount, :reason, :reason_code, :vat_category, :vat_rate) do
132
+ def initialize(amount:, reason: nil, reason_code: nil, vat_category: nil, vat_rate: nil)
133
+ rated = vat_category || vat_rate
134
+ super(amount: Invoice.cents(Invoice.decimal(amount, "amount")), reason: Invoice.text(reason, "reason"),
135
+ reason_code: Invoice.text(reason_code, "reason_code"), vat_category: rated && (vat_category || :standard),
136
+ vat_rate: rated && Invoice.vat(vat_category || :standard, vat_rate, "an allowance or charge"))
137
+ end
138
+ end
139
+
140
+ Line = Data.define(:id, :name, :description, :quantity, :unit, :unit_price, :vat_category, :vat_rate, :allowances, :charges) do
141
+ def initialize(name:, quantity:, unit_price:, id: nil, description: nil, unit: "C62", vat_category: :standard, vat_rate: nil, allowances: [], charges: [])
142
+ super(id: id && Invoice.text(id.to_s, "id"), name: Invoice.text(name, "name", required: true), description: Invoice.text(description, "description"),
143
+ quantity: Invoice.decimal(quantity, "quantity"), unit: Invoice.text(unit, "unit", required: true), unit_price: Invoice.decimal(unit_price, "unit_price"),
144
+ vat_category:, vat_rate: Invoice.vat(vat_category, vat_rate, "line #{name.inspect}"),
145
+ allowances: Invoice.list(Adjustment, allowances, "allowances"), charges: Invoice.list(Adjustment, charges, "charges"))
146
+ end
147
+
148
+ # BT-131: quantity times net price, plus the line's charges, minus its allowances.
149
+ def net_amount
150
+ Invoice.cents(quantity * unit_price) + charges.sum(0r, &:amount) - allowances.sum(0r, &:amount)
151
+ end
152
+ end
153
+
154
+ Note = Data.define(:text, :subject) do
155
+ def initialize(text:, subject: nil)
156
+ super(text: Invoice.text(text, "note", required: true), subject: Invoice.text(subject, "note subject"))
157
+ end
158
+ end
159
+
160
+ Payment = Data.define(:means, :iban, :bic, :account_name, :reference) do
161
+ def initialize(means: :sepa_credit_transfer, iban: nil, bic: nil, account_name: nil, reference: nil)
162
+ super(means: Invoice.choice(means, PAYMENT_MEANS_CODE_BY_NAME, "payment means"), iban: iban && Invoice.text(iban.delete(" "), "iban"),
163
+ bic: Invoice.text(bic, "bic"), account_name: Invoice.text(account_name, "account_name"), reference: Invoice.text(reference, "payment reference"))
164
+ end
165
+ end
166
+
167
+ # The invoice a credit note corrects (BT-25), with its date (BT-26), which French rules ask for.
168
+ Reference = Data.define(:number, :issued_on) do
169
+ def initialize(number:, issued_on: nil)
170
+ super(number: Invoice.text(number, "preceding_invoice number", required: true), issued_on: Invoice.date(issued_on, "preceding_invoice issued_on"))
171
+ end
172
+ end
173
+
174
+ Exemption = Data.define(:reason, :code) do
175
+ def initialize(reason: nil, code: nil)
176
+ raise ArgumentError, "an exemption takes a reason, a code (VATEX), or both" unless reason || code
177
+
178
+ super(reason: Invoice.text(reason, "exemption reason"), code: Invoice.text(code, "exemption code"))
179
+ end
180
+ end
181
+
182
+ # One line of the VAT breakdown (BG-23): a category and rate, the amount taxed and the tax.
183
+ TaxBreakdown = Data.define(:vat_category, :vat_rate, :basis, :amount, :exemption)
184
+
185
+ def initialize(number:, issued_on:, seller:, buyer:, lines:, type: :invoice, currency: "EUR", allowances: [], charges: [], due_on: nil,
186
+ delivered_on: nil, deliver_to: nil, period: nil, buyer_reference: nil, order_reference: nil, preceding_invoice: nil, notes: [], payment: nil,
187
+ payment_terms: nil, exemptions: {}, paid: 0)
188
+ raise ArgumentError, "currency is #{currency.inspect}: give its ISO 4217 code, such as \"EUR\"" unless currency.is_a?(String) && currency.match?(/\A[A-Z]{3}\z/)
189
+ raise ArgumentError, "an invoice has at least one line" if lines.is_a?(Array) && lines.empty?
190
+ raise ArgumentError, "period is #{period.inspect}: give a Range of two Dates" if period && !(period.is_a?(Range) && period.begin.is_a?(Date) && period.end.is_a?(Date))
191
+ raise ArgumentError, "exemptions is #{exemptions.inspect}: give a Hash by VAT category" unless exemptions.is_a?(Hash)
192
+
193
+ super(
194
+ number: Invoice.text(number, "number", required: true), type: Invoice.choice(type, TYPE_CODE_BY_NAME, "type"),
195
+ issued_on: Invoice.date(issued_on, "issued_on", required: true), currency:,
196
+ seller: Invoice.build(Party, seller, "seller"), buyer: Invoice.build(Party, buyer, "buyer"),
197
+ lines: Invoice.list(Line, lines, "lines"), allowances: Invoice.list(Adjustment, allowances, "allowances"), charges: Invoice.list(Adjustment, charges, "charges"),
198
+ due_on: Invoice.date(due_on, "due_on"), delivered_on: Invoice.date(delivered_on, "delivered_on"),
199
+ deliver_to: deliver_to && Invoice.build(Delivery, deliver_to, "deliver_to"), period:,
200
+ buyer_reference: Invoice.text(buyer_reference, "buyer_reference"), order_reference: Invoice.text(order_reference, "order_reference"),
201
+ preceding_invoice: preceding_invoice && Invoice.build(Reference, preceding_invoice.is_a?(String) ? {number: preceding_invoice} : preceding_invoice, "preceding_invoice"),
202
+ notes: Invoice.list(Note, notes.map { _1.is_a?(String) ? {text: _1} : _1 }, "notes"),
203
+ payment: payment && Invoice.build(Payment, payment, "payment"), payment_terms: Invoice.text(payment_terms, "payment_terms"),
204
+ exemptions: exemptions.to_h { |category, exemption| [Invoice.choice(category, VAT_CATEGORY_CODE_BY_NAME, "exemption category"), Invoice.build(Exemption, exemption.is_a?(String) ? {reason: exemption} : exemption, "exemption")] }.freeze,
205
+ paid: Invoice.cents(Invoice.decimal(paid, "paid"))
206
+ )
207
+ document_adjustments = self.allowances + self.charges
208
+ raise ArgumentError, "an invoice's allowances and charges each take a vat_category or a vat_rate" unless document_adjustments.all?(&:vat_category)
209
+ raise ArgumentError, "an allowance or charge takes a reason, a reason_code, or both" unless (document_adjustments + self.lines.flat_map { _1.allowances + _1.charges }).all? { _1.reason || _1.reason_code }
210
+ end
211
+
212
+ # BT-106
213
+ def line_total
214
+ lines.sum(0r, &:net_amount)
215
+ end
216
+
217
+ # BT-107
218
+ def allowance_total
219
+ allowances.sum(0r, &:amount)
220
+ end
221
+
222
+ # BT-108
223
+ def charge_total
224
+ charges.sum(0r, &:amount)
225
+ end
226
+
227
+ # BT-109
228
+ def tax_basis_total
229
+ line_total - allowance_total + charge_total
230
+ end
231
+
232
+ # BG-23, one entry for each VAT category and rate, in the order they first appear.
233
+ def tax_breakdown
234
+ basis_by_vat = Hash.new(0r)
235
+ lines.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] += _1.net_amount }
236
+ charges.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] += _1.amount }
237
+ allowances.each { basis_by_vat[[_1.vat_category, _1.vat_rate]] -= _1.amount }
238
+ basis_by_vat.map do |(category, rate), basis|
239
+ TaxBreakdown.new(vat_category: category, vat_rate: rate, basis:, amount: Invoice.cents(basis * (rate || 0) / 100), exemption: exemptions[category])
240
+ end
241
+ end
242
+
243
+ # BT-110
244
+ def tax_total
245
+ tax_breakdown.sum(0r, &:amount)
246
+ end
247
+
248
+ # BT-112
249
+ def grand_total
250
+ tax_basis_total + tax_total
251
+ end
252
+
253
+ # BT-115
254
+ def due
255
+ grand_total - paid
256
+ end
257
+
258
+ # The business rules the invoice breaks: EN 16931's, and with rules: :fr those France adds.
259
+ def violations(rules: :en16931)
260
+ Rules.check(self, rules)
261
+ end
262
+
263
+ # The Cross Industry Invoice XML of the profile, as Factur-X and ZUGFeRD embed it, once the invoice passes the
264
+ # rules: RuleViolation lists those it breaks. rules: nil writes it unchecked.
265
+ def to_xml(profile: :en16931, rules: :en16931)
266
+ found = violations(rules:)
267
+ raise RuleViolation, found unless found.empty?
268
+
269
+ CrossIndustryInvoice.new(self, profile).to_s
270
+ end
271
+ end
272
+ end
@@ -12,7 +12,7 @@ module Gamba
12
12
 
13
13
  OPTIONS = %i[
14
14
  page_size page_layout margin left_margin right_margin top_margin bottom_margin background info print_scaling
15
- pdf_a pdf lang background_pdf background_pdf_page
15
+ pdf_a pdf lang background_pdf background_pdf_page watermark
16
16
  ].freeze
17
17
  TEXT_ATTRIBUTES = Layout::Styles::TEXT_ATTRIBUTES
18
18
  # No Prawn page to match here, so fonts that have ligatures and GPOS kerning use them.
@@ -67,6 +67,12 @@ module Gamba
67
67
  declare_band(:footer, gap, block)
68
68
  end
69
69
 
70
+ # Embeds the invoice's Factur-X XML: a Gamba::Invoice, or the XML as a String. The document is a PDF/A one.
71
+ def factur_x(invoice, profile: :en16931, rules: :en16931, filename: PdfA::FACTUR_X_FILENAME, description: "Factur-X invoice")
72
+ @prawn.factur_x(invoice, profile:, rules:, filename:, description:)
73
+ self
74
+ end
75
+
70
76
  def to_s
71
77
  prawn.render
72
78
  end
@@ -139,26 +139,7 @@ module PDF
139
139
  end
140
140
 
141
141
  def hash_2b(salt)
142
- digest = Digest::SHA256.digest(salt)
143
- return digest if @revision == 5
144
-
145
- round = 0
146
- loop do
147
- block = digest * 64
148
- cipher = OpenSSL::Cipher.new("aes-128-cbc").encrypt
149
- cipher.key = digest.byteslice(0, 16)
150
- cipher.iv = digest.byteslice(16, 16)
151
- cipher.padding = 0
152
- encrypted = cipher.update(block) + cipher.final
153
- digest = case encrypted.byteslice(0, 16).bytes.sum % 3
154
- when 0 then Digest::SHA256.digest(encrypted)
155
- when 1 then Digest::SHA384.digest(encrypted)
156
- else Digest::SHA512.digest(encrypted)
157
- end
158
- round += 1
159
- break if round >= 64 && encrypted.getbyte(-1) <= round - 32
160
- end
161
- digest.byteslice(0, 32)
142
+ (@revision == 5) ? Digest::SHA256.digest(salt) : Prawn::Document::Security.hash_2b("".b, salt)
162
143
  end
163
144
  end
164
145
  end
@@ -5,8 +5,9 @@ require "zlib"
5
5
 
6
6
  module PDF
7
7
  module Core
8
- # Writes a PDF 1.5 file: streams compressed, every other object packed into one compressed object stream, and
9
- # a compressed cross-reference stream instead of the xref table (ISO 32000-1 §7.5.7, §7.5.8).
8
+ # Writes a PDF 1.5 file: streams compressed, every other object but an encrypted document's catalog packed into
9
+ # one compressed object stream, and a compressed cross-reference stream instead of the xref table (ISO 32000-1
10
+ # §7.5.7, §7.5.8).
10
11
  class Writer
11
12
  MINIMUM_VERSION = 1.5
12
13
  BINARY_MARKER = "%\xE2\xE3\xCF\xD3\n".b
@@ -27,6 +28,7 @@ module PDF
27
28
  @trailer = trailer.merge(ID: [file_identifier, file_identifier])
28
29
  return unless encryption
29
30
 
31
+ @encryption = encryption
30
32
  @encryption_key = encryption.key(file_identifier)
31
33
  @trailer[:Encrypt] = encryption.dictionary(file_identifier)
32
34
  end
@@ -41,6 +43,14 @@ module PDF
41
43
  output << indirect_stream(reference.identifier, reference.data, reference.stream, compressed: !reference.uncompressed)
42
44
  end
43
45
 
46
+ # 2026-11, macOS 27.2: Apple's PDFKit and Core Graphics (Preview, Safari, Quick Look) open no encrypted file
47
+ # whose catalog is in an object stream.
48
+ if @encryption_key
49
+ packed_objects.delete(root)
50
+ location_by_identifier[root.identifier] = [1, output.bytesize]
51
+ output << "#{root.identifier} 0 obj\n#{PDF::Core.serialize(encrypted_strings(root.data, root.identifier))}\nendobj\n"
52
+ end
53
+
44
54
  object_stream_identifier = objects.size + 1
45
55
  unless packed_objects.empty?
46
56
  location_by_identifier[object_stream_identifier] = [1, output.bytesize]
@@ -57,7 +67,7 @@ module PDF
57
67
  attr_reader :objects, :root, :info, :version, :trailer
58
68
 
59
69
  # A file identifier derived from the document's content, so the same document always gets the same one; an
60
- # encrypted document's mixes in its passwords.
70
+ # encrypted document's mixes in a secret: its passwords under RC4, a random one under AES-256.
61
71
  def document_digest(secret)
62
72
  digest = Digest::MD5.new
63
73
  digest << secret if secret
@@ -68,11 +78,30 @@ module PDF
68
78
  digest.digest
69
79
  end
70
80
 
71
- # Streams are encrypted once compressed; the cross-reference stream never is (ISO 32000-1 §7.5.8.4).
81
+ # Outside an object stream, each string is encrypted on its own (ISO 32000-1 §7.6.2).
82
+ def encrypted_strings(value, identifier)
83
+ case value
84
+ when Hash then value.transform_values { encrypted_strings(_1, identifier) }
85
+ when Array then value.map { encrypted_strings(_1, identifier) }
86
+ when PDF::Core::Serializable then encrypted_strings(value.to_hash, identifier)
87
+ when Time, String then PDF::Core::ByteString.new(encrypt(PDF::Core.string_bytes(value), identifier))
88
+ else value
89
+ end
90
+ end
91
+
92
+ def encrypt(bytes, identifier)
93
+ @encryption.encrypt(bytes, @encryption_key, identifier)
94
+ end
95
+
96
+ # Streams and the strings of their dictionary are encrypted, the stream once compressed; the cross-reference
97
+ # stream never is (ISO 32000-1 §7.5.8.4).
72
98
  def indirect_stream(identifier, dictionary, bytes, encrypted: true, compressed: true)
73
99
  compressed &&= dictionary[:Filter].nil?
74
100
  bytes = Zlib::Deflate.deflate(bytes) if compressed
75
- bytes = Prawn::Document::Arcfour.new(Prawn::Document::Security.object_key(@encryption_key, identifier, 0)).encrypt(bytes) if @encryption_key && encrypted
101
+ if @encryption_key && encrypted
102
+ bytes = encrypt(bytes, identifier)
103
+ dictionary = encrypted_strings(dictionary, identifier)
104
+ end
76
105
  dictionary = dictionary.merge(Length: bytes.bytesize)
77
106
  dictionary[:Filter] = :FlateDecode if compressed
78
107
  "#{identifier} 0 obj\n#{PDF::Core.serialize(dictionary)}\nstream\n".b << bytes.b << "\nendstream\nendobj\n"
data/lib/gamba/pdf.rb CHANGED
@@ -65,7 +65,7 @@ module PDF
65
65
  when Real then value.source
66
66
  when LiteralString then "(#{value.gsub(/[\\\r()]/, LITERAL_STRING_ESCAPES)})"
67
67
  when ByteString then "<#{value.unpack1("H*")}>"
68
- when Time then "(#{value.strftime("D:%Y%m%d%H%M%S%z").chop.chop}'00')"
68
+ when Time then "(#{date(value)})"
69
69
  when String then "<#{(in_content_stream ? value : utf16be(value)).unpack1("H*")}>"
70
70
  when Array then "[#{value.map { serialize(_1, in_content_stream) }.join(" ")}]"
71
71
  when Hash then "<<#{value.map { |key, entry| "#{serialize(key.to_sym)} #{serialize(entry, in_content_stream)}" }.join("\n")}>>"
@@ -80,6 +80,20 @@ module PDF
80
80
  serialize(object, in_content_stream)
81
81
  end
82
82
 
83
+ def date(time)
84
+ offset = time.strftime("%z")
85
+ "#{time.strftime("D:%Y%m%d%H%M%S")}#{offset[0, 3]}'#{offset[3, 2]}'"
86
+ end
87
+
88
+ # What serialize writes between a string's delimiters.
89
+ def string_bytes(value)
90
+ case value
91
+ when Time then date(value)
92
+ when LiteralString, ByteString then value.b
93
+ else utf16be(value)
94
+ end
95
+ end
96
+
83
97
  def utf16be(string)
84
98
  "\xFE\xFF".b + string.encode(::Encoding::UTF_16BE).b
85
99
  end
data/lib/gamba/pdf_a.rb CHANGED
@@ -45,10 +45,13 @@ module Gamba
45
45
  !@pdf_a_conformance.nil?
46
46
  end
47
47
 
48
- def factur_x(xml, profile: :en16931, filename: FACTUR_X_FILENAME, description: "Factur-X invoice")
48
+ # The invoice is a Gamba::Invoice, whose XML Gamba writes once it passes the rules (Gamba::Invoice#to_xml), or
49
+ # the XML itself as a String.
50
+ def factur_x(invoice, profile: :en16931, rules: :en16931, filename: FACTUR_X_FILENAME, description: "Factur-X invoice")
49
51
  raise Prawn::Errors::PdfAViolation, "Factur-X invoices are PDF/A-3 documents: create this one with pdf_a: true" unless pdf_a?
50
52
 
51
53
  level = FACTUR_X_LEVEL_BY_PROFILE.fetch(profile) { raise ArgumentError, "Unknown Factur-X profile #{profile.inspect}: #{FACTUR_X_LEVEL_BY_PROFILE.keys.join(", ")}" }
54
+ xml = invoice.is_a?(Gamba::Invoice) ? invoice.to_xml(profile:, rules:) : invoice
52
55
  @factur_x = {xml: xml.b, level:, relationship: RELATIONSHIP_BY_PROFILE.fetch(profile), filename:, description:}
53
56
  end
54
57
 
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest/md5"
4
+ require "openssl"
4
5
  require "securerandom"
5
6
 
6
7
  module Prawn
7
8
  class Document
8
- # The standard security handler, revision 2: 40-bit RC4 (ISO 32000-1 §7.6.3).
9
+ # The standard security handler: 40-bit RC4 by default (revision 2, ISO 32000-1 §7.6.3), or AES-256
10
+ # (revision 6, ISO 32000-2 §7.6.4) with algorithm: :aes_256.
9
11
  module Security
10
12
  PERMISSIONS_BITS = {print_document: 3, modify_contents: 4, copy_contents: 5, modify_annotations: 6}.freeze
11
13
  FULL_PERMISSIONS = 0xFFFFFFFF
@@ -16,18 +18,48 @@ module Prawn
16
18
  def encrypt_document(options = {})
17
19
  raise Errors::PdfAViolation, "PDF/A forbids encryption" if pdf_a?
18
20
 
19
- Prawn.verify_options(%i[user_password owner_password permissions], options)
21
+ Prawn.verify_options(%i[user_password owner_password permissions algorithm], options)
22
+ options = options.dup
23
+ algorithm = options.delete(:algorithm) || :rc4_40
24
+ encryption_class = case algorithm
25
+ when :rc4_40 then Rc4Encryption
26
+ when :aes_256 then Aes256Encryption
27
+ else raise ArgumentError, "algorithm is #{algorithm.inspect}: encrypt_document takes :rc4_40 or :aes_256"
28
+ end
20
29
  @user_password = options.delete(:user_password) || ""
21
30
  @owner_password = options.delete(:owner_password) || @user_password
22
31
  @owner_password = SecureRandom.bytes(32) if @owner_password == :random
23
32
  self.permissions = options.delete(:permissions) || {}
24
- @encryption = Encryption.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
33
+ @encryption = encryption_class.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
34
+ declare_extension_level_8 if algorithm == :aes_256
25
35
  end
26
36
 
27
37
  def self.encrypt_string(string, key, identifier, generation)
28
38
  Arcfour.new(object_key(key, identifier, generation)).encrypt(string)
29
39
  end
30
40
 
41
+ # Algorithm 2.B (ISO 32000-2 §7.6.4.3.4): the hash of a password for revision 6, salted, and for the owner
42
+ # password also keyed by the user entry.
43
+ def self.hash_2b(password, salt, user_entry = "".b)
44
+ digest = Digest::SHA256.digest(password + salt + user_entry)
45
+ round = 0
46
+ loop do
47
+ cipher = OpenSSL::Cipher.new("aes-128-cbc").encrypt
48
+ cipher.key = digest.byteslice(0, 16)
49
+ cipher.iv = digest.byteslice(16, 16)
50
+ cipher.padding = 0
51
+ encrypted = cipher.update((password + digest + user_entry) * 64) + cipher.final
52
+ digest = case encrypted.byteslice(0, 16).bytes.sum % 3
53
+ when 0 then Digest::SHA256.digest(encrypted)
54
+ when 1 then Digest::SHA384.digest(encrypted)
55
+ else Digest::SHA512.digest(encrypted)
56
+ end
57
+ round += 1
58
+ break if round >= 64 && encrypted.getbyte(-1) <= round - 32
59
+ end
60
+ digest.byteslice(0, 32)
61
+ end
62
+
31
63
  # The key of one object: the document key extended with its number and generation (algorithm 1), and with
32
64
  # "sAlT" for AES-128, which only PDF::Core::Decryption reads.
33
65
  def self.object_key(key, identifier, generation, salt = nil)
@@ -43,6 +75,12 @@ module Prawn
43
75
 
44
76
  private
45
77
 
78
+ # Revision 6 came as Adobe's extension level 8 to PDF 1.7, before ISO 32000-2 made it part of PDF 2.0.
79
+ def declare_extension_level_8
80
+ min_version(1.7)
81
+ (@root.data[:Extensions] ||= {})[:ADBE] = {BaseVersion: :"1.7", ExtensionLevel: 8}
82
+ end
83
+
46
84
  def permissions=(permissions = {})
47
85
  @permissions ||= FULL_PERMISSIONS
48
86
  permissions.each do |key, value|
@@ -58,8 +96,8 @@ module Prawn
58
96
  end
59
97
  end
60
98
 
61
- # The keys and dictionary of an encrypted document, which depend on its file identifier.
62
- class Encryption
99
+ # Revision 2, 40-bit RC4: the keys and dictionary of an encrypted document, which depend on its file identifier.
100
+ class Rc4Encryption
63
101
  def initialize(user_password:, owner_password:, permissions:)
64
102
  @user_password = user_password
65
103
  @owner_password = owner_password
@@ -89,6 +127,96 @@ module Prawn
89
127
  {Filter: :Standard, V: 1, R: 2, O: PDF::Core::ByteString.new(owner_password_hash), U: PDF::Core::ByteString.new(user_password_hash),
90
128
  P: [@permissions].pack("L").unpack1("l")}
91
129
  end
130
+
131
+ def encrypt(bytes, key, identifier)
132
+ Security.encrypt_string(bytes, key, identifier, 0)
133
+ end
134
+ end
135
+
136
+ # Revision 6 of the standard security handler: AES-256 with the file key itself (ISO 32000-2 §7.6.4). The key,
137
+ # salts and initialization vectors are random, as the standard asks: derived from the passwords, the public salts
138
+ # would let anyone test a guess far faster than algorithm 2.B allows. Two renders give different bytes.
139
+ class Aes256Encryption
140
+ # Bits 1 and 2 are reserved and must be 0 (ISO 32000-2 table 22).
141
+ RESERVED_PERMISSIONS = 0b11
142
+ # Revision 3 on, bit 11 (assemble) and bit 9 (fill forms) grant on their own what bit 4 (modify) and bit 6
143
+ # (annotate) cover in revision 2: refused with them, as Prawn's permissions mean.
144
+ IMPLIED_PERMISSION_BY_BIT = {1 << 3 => 1 << 10, 1 << 5 => 1 << 8}.freeze
145
+ ZERO_IV = ("\x00" * 16).b.freeze
146
+
147
+ attr_reader :identifier_secret
148
+
149
+ def initialize(user_password:, owner_password:, permissions:)
150
+ @user_password = password_bytes(user_password)
151
+ @owner_password = password_bytes(owner_password)
152
+ @permissions = IMPLIED_PERMISSION_BY_BIT.reduce(permissions & ~RESERVED_PERMISSIONS) do |value, (bit, implied)|
153
+ value.anybits?(bit) ? value : value & ~implied
154
+ end
155
+ @file_key = SecureRandom.bytes(32)
156
+ @identifier_secret = SecureRandom.bytes(32)
157
+ end
158
+
159
+ def key(_file_identifier)
160
+ @file_key
161
+ end
162
+
163
+ def dictionary(_file_identifier)
164
+ user_entry = password_entry(@user_password)
165
+ owner_entry = password_entry(@owner_password, user_entry)
166
+ {Filter: :Standard, V: 5, R: 6, Length: 256, CF: {StdCF: {AuthEvent: :DocOpen, CFM: :AESV3, Length: 32}}, StmF: :StdCF, StrF: :StdCF,
167
+ U: byte_string(user_entry), UE: byte_string(wrapped_key(@user_password, user_entry)),
168
+ O: byte_string(owner_entry), OE: byte_string(wrapped_key(@owner_password, owner_entry, user_entry)),
169
+ P: [@permissions].pack("L").unpack1("l"), Perms: byte_string(permissions_entry), EncryptMetadata: true}
170
+ end
171
+
172
+ # Each string and stream: its initialization vector, then its bytes in AES-256-CBC with PKCS#7 padding.
173
+ def encrypt(bytes, key, _identifier)
174
+ iv = SecureRandom.bytes(16)
175
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
176
+ cipher.key = key
177
+ cipher.iv = iv
178
+ iv << cipher.update(bytes) << cipher.final
179
+ end
180
+
181
+ private
182
+
183
+ # Without SASLprep, as qpdf, Poppler and MuPDF take a typed password: normalized, "fi" would no longer open in
184
+ # them. 127 bytes is the limit revision 6 hashes.
185
+ def password_bytes(password)
186
+ password.to_s.encode(::Encoding::UTF_8).b.byteslice(0, 127)
187
+ rescue ::EncodingError # bytes that are no text, owner_password: :random's among them
188
+ password.to_s.b.byteslice(0, 127)
189
+ end
190
+
191
+ # Algorithm 8 (user) or 9 (owner): the password's hash, its validation salt and its key salt.
192
+ def password_entry(password, user_entry = "".b)
193
+ validation_salt = SecureRandom.bytes(8)
194
+ Security.hash_2b(password, validation_salt, user_entry) + validation_salt + SecureRandom.bytes(8)
195
+ end
196
+
197
+ # The file key encrypted with the hash of the password and its key salt, /UE or /OE.
198
+ def wrapped_key(password, entry, user_entry = "".b)
199
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
200
+ cipher.key = Security.hash_2b(password, entry.byteslice(40, 8), user_entry)
201
+ cipher.iv = ZERO_IV
202
+ cipher.padding = 0
203
+ cipher.update(@file_key) + cipher.final
204
+ end
205
+
206
+ # Algorithm 10: the permissions, encrypted so that a reader can check nobody changed /P. It asks for ECB on one
207
+ # block, which CBC with a zero IV gives byte for byte.
208
+ def permissions_entry
209
+ block = [@permissions].pack("l<") + "\xFF\xFF\xFF\xFFTadb".b + SecureRandom.bytes(4)
210
+ cipher = OpenSSL::Cipher.new("aes-256-cbc").encrypt
211
+ cipher.key = @file_key
212
+ cipher.iv = ZERO_IV
213
+ cipher.padding = 0
214
+ cipher.update(block) + cipher.final
215
+ end
216
+
217
+ def byte_string(bytes)
218
+ PDF::Core::ByteString.new(bytes)
219
+ end
92
220
  end
93
221
 
94
222
  # RC4, the stream cipher of the standard security handler's first revisions.
data/lib/gamba/version.rb CHANGED
@@ -6,5 +6,5 @@ module Prawn
6
6
  end
7
7
 
8
8
  module Gamba
9
- VERSION = "2.1.0"
9
+ VERSION = "2.2.0"
10
10
  end