rodauth-bankid 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.
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Rodauth
6
+ module BankID
7
+ # Drives one BankID order from start to consumed proof: starts it at
8
+ # BankID, feeds the animated QR code, throttles collect, and runs the
9
+ # claim/assign/consume handshake the features wrap in their
10
+ # transactions. Knows nothing about Rodauth accounts. The features
11
+ # build one per request via +bankid_flow+; hosts rarely touch it
12
+ # directly.
13
+ #
14
+ # flow = Rodauth::BankID::Flow.new(client: client, store: Rodauth::BankID::Store.new(db))
15
+ # token, row = flow.start(end_user_ip: request.ip)
16
+ # flow.qr(token) # => "bankid.<qrStartToken>.<seconds>.<hmac>"
17
+ # flow.collect(token) # => { "status" => "pending", ... }
18
+ #
19
+ # = Options
20
+ #
21
+ # client :: Client, or any object answering +auth+, +sign+, +collect+,
22
+ # and +cancel+ the same way.
23
+ # store :: Store holding the attempt rows.
24
+ # clock :: Callable returning the current Time. Injected by tests.
25
+ # ttl :: Seconds an order may run. Default: 180.
26
+ # completion_ttl :: Seconds between completion and the finishing POST.
27
+ # Default: 60.
28
+ # collect_interval :: Server-enforced seconds between collects.
29
+ # Default: 2.
30
+ class Flow
31
+ PERSONAL_NUMBER_RE = /\A\d{12}\z/
32
+ AUTH_FIELDS = %w[orderRef autoStartToken qrStartToken qrStartSecret].freeze
33
+
34
+ # Order kinds and the Client call each one maps to. +:confirm+ is an
35
+ # identification order for an account that is already logged in.
36
+ KINDS = { auth: :auth, sign: :sign, confirm: :auth }.freeze
37
+
38
+ attr_reader :client, :store
39
+
40
+ def initialize(client:, store:, clock: -> { Time.now },
41
+ ttl: 180, completion_ttl: 60, collect_interval: 2)
42
+ raise ArgumentError, 'ttl must be positive' unless ttl.positive?
43
+
44
+ @client = client
45
+ @store = store
46
+ @clock = clock
47
+ @ttl = ttl
48
+ @completion_ttl = completion_ttl
49
+ @collect_interval = collect_interval
50
+ end
51
+
52
+ # Starts an order of +kind+ (a KINDS key) and returns
53
+ # <tt>[token, row]</tt>. Only the token goes to the browser session.
54
+ # +attributes+ are extra columns for the attempt row (+account_id+,
55
+ # +account_bankid_signature_id+); +order_opts+ go to the Client call.
56
+ # Raises ArgumentError for an unknown kind and ProtocolError when
57
+ # BankID's answer lacks a field.
58
+ def start(end_user_ip:, nonce: SecureRandom.hex(16), kind: :auth, attributes: {}, **order_opts)
59
+ call = KINDS.fetch(kind.to_sym) { raise ArgumentError, "unknown order kind #{kind.inspect}" }
60
+ result = client.public_send(call, end_user_ip:, **order_opts)
61
+
62
+ unless AUTH_FIELDS.all? { |f| result[f].is_a?(String) && !result[f].empty? }
63
+ raise ProtocolError, 'incomplete auth response'
64
+ end
65
+
66
+ now = @clock.call
67
+ token = Store.generate_token
68
+ row = attributes.merge(
69
+ kind: kind.to_s,
70
+ order_ref: result['orderRef'],
71
+ auto_start_token: result['autoStartToken'],
72
+ qr_start_token: result['qrStartToken'],
73
+ qr_start_secret: result['qrStartSecret'],
74
+ nonce:,
75
+ started_at: now,
76
+ expires_at: now + @ttl,
77
+ next_collect_at: now
78
+ )
79
+ store.create(token, row)
80
+ [token, row]
81
+ end
82
+
83
+ # Returns the active attempt row. Raises InvalidAttempt when there
84
+ # is none.
85
+ def read(token)
86
+ store.read(token, now: @clock.call)
87
+ end
88
+
89
+ # Returns the current QR payload (see QR.data), or +nil+ once the
90
+ # order completed.
91
+ def qr(token)
92
+ now = @clock.call
93
+ row = store.read(token, now: now)
94
+ return nil if row[:completed_at]
95
+
96
+ QR.data(row[:qr_start_token], row[:qr_start_secret], row[:started_at], now)
97
+ end
98
+
99
+ # Polls BankID once and returns a Hash whose <tt>"status"</tt> is
100
+ # +pending+, +failed+, or +complete+. On +complete+,
101
+ # <tt>"completionData"</tt> holds BankID's verified payload — or +nil+
102
+ # when the attempt was already claimed, in which case BankID is not
103
+ # called again. Failed and unparseable orders are removed. Raises
104
+ # TooFrequent before the collect interval passed and ProtocolError
105
+ # for answers that fail validation.
106
+ def collect(token)
107
+ row = store.reserve_collect(token, now: @clock.call, interval: @collect_interval)
108
+ return { 'status' => 'complete', 'completionData' => nil } if row[:completed_at]
109
+
110
+ result = client.collect(order_ref: row[:order_ref])
111
+
112
+ unless result['orderRef'] == row[:order_ref]
113
+ store.remove(token)
114
+ raise ProtocolError, 'order reference mismatch'
115
+ end
116
+
117
+ case result['status']
118
+ when 'complete'
119
+ completion = result['completionData']
120
+ number = completion.is_a?(Hash) && completion['user'].is_a?(Hash) && completion['user']['personalNumber']
121
+ unless number.is_a?(String) && number.match?(PERSONAL_NUMBER_RE)
122
+ store.remove(token)
123
+ raise ProtocolError, 'completion without verified identity'
124
+ end
125
+ { 'status' => 'complete', 'completionData' => completion }
126
+ when 'failed'
127
+ store.remove(token)
128
+ { 'status' => 'failed', 'hintCode' => result['hintCode'] }
129
+ when 'pending'
130
+ { 'status' => 'pending', 'hintCode' => result['hintCode'], 'pollAfter' => @collect_interval }
131
+ else
132
+ store.remove(token)
133
+ raise ProtocolError, 'unknown order status'
134
+ end
135
+ end
136
+
137
+ # Claims the attempt (see Store#claim). Returns +false+ if another
138
+ # request got there first. Call inside the transaction that records
139
+ # the completion.
140
+ def claim(token, identity_digest:, completion:)
141
+ store.claim(token, now: @clock.call, ttl: @completion_ttl, identity_digest:, completion:)
142
+ end
143
+
144
+ # Binds the claimed attempt to the resolved account. Raises
145
+ # InvalidAttempt if the attempt was cancelled or expired after the
146
+ # claim.
147
+ def assign_account(token, account_id:)
148
+ store.assign_account(token, account_id:, now: @clock.call)
149
+ end
150
+
151
+ # Returns the completed, account-bound row and deletes it. Raises
152
+ # InvalidAttempt if nobody completed it or it was consumed already.
153
+ def consume(token)
154
+ store.consume(token, now: @clock.call)
155
+ end
156
+
157
+ # Cancels the order locally first, then at BankID (unless it already
158
+ # completed), so a remote failure cannot revive the attempt. Raises
159
+ # InvalidAttempt when there is nothing to cancel.
160
+ def cancel(token)
161
+ row = store.read(token, now: @clock.call)
162
+ store.remove(token)
163
+ client.cancel(order_ref: row[:order_ref]) unless row[:completed_at]
164
+ nil
165
+ end
166
+
167
+ # Deletes the attempt without telling BankID.
168
+ def remove(token)
169
+ store.remove(token)
170
+ end
171
+
172
+ # Deletes expired attempts and returns the count.
173
+ def prune
174
+ store.prune(now: @clock.call)
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+
5
+ module Rodauth
6
+ module BankID
7
+ # Builds the payload of the animated QR code.
8
+ module QR
9
+ # Returns the string the QR code must contain right now:
10
+ # <tt>bankid.<qrStartToken>.<seconds since order start>.<HMAC-SHA256 hex></tt>.
11
+ # Regenerate it every second. +started_at+ and +now+ are Time objects
12
+ # (or anything whose difference is a number of seconds). Keep
13
+ # +start_secret+ on the server.
14
+ def self.data(start_token, start_secret, started_at, now = Time.now)
15
+ seconds = [(now - started_at).floor, 0].max
16
+ code = OpenSSL::HMAC.hexdigest('SHA256', start_secret, seconds.to_s)
17
+ "bankid.#{start_token}.#{seconds}.#{code}"
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'securerandom'
5
+
6
+ module Rodauth
7
+ module BankID
8
+ # Server-side state for one BankID order, keyed by the SHA-256 digest of
9
+ # a random browser token. Created by Flow; hosts only meet it through
10
+ # Flow#prune and the +bankid_attempts_table+ setting. Every +now:+
11
+ # argument is a Time and every timestamp column is +timestamptz+, so
12
+ # deadlines are compared in the database.
13
+ class Store
14
+ TOKEN_RE = /\A[0-9a-f]{64}\z/
15
+
16
+ def initialize(db, table: :account_bankid_attempts)
17
+ @ds = db[table]
18
+ end
19
+
20
+ # Returns a fresh 64-hex-character browser token. Only its digest is
21
+ # ever stored.
22
+ def self.generate_token
23
+ SecureRandom.hex(32)
24
+ end
25
+
26
+ # Inserts the row for +token+. +attributes+ are the columns Flow#start
27
+ # builds; the token digest is added here.
28
+ def create(token, attributes)
29
+ @ds.insert(attributes.merge(token_digest: digest(token)))
30
+ end
31
+
32
+ # Returns the active row for +token+. Raises InvalidAttempt when the
33
+ # token is malformed, unknown, or expired.
34
+ def read(token, now:)
35
+ row = active(token, now).first
36
+ raise InvalidAttempt, 'no active BankID attempt' unless row
37
+
38
+ row
39
+ end
40
+
41
+ # Grants one collect per +interval+ seconds and returns the row. The
42
+ # +UPDATE+ of +next_collect_at+ is the lock: raises TooFrequent when
43
+ # the slot was already taken, InvalidAttempt when the attempt is gone.
44
+ def reserve_collect(token, now:, interval:)
45
+ row = read(token, now: now)
46
+ count = active(token, now).where { next_collect_at <= now }.update(next_collect_at: now + interval)
47
+ raise TooFrequent, 'collect called too early' unless count == 1
48
+
49
+ row
50
+ end
51
+
52
+ # Claims the attempt for exactly one caller. Returns +true+ for the
53
+ # winner, +false+ when someone else already claimed it. Drops the QR
54
+ # secret, records +identity_digest+ and +completion+, and shortens the
55
+ # deadline to +ttl+ seconds. Run inside the transaction that performs
56
+ # the completion side effects, so a rollback releases the claim.
57
+ def claim(token, now:, ttl:, identity_digest:, completion:)
58
+ count = active(token, now).where(completed_at: nil).update(
59
+ completed_at: now,
60
+ expires_at: now + ttl,
61
+ qr_start_secret: '',
62
+ identity_digest: identity_digest,
63
+ completion: completion
64
+ )
65
+ count == 1
66
+ end
67
+
68
+ # Binds the claimed attempt to +account_id+. Raises InvalidAttempt
69
+ # when the attempt was cancelled or expired after the claim.
70
+ def assign_account(token, account_id:, now:)
71
+ count = active(token, now).exclude(completed_at: nil).where(account_id: nil).update(account_id: account_id)
72
+ raise InvalidAttempt, 'attempt cancelled during completion' unless count == 1
73
+ end
74
+
75
+ # Deletes a completed, account-bound attempt and returns its row.
76
+ # Only one caller can win; the others raise InvalidAttempt.
77
+ def consume(token, now:)
78
+ ready = active(token, now).exclude(completed_at: nil).exclude(account_id: nil)
79
+ row = ready.first
80
+ raise InvalidAttempt, 'no completed BankID attempt' unless row
81
+
82
+ count = ready.delete
83
+ raise InvalidAttempt, 'attempt already consumed' unless count == 1
84
+
85
+ row
86
+ end
87
+
88
+ # Deletes the row for +token+ regardless of state and returns the
89
+ # count. A malformed token counts as already gone.
90
+ def remove(token)
91
+ @ds.where(token_digest: digest(token)).delete
92
+ rescue InvalidAttempt
93
+ 0
94
+ end
95
+
96
+ # Deletes every attempt whose deadline passed and returns the count.
97
+ # One indexed +DELETE+; cheap enough to run before each new order.
98
+ def prune(now: Time.now)
99
+ @ds.where { expires_at <= now }.delete
100
+ end
101
+
102
+ private
103
+
104
+ def active(token, now)
105
+ @ds.where(token_digest: digest(token)).where { expires_at > now }
106
+ end
107
+
108
+ def digest(token)
109
+ raise InvalidAttempt, 'no active BankID attempt' unless token.is_a?(String) && token.match?(TOKEN_RE)
110
+
111
+ Digest::SHA256.hexdigest(token)
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rodauth
4
+ module BankID
5
+ # Bumped per release in lockstep with CHANGELOG.md.
6
+ VERSION = '1.0.0'
7
+ end
8
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'rodauth/bankid/version'
5
+ require 'rodauth/bankid/errors'
6
+ require 'rodauth/bankid/client'
7
+ require 'rodauth/bankid/qr'
8
+ require 'rodauth/bankid/store'
9
+ require 'rodauth/bankid/flow'
10
+
11
+ module Rodauth
12
+ # Swedish BankID for Rodauth. Apps enable the +:bankid+ feature (login),
13
+ # +:bankid_sign+ (signing), and +:bankid_confirm+ (re-authentication);
14
+ # Rodauth loads them from +rodauth/features/+ on +enable+. This module
15
+ # holds the plumbing they share — Client, Flow, Store, QR, the errors —
16
+ # and the page script. See README.md for the guide.
17
+ module BankID
18
+ GEM_ROOT = File.expand_path('../..', __dir__).freeze
19
+
20
+ # Path of the page script. The +bankid+ feature serves it at
21
+ # +bankid_script_path+; hosts that bundle assets themselves can read it
22
+ # from here instead.
23
+ SCRIPT_PATH = File.join(GEM_ROOT, 'public/javascripts/rodauth_bankid.js').freeze
24
+
25
+ class << self
26
+ # Returns the page script body, read once and frozen.
27
+ def script
28
+ @script ||= File.read(SCRIPT_PATH).freeze
29
+ end
30
+
31
+ # Returns the strong ETag for #script, quoted as the header expects.
32
+ def script_etag
33
+ @script_etag ||= %("#{Digest::SHA256.hexdigest(script)[0, 32]}").freeze
34
+ end
35
+ end
36
+ end
37
+ end