bdgtr-cli 0.2 → 0.3

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 (87) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/bin/bdgtr +26 -5
  4. data/lib/bdgtr/cli/config.rb +188 -0
  5. data/lib/bdgtr/cli/config.sample.yml +15 -0
  6. data/lib/bdgtr/cli/help.rb +168 -0
  7. data/lib/bdgtr/cli/ledger_sync.rb +102 -0
  8. data/lib/bdgtr/cli/prompt.rb +47 -0
  9. data/lib/bdgtr/cli/psd2.rb +530 -0
  10. data/lib/bdgtr/cli/rows.rb +38 -0
  11. data/lib/bdgtr/cli/runtime.rb +88 -0
  12. data/lib/bdgtr/cli/table.rb +458 -0
  13. data/lib/bdgtr/cli.rb +126 -0
  14. data/lib/bdgtr/core/binder.rb +79 -0
  15. data/lib/bdgtr/core/exchange.rb +66 -0
  16. data/lib/bdgtr/core/models/account.rb +177 -0
  17. data/lib/bdgtr/core/models/account_requisition.rb +12 -0
  18. data/lib/bdgtr/core/models/account_sync.rb +12 -0
  19. data/lib/bdgtr/core/models/import.rb +12 -0
  20. data/lib/bdgtr/core/models/ledger.rb +10 -0
  21. data/lib/bdgtr/core/models/requisition.rb +27 -0
  22. data/lib/bdgtr/core/models/transaction.rb +98 -0
  23. data/lib/bdgtr/core/models/transaction_category.rb +12 -0
  24. data/lib/bdgtr/core/record.rb +11 -0
  25. data/lib/bdgtr/core/schema.rb +290 -0
  26. data/lib/bdgtr/core/session.rb +76 -0
  27. data/lib/bdgtr/core/syncable.rb +272 -0
  28. data/lib/bdgtr/core/transfer.rb +90 -0
  29. data/lib/bdgtr/core.rb +18 -0
  30. data/lib/bdgtr/portfolio/Rakefile +20 -0
  31. data/lib/bdgtr/portfolio/cli/LICENSE +21 -0
  32. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/app.rb +77 -0
  33. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/import.rb +30 -0
  34. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/spreadsheet.rb +25 -0
  35. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli.rb +52 -0
  36. data/lib/bdgtr/portfolio/exe/bdgtr +7 -0
  37. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/accounts_csv.rb +67 -0
  38. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/app.rb +104 -0
  39. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/auth.rb +52 -0
  40. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/balances.rb +157 -0
  41. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/cache.rb +46 -0
  42. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_menu.rb +90 -0
  43. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_selection.rb +68 -0
  44. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/config.rb +138 -0
  45. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/decryptor.rb +70 -0
  46. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/drive_client.rb +182 -0
  47. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/errors.rb +10 -0
  48. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/file_reader.rb +80 -0
  49. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_import.rb +609 -0
  50. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_xls.rb +235 -0
  51. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import/fineco.rb +243 -0
  52. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import.rb +85 -0
  53. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/parser.rb +254 -0
  54. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_source.rb +30 -0
  55. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_store.rb +124 -0
  56. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/preview_window.rb +98 -0
  57. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/proto/client_pb.rb +29 -0
  58. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/row_preview.rb +174 -0
  59. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sheets_client.rb +272 -0
  60. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/snapshot.rb +27 -0
  61. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync.rb +247 -0
  62. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync_preview.rb +63 -0
  63. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_identity.rb +49 -0
  64. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_sync.rb +948 -0
  65. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_types.rb +142 -0
  66. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/version.rb +5 -0
  67. data/lib/bdgtr/portfolio/lib/portfolio_performance_api.rb +42 -0
  68. data/lib/bdgtr/portfolio/proto/client.proto +114 -0
  69. data/lib/bdgtr/psd2/account.rb +24 -0
  70. data/lib/bdgtr/psd2/account_snapshot.rb +96 -0
  71. data/lib/bdgtr/psd2/callback.rb +49 -0
  72. data/lib/bdgtr/psd2/connect.rb +75 -0
  73. data/lib/bdgtr/psd2/enable_banking.rb +250 -0
  74. data/lib/bdgtr/psd2/go_cardless.rb +133 -0
  75. data/lib/bdgtr/psd2/institution.rb +17 -0
  76. data/lib/bdgtr/psd2/platform.rb +37 -0
  77. data/lib/bdgtr/psd2/requisition.rb +21 -0
  78. data/lib/bdgtr/psd2/transaction.rb +29 -0
  79. data/lib/bdgtr/psd2.rb +25 -0
  80. data/lib/bdgtr/sync/importer.rb +125 -0
  81. data/lib/bdgtr/sync/library.rb +18 -0
  82. data/lib/bdgtr/sync/portfolio.rb +14 -0
  83. data/lib/bdgtr/sync/projection.rb +38 -0
  84. data/lib/bdgtr/sync/spreadsheet.rb +23 -0
  85. data/lib/bdgtr/sync.rb +25 -0
  86. data/lib/bdgtr/version.rb +1 -1
  87. metadata +353 -30
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PortfolioPerformanceApi
4
+ class Balances
5
+ # Signs match Account#getCurrentAmount in Portfolio Performance.
6
+ # XML stores TRANSFER_IN on the destination account; protobuf stores a
7
+ # single CASH_TRANSFER on the source (otherAccount = destination).
8
+ CASH_SIGN = {
9
+ "DEPOSIT" => 1,
10
+ "REMOVAL" => -1,
11
+ "DIVIDEND" => 1,
12
+ "INTEREST" => 1,
13
+ "INTEREST_CHARGE" => -1,
14
+ "TAX_REFUND" => 1,
15
+ "TAX" => -1,
16
+ "FEE_REFUND" => 1,
17
+ "FEE" => -1,
18
+ "SALE" => 1,
19
+ "PURCHASE" => -1,
20
+ "TRANSFER_IN" => 1
21
+ }.freeze
22
+
23
+ SHARE_DIVISOR = 100_000_000
24
+ QUOTE_DIVISOR = 100_000_000
25
+
26
+ def self.compute(client, include_retired: true)
27
+ deposits = Array(client.accounts)
28
+ portfolios = Array(client.portfolios)
29
+ unless include_retired
30
+ deposits = deposits.reject(&:retired)
31
+ portfolios = portfolios.reject(&:retired)
32
+ end
33
+
34
+ rows = deposits.map { |account| deposit_row(account, client) } +
35
+ portfolios.map { |account| securities_row(account, client) }
36
+
37
+ totals = rows.group_by { |row| row[:currency] }.map do |currency, group|
38
+ cents = group.sum { |row| row[:balance_cents] }
39
+ { currency: currency, balance: cents / 100.0, balance_cents: cents }
40
+ end
41
+
42
+ {
43
+ base_currency: client.base_currency,
44
+ version: client.version,
45
+ accounts: rows,
46
+ totals: totals
47
+ }
48
+ end
49
+
50
+ def self.deposit_row(account, client)
51
+ cents = cash_balance_cents(account, client.transactions)
52
+ {
53
+ uuid: account.uuid,
54
+ kind: Parser::KIND_DEPOSIT,
55
+ name: account.name,
56
+ currency: account.currency,
57
+ retired: account.retired,
58
+ balance: cents / 100.0,
59
+ balance_cents: cents
60
+ }
61
+ end
62
+
63
+ def self.securities_row(account, client)
64
+ cents = market_value_cents(account, client)
65
+ {
66
+ uuid: account.uuid,
67
+ kind: Parser::KIND_SECURITIES,
68
+ name: account.name,
69
+ currency: account.currency || client.base_currency,
70
+ retired: account.retired,
71
+ balance: cents / 100.0,
72
+ balance_cents: cents,
73
+ reference_account_uuid: account.reference_account_uuid
74
+ }
75
+ end
76
+
77
+ def self.cash_balance_cents(account, transactions)
78
+ transactions.sum { |tx| signed_amount(account, tx) }
79
+ end
80
+
81
+ def self.signed_amount(account, tx)
82
+ type = tx.type
83
+ if type == "CASH_TRANSFER"
84
+ return cash_transfer_amount(account, tx)
85
+ end
86
+
87
+ return 0 unless tx.account_uuid == account.uuid
88
+
89
+ sign = CASH_SIGN[type]
90
+ sign ? sign * tx.amount_cents : 0
91
+ end
92
+
93
+ def self.cash_transfer_amount(account, tx)
94
+ if tx.account_uuid == account.uuid
95
+ -tx.amount_cents
96
+ elsif tx.other_account_uuid == account.uuid
97
+ target_amount(account, tx)
98
+ else
99
+ 0
100
+ end
101
+ end
102
+
103
+ def self.target_amount(account, tx)
104
+ if tx.currency == account.currency
105
+ return tx.amount_cents
106
+ end
107
+
108
+ fx = Array(tx.units).find do |unit|
109
+ unit.type.to_s == "GROSS_VALUE" &&
110
+ unit.fx_currency == account.currency &&
111
+ !unit.fx_amount_cents.nil?
112
+ end
113
+ fx ? fx.fx_amount_cents : tx.amount_cents
114
+ end
115
+
116
+ def self.market_value_cents(portfolio, client)
117
+ securities = Array(client.securities).to_h { |security| [security.uuid, security] }
118
+ shares_by_security = Hash.new(0)
119
+ Array(client.transactions).each do |tx|
120
+ delta = share_delta(portfolio.uuid, tx)
121
+ next if delta.zero? || tx.security_uuid.to_s.empty?
122
+
123
+ shares_by_security[tx.security_uuid] += delta
124
+ end
125
+
126
+ shares_by_security.sum do |security_uuid, shares|
127
+ next 0 if shares.zero?
128
+
129
+ security = securities[security_uuid]
130
+ next 0 if security.nil? || security.quote.to_i.zero?
131
+
132
+ (shares * security.quote) / (SHARE_DIVISOR * QUOTE_DIVISOR / 100)
133
+ end
134
+ end
135
+
136
+ def self.share_delta(portfolio_uuid, tx)
137
+ case tx.type
138
+ when "PURCHASE", "INBOUND_DELIVERY", "TRANSFER_IN"
139
+ tx.portfolio_uuid == portfolio_uuid ? tx.shares.to_i : 0
140
+ when "SALE", "OUTBOUND_DELIVERY"
141
+ tx.portfolio_uuid == portfolio_uuid ? -tx.shares.to_i : 0
142
+ when "SECURITY_TRANSFER"
143
+ if tx.portfolio_uuid == portfolio_uuid
144
+ -tx.shares.to_i
145
+ elsif tx.other_portfolio_uuid == portfolio_uuid
146
+ tx.shares.to_i
147
+ else
148
+ 0
149
+ end
150
+ else
151
+ 0
152
+ end
153
+ end
154
+ private_class_method :deposit_row, :securities_row, :cash_balance_cents, :signed_amount,
155
+ :cash_transfer_amount, :target_amount, :market_value_cents, :share_delta
156
+ end
157
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PortfolioPerformanceApi
4
+ class Cache
5
+ Entry = Struct.new(:payload, :cached_at, :expires_at, keyword_init: true)
6
+
7
+ def initialize(ttl: Config.cache_ttl)
8
+ @ttl = ttl
9
+ @mutex = Mutex.new
10
+ @entry = nil
11
+ end
12
+
13
+ def fetch(force: false)
14
+ unless force
15
+ current = @entry
16
+ return decorate(current, hit: true) if current && Time.now < current.expires_at
17
+ end
18
+
19
+ @mutex.synchronize do
20
+ unless force
21
+ current = @entry
22
+ return decorate(current, hit: true) if current && Time.now < current.expires_at
23
+ end
24
+
25
+ payload = yield
26
+ now = Time.now.utc
27
+ @entry = Entry.new(payload: payload, cached_at: now, expires_at: now + @ttl)
28
+ decorate(@entry, hit: false)
29
+ end
30
+ end
31
+
32
+ def clear
33
+ @mutex.synchronize { @entry = nil }
34
+ end
35
+
36
+ private
37
+
38
+ def decorate(entry, hit:)
39
+ entry.payload.merge(
40
+ cached: hit,
41
+ cached_at: entry.cached_at.iso8601,
42
+ expires_at: entry.expires_at.iso8601
43
+ )
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tty-cursor"
4
+ require "tty-prompt"
5
+ require "tty-reader"
6
+ require "tty-screen"
7
+
8
+ require_relative "checkbox_selection"
9
+
10
+ module PortfolioPerformanceApi
11
+ class CheckboxMenu
12
+ def initialize(labels, help: "↑/↓ navigate space select enter confirm q abort")
13
+ @labels = labels
14
+ @help = help
15
+ @state = CheckboxSelection.new(labels.each_index.to_a)
16
+ @prompt = TTY::Prompt.new
17
+ @reader = TTY::Reader.new(interrupt: :exit)
18
+ @cursor = TTY::Cursor
19
+ @drawn_lines = 0
20
+ end
21
+
22
+ def run
23
+ raise ArgumentError, "needs an interactive terminal" unless $stdin.tty?
24
+
25
+ $stdout.print @cursor.hide
26
+ $stdout.sync = true
27
+ decision = nil
28
+ @reader.on(:keyup) { @state.up }
29
+ @reader.on(:keydown) { @state.down }
30
+ @reader.on(:keyspace) { @state.toggle }
31
+ @reader.on(:keyreturn) { decision = :confirm }
32
+ @reader.on(:keyenter) { decision = :confirm }
33
+ @reader.on(:keypress) do |event|
34
+ decision = :abort if %w[q Q].include?(event.value)
35
+ end
36
+
37
+ begin
38
+ until decision
39
+ draw
40
+ @reader.read_keypress
41
+ end
42
+ ensure
43
+ clear_frame
44
+ $stdout.print @cursor.show
45
+ end
46
+
47
+ decision == :confirm ? @state.selected_items : []
48
+ end
49
+
50
+ private
51
+
52
+ def draw
53
+ lines = render_lines
54
+ clear_frame
55
+ lines.each { |line| $stdout.puts line }
56
+ @drawn_lines = lines.size
57
+ end
58
+
59
+ def clear_frame
60
+ return if @drawn_lines.zero?
61
+
62
+ $stdout.print @cursor.up(@drawn_lines)
63
+ @drawn_lines.times do
64
+ $stdout.print @cursor.clear_line
65
+ $stdout.print @cursor.next_line
66
+ end
67
+ $stdout.print @cursor.up(@drawn_lines)
68
+ @drawn_lines = 0
69
+ end
70
+
71
+ def render_lines
72
+ page_size = [TTY::Screen.height - 4, 3].max
73
+ item_page = [page_size - 1, 1].max
74
+ from, to = @state.visible_window(item_page)
75
+ lines = [@help, format_row(-1, "toggle all", @state.all_selected?, @state.cursor.zero?)]
76
+ (from..to).each do |index|
77
+ next if index.negative?
78
+
79
+ lines << format_row(index, @labels[index], @state.selected?(index), @state.cursor == index + 1)
80
+ end
81
+ lines
82
+ end
83
+
84
+ def format_row(_index, label, selected, current)
85
+ marker = current ? ">" : " "
86
+ box = selected ? "[x]" : "[ ]"
87
+ "#{marker} #{box} #{label}"
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PortfolioPerformanceApi
4
+ class CheckboxSelection
5
+ attr_reader :cursor
6
+
7
+ def initialize(items)
8
+ @items = items
9
+ @selected = Array.new(items.size, false)
10
+ @cursor = 0
11
+ end
12
+
13
+ def size
14
+ @items.size
15
+ end
16
+
17
+ def line_count
18
+ size + 1
19
+ end
20
+
21
+ def up
22
+ @cursor = (@cursor - 1) % line_count
23
+ end
24
+
25
+ def down
26
+ @cursor = (@cursor + 1) % line_count
27
+ end
28
+
29
+ def toggle
30
+ if @cursor.zero?
31
+ toggle_all
32
+ else
33
+ index = @cursor - 1
34
+ @selected[index] = !@selected[index]
35
+ end
36
+ end
37
+
38
+ def toggle_all
39
+ @selected.fill(all_selected? ? false : true)
40
+ end
41
+
42
+ def all_selected?
43
+ !@selected.empty? && @selected.all?
44
+ end
45
+
46
+ def selected?(index)
47
+ @selected.fetch(index)
48
+ end
49
+
50
+ def selected_items
51
+ @items.each_with_index.filter_map { |item, index| item if @selected[index] }
52
+ end
53
+
54
+ def selected_count
55
+ @selected.count(true)
56
+ end
57
+
58
+ def visible_window(page_size)
59
+ return [0, size - 1] if size <= page_size || page_size < 1
60
+
61
+ item_cursor = [@cursor - 1, 0].max
62
+ start = item_cursor - (page_size / 2)
63
+ start = 0 if start.negative?
64
+ start = size - page_size if start + page_size > size
65
+ [start, start + page_size - 1]
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "base64"
5
+
6
+ module PortfolioPerformanceApi
7
+ module Config
8
+ module_function
9
+
10
+ def api_key
11
+ required("API_KEY")
12
+ end
13
+
14
+ def api_key_header
15
+ env("API_KEY_HEADER", "X-Api-Key")
16
+ end
17
+
18
+ def portfolio_password
19
+ env("PORTFOLIO_PASSWORD")
20
+ end
21
+
22
+ def drive_file_id
23
+ raw = env("PORTFOLIO_GOOGLE_DRIVE_FILE_ID")
24
+ return if raw.nil? || raw.empty?
25
+
26
+ extract_drive_id(raw)
27
+ end
28
+
29
+ def sync_drive_file_id
30
+ raw = env("SYNC_GOOGLE_DRIVE_FILE_ID")
31
+ return if raw.nil? || raw.empty?
32
+
33
+ extract_drive_id(raw)
34
+ end
35
+
36
+ def sync_test_drive_file_id
37
+ raw = env("SYNC_GOOGLE_DRIVE_FILE_ID_TEST")
38
+ return if raw.nil? || raw.empty?
39
+
40
+ extract_drive_id(raw)
41
+ end
42
+
43
+ def sync_skip_rows
44
+ Integer(env("SYNC_GOOGLE_DRIVE_FILE_SKIP_ROWS", "0"))
45
+ end
46
+
47
+ def sync_rows_chunk
48
+ Integer(env("SYNC_GOOGLE_DRIVE_ROWS_CHUNK", "100"))
49
+ end
50
+
51
+ def sync_preview_rows
52
+ Integer(env("SYNC_GOOGLE_DRIVE_PREVIEW_ROWS", "20"))
53
+ end
54
+
55
+ def service_account_json
56
+ inline = env("GOOGLE_SERVICE_ACCOUNT_JSON")
57
+ return decode_service_account(inline) unless inline.nil? || inline.empty?
58
+
59
+ path = env("GOOGLE_APPLICATION_CREDENTIALS")
60
+ return File.read(path) if path && !path.empty? && File.file?(path)
61
+
62
+ nil
63
+ end
64
+
65
+ def portfolio_file
66
+ env("PORTFOLIO_FILE")
67
+ end
68
+
69
+ def cache_ttl
70
+ minutes = Integer(env("CACHE_TTL_MINUTES", "15"))
71
+ minutes * 60
72
+ end
73
+
74
+ def include_retired?
75
+ env("INCLUDE_RETIRED", "true") != "false"
76
+ end
77
+
78
+ def port
79
+ Integer(env("PORT", "9292"))
80
+ end
81
+
82
+ def drive_configured?
83
+ !drive_file_id.to_s.empty? && !service_account_json.to_s.empty?
84
+ end
85
+
86
+ def local_file_configured?
87
+ path = portfolio_file
88
+ path && !path.empty? && File.file?(path)
89
+ end
90
+
91
+ def extract_drive_id(value)
92
+ value[/\/d\/([a-zA-Z0-9_-]+)/, 1] ||
93
+ value[/[?&]id=([a-zA-Z0-9_-]+)/, 1] ||
94
+ value
95
+ end
96
+
97
+ def env(name, default = nil)
98
+ value = ENV[name]
99
+ return default if value.nil? || value.empty?
100
+
101
+ value
102
+ end
103
+
104
+ def required(name)
105
+ value = ENV[name]
106
+ raise NotConfigured, "missing env #{name}" if value.nil? || value.empty?
107
+
108
+ value
109
+ end
110
+
111
+ def decode_service_account(raw)
112
+ value = unwrap_quotes(raw)
113
+ return value if json_object?(value)
114
+
115
+ decoded = Base64.decode64(value.delete(" \n"))
116
+ return decoded if json_object?(decoded)
117
+
118
+ value
119
+ end
120
+
121
+ def unwrap_quotes(value)
122
+ text = value.to_s.strip
123
+ return text[1..-2] if text.length >= 2 && (
124
+ (text.start_with?("'") && text.end_with?("'")) ||
125
+ (text.start_with?('"') && text.end_with?('"'))
126
+ )
127
+
128
+ text
129
+ end
130
+
131
+ def json_object?(value)
132
+ parsed = JSON.parse(value)
133
+ parsed.is_a?(Hash)
134
+ rescue JSON::ParserError, TypeError
135
+ false
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module PortfolioPerformanceApi
6
+ # Decrypts Portfolio Performance AES-encrypted .portfolio files.
7
+ #
8
+ # Layout (see ClientFactory.Decryptor in the upstream Java app):
9
+ # signature 9 bytes "PORTFOLIO"
10
+ # method 1 byte (0 = AES-128, 1 = AES-256)
11
+ # iv 16 bytes
12
+ # ciphertext = AES-CBC-PKCS5( contentType:int32be, version:int32be, zip )
13
+ class Decryptor
14
+ SIGNATURE = "PORTFOLIO"
15
+ SALT = [112, 67, 103, 107, -92, -125, -112, -95, -97, -114, 117, -56, -53, -69, -25, -28].pack("c*")
16
+ ITERATIONS = 65_536
17
+ IV_LENGTH = 16
18
+ MAX_VERSION = 200
19
+
20
+ Payload = Struct.new(:content_type, :version, :zip_bytes, keyword_init: true)
21
+
22
+ def self.encrypted?(bytes)
23
+ bytes.start_with?(SIGNATURE)
24
+ end
25
+
26
+ def self.decrypt(bytes, password)
27
+ raise NotAPortfolioFile, "not an encrypted portfolio file" unless encrypted?(bytes)
28
+ raise IncorrectPassword, "portfolio password is required" if password.nil? || password.empty?
29
+
30
+ method = bytes.getbyte(SIGNATURE.bytesize)
31
+ key_len = method == 1 ? 32 : 16
32
+ iv = bytes.byteslice(SIGNATURE.bytesize + 1, IV_LENGTH)
33
+ ciphertext = bytes.byteslice(SIGNATURE.bytesize + 1 + IV_LENGTH..)
34
+ raise NotAPortfolioFile, "truncated encrypted portfolio file" if iv.nil? || iv.bytesize != IV_LENGTH || ciphertext.nil? || ciphertext.empty?
35
+
36
+ key = OpenSSL::KDF.pbkdf2_hmac(password, salt: SALT, iterations: ITERATIONS, length: key_len, hash: "SHA1")
37
+ cipher = OpenSSL::Cipher::AES.new(key_len * 8, :CBC)
38
+ cipher.decrypt
39
+ cipher.key = key
40
+ cipher.iv = iv
41
+
42
+ begin
43
+ plaintext = cipher.update(ciphertext) + cipher.final
44
+ rescue OpenSSL::Cipher::CipherError
45
+ raise IncorrectPassword, "incorrect portfolio password"
46
+ end
47
+
48
+ content_type, version = plaintext.unpack("l>l>")
49
+ if content_type < 1 || content_type > 2 || version < 1 || version > MAX_VERSION
50
+ raise IncorrectPassword, "incorrect portfolio password"
51
+ end
52
+
53
+ Payload.new(content_type: content_type, version: version, zip_bytes: plaintext.byteslice(8..))
54
+ end
55
+
56
+ def self.encrypt(zip_bytes, password, aes256: true, content_type: 2, version: 70)
57
+ key_len = aes256 ? 32 : 16
58
+ key = OpenSSL::KDF.pbkdf2_hmac(password, salt: SALT, iterations: ITERATIONS, length: key_len, hash: "SHA1")
59
+ cipher = OpenSSL::Cipher::AES.new(key_len * 8, :CBC)
60
+ cipher.encrypt
61
+ cipher.key = key
62
+ iv = cipher.random_iv
63
+
64
+ header = [content_type, version].pack("l>l>")
65
+ ciphertext = cipher.update(header + zip_bytes) + cipher.final
66
+
67
+ SIGNATURE.b + [aes256 ? 1 : 0].pack("C") + iv + ciphertext
68
+ end
69
+ end
70
+ end