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,915 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cgi'
4
+ require 'date'
5
+ require 'json'
6
+ require 'openssl'
7
+ require 'rqrcode'
8
+ require 'rodauth'
9
+ require 'rodauth/bankid'
10
+
11
+ module Rodauth
12
+ # The +bankid+ feature logs an account in with Swedish BankID. It adds
13
+ # five routes under the Rodauth prefix and serves the page script:
14
+ #
15
+ # /bankid-login :: GET renders the page; POST finishes the login.
16
+ # /bankid-auth :: POST starts an order (JSON for XHR, redirect for forms).
17
+ # /bankid-qr :: POST returns the animated QR code as SVG. Call every second.
18
+ # /bankid-collect :: POST polls BankID. Call every +pollAfter+ seconds.
19
+ # /bankid-cancel :: POST cancels the current attempt.
20
+ # /bankid.js :: GET serves the page script with cache headers.
21
+ #
22
+ # A completed order is claimed in one transaction: the attempt row is
23
+ # bound to the account whose linked identity matches the personnummer's
24
+ # digest, the identity row is refreshed, and +after_bankid_collect+ runs.
25
+ # The finishing POST then calls Rodauth's +login('bankid')+, consumes the
26
+ # attempt inside the login transaction, and writes the login log row.
27
+ #
28
+ # = Usage
29
+ #
30
+ # plugin :rodauth do
31
+ # enable :login, :logout, :bankid
32
+ # bankid_environment :test
33
+ # bankid_p12_path 'config/bankid/rp.p12'
34
+ # bankid_p12_password ENV.fetch('BANKID_P12_PASSWORD')
35
+ # bankid_ca_file 'config/bankid/bankid-ca.pem'
36
+ # bankid_identity_secret ENV.fetch('BANKID_IDENTITY_SECRET')
37
+ # bankid_return_url 'https://members.example.se/bankid-login'
38
+ # end
39
+ #
40
+ # = Configuration
41
+ #
42
+ # bankid_client :: A Client to use instead of building one. Default: built
43
+ # from the settings below on first use.
44
+ # bankid_environment :: +:production+ or +:test+. Default: +:production+.
45
+ # bankid_p12_path, bankid_p12_password :: The RP certificate bundle.
46
+ # bankid_cert_pem, bankid_key_pem :: Alternative to the +.p12+: PEM strings.
47
+ # bankid_ca_file :: BankID's server CA bundle. Required for a built client.
48
+ # bankid_open_timeout, bankid_read_timeout, bankid_write_timeout :: Seconds.
49
+ # bankid_identity_secret :: HMAC key (32+ bytes) that replaces the
50
+ # personnummer in the identities table. Never
51
+ # rotate it — the plain number is not stored, so a
52
+ # new key orphans every linked identity.
53
+ # bankid_return_url :: Absolute https URL of the login page. Enables the
54
+ # mobile return flow. Default: +nil+.
55
+ # bankid_return_risk? :: Ask BankID for a risk indication. Default: +false+.
56
+ # bankid_attempt_ttl :: Seconds an order may run. Default: 180.
57
+ # bankid_completion_ttl :: Seconds between completion and the login POST.
58
+ # Default: 60.
59
+ # bankid_collect_interval :: Server-enforced polling interval. Default: 2.
60
+ # bankid_qr_module_size :: SVG pixels per QR module. Default: 4.
61
+ # bankid_create_account? :: Create accounts on first login via
62
+ # +bankid_new_account+. Default: +false+.
63
+ # bankid_log_signature? :: Also store BankID's signature XML and OCSP
64
+ # response in the login log. Default: +false+ —
65
+ # the XML contains the personnummer in clear.
66
+ # bankid_script_cache_control :: +Cache-Control+ for the page script.
67
+ # Default: <tt>'public, max-age=86400'</tt>.
68
+ # bankid_*_table, bankid_*_column :: Table and column names. Set a column
69
+ # to +nil+ to stop storing that value.
70
+ #
71
+ # = Hooks
72
+ #
73
+ # after_bankid_collect :: Identity verified, inside the claim transaction.
74
+ # +account+ and +bankid_completion+ (the full
75
+ # payload) are set. Use +db.after_commit+ for
76
+ # effects outside the database.
77
+ # before_bankid_login :: Before Rodauth's +login+, outside its transaction.
78
+ # after_bankid_login :: Inside the login transaction, after the login was
79
+ # recorded. +bankid_completion+ holds the stored
80
+ # subset.
81
+ # before_bankid_*_route :: One per route, as usual in Rodauth.
82
+ #
83
+ # = Methods
84
+ #
85
+ # bankid_account_from_completion(completion) :: Resolves the account for
86
+ # BankID's +completionData+.
87
+ # Default: digest lookup.
88
+ # bankid_new_account(completion) :: Creates and returns the account when
89
+ # +bankid_create_account?+ is on.
90
+ # bankid_link_identity(account_id, personal_number) :: Links a BankID to an
91
+ # account.
92
+ # bankid_end_user_ip :: The client IP sent to BankID. Default: +request.ip+.
93
+ # bankid_auth_requirement :: BankID +requirement+ object. Default: +nil+.
94
+ # bankid_web_parameters :: BankID v6.1 +web+ object. Default: +nil+.
95
+ # bankid_hint_message(code) :: Text for a BankID hint code.
96
+ Feature.define(:bankid, :Bankid) do
97
+ depends :login
98
+
99
+ loaded_templates %w[bankid-login bankid-script]
100
+ view 'bankid-login', 'Login with BankID', 'bankid_login'
101
+
102
+ before 'bankid_login'
103
+ after 'bankid_login'
104
+ after 'bankid_collect'
105
+
106
+ error_flash 'BankID login failed', 'bankid_failed'
107
+ error_flash 'Your BankID session has expired. Start again', 'bankid_expired'
108
+ error_flash 'BankID is not responding. Try again in a moment', 'bankid_unavailable'
109
+ error_flash 'No account is linked to this BankID', 'bankid_no_account'
110
+ error_flash 'BankID login was cancelled', 'bankid_cancelled'
111
+
112
+ redirect(:bankid_failed) { bankid_login_path }
113
+ redirect(:bankid_cancelled) { login_path }
114
+
115
+ session_key :bankid_attempt_session_key, :bankid_attempt
116
+ session_key :bankid_authenticated_at_session_key, :bankid_authenticated_at
117
+
118
+ # Client. Set bankid_client to your own instance, or let the feature
119
+ # build one from these. bankid_environment only affects the built
120
+ # client; identity digests use the environment of whichever client is
121
+ # in use.
122
+ auth_value_method :bankid_client, nil
123
+ auth_value_method :bankid_environment, :production
124
+ auth_value_method :bankid_p12_path, nil
125
+ auth_value_method :bankid_p12_password, nil
126
+ auth_value_method :bankid_cert_pem, nil
127
+ auth_value_method :bankid_key_pem, nil
128
+ auth_value_method :bankid_ca_file, nil
129
+ auth_value_method :bankid_open_timeout, 5
130
+ auth_value_method :bankid_read_timeout, 10
131
+ auth_value_method :bankid_write_timeout, 5
132
+
133
+ # Orders.
134
+ auth_value_method :bankid_identity_secret, nil
135
+ auth_value_method :bankid_return_url, nil
136
+ auth_value_method :bankid_return_risk?, false
137
+ auth_value_method :bankid_attempt_ttl, 180
138
+ auth_value_method :bankid_completion_ttl, 60
139
+ auth_value_method :bankid_collect_interval, 2
140
+ auth_value_method :bankid_qr_module_size, 4
141
+ auth_value_method :bankid_create_account?, false
142
+ auth_value_method :bankid_script_cache_control, 'public, max-age=86400'
143
+
144
+ # Tables. Set a column to nil to stop storing that value.
145
+ auth_value_method :bankid_attempts_table, :account_bankid_attempts
146
+ auth_value_method :bankid_identities_table, :account_bankid_identities
147
+ auth_value_method :bankid_identities_account_id_column, :account_id
148
+ auth_value_method :bankid_identities_digest_column, :identity_digest
149
+ auth_value_method :bankid_identities_name_column, :name
150
+ auth_value_method :bankid_identities_given_name_column, :given_name
151
+ auth_value_method :bankid_identities_surname_column, :surname
152
+ auth_value_method :bankid_identities_issue_date_column, :bankid_issue_date
153
+ auth_value_method :bankid_identities_verified_at_column, :last_verified_at
154
+ auth_value_method :bankid_identities_first_login_column, :first_login_at
155
+ auth_value_method :bankid_identities_last_login_column, :last_login_at
156
+ auth_value_method :bankid_logins_table, :account_bankid_logins
157
+ auth_value_method :bankid_logins_account_id_column, :account_id
158
+ auth_value_method :bankid_logins_ip_address_column, :ip_address
159
+ auth_value_method :bankid_logins_uhi_column, :uhi
160
+ auth_value_method :bankid_logins_step_up_mrtd_column, :step_up_mrtd
161
+ auth_value_method :bankid_logins_risk_column, :risk
162
+ auth_value_method :bankid_logins_signature_column, :signature
163
+ auth_value_method :bankid_logins_ocsp_response_column, :ocsp_response
164
+ auth_value_method :bankid_logins_created_at_column, :created_at
165
+ auth_value_method :bankid_log_signature?, false
166
+
167
+ translatable_method :bankid_start_button, 'Start BankID'
168
+ translatable_method :bankid_continue_button, 'Continue'
169
+ translatable_method :bankid_cancel_button, 'Cancel'
170
+ translatable_method :bankid_restart_button, 'Start again'
171
+ translatable_method :bankid_open_app_button, 'Open BankID on this device'
172
+ translatable_method :bankid_scan_text, 'Scan the QR code with your BankID app'
173
+
174
+ # Texts follow BankID's RFA recommendations. Override per language.
175
+ translatable_method :bankid_hint_outstanding_transaction, 'Start the BankID app'
176
+ translatable_method :bankid_hint_no_client, 'Start the BankID app'
177
+ translatable_method :bankid_hint_started, 'Searching for BankID'
178
+ translatable_method :bankid_hint_user_sign, 'Enter your security code in the BankID app'
179
+ translatable_method :bankid_hint_user_mrtd, 'Scan your ID document with the BankID app'
180
+ translatable_method :bankid_hint_user_cancel, 'Action cancelled'
181
+ translatable_method :bankid_hint_expired_transaction, 'BankID login timed out. Start again'
182
+ translatable_method :bankid_hint_certificate_err, 'Your BankID is blocked or invalid'
183
+ translatable_method :bankid_hint_start_failed, 'Could not start the BankID app'
184
+ translatable_method :bankid_hint_wait, 'Waiting for BankID'
185
+ translatable_method :bankid_hint_session_mismatch, 'This page was opened in a different browser. Start again'
186
+ translatable_method :bankid_hint_default, 'Unknown BankID error. Start again'
187
+
188
+ cached_auth_method :bankid_flow
189
+
190
+ auth_methods(
191
+ :bankid_account_from_completion,
192
+ :bankid_auth_options,
193
+ :bankid_auth_requirement,
194
+ :bankid_autostart_url,
195
+ :bankid_end_user_ip,
196
+ :bankid_hint_message,
197
+ :bankid_identity_digest,
198
+ :bankid_link_identity,
199
+ :bankid_log_login,
200
+ :bankid_new_account,
201
+ :bankid_qr_svg,
202
+ :bankid_record_login,
203
+ :bankid_register_account,
204
+ :bankid_universal_url,
205
+ :bankid_update_identity,
206
+ :bankid_web_parameters
207
+ )
208
+
209
+ # GET renders the page without side effects.
210
+ # POST finishes the login: collects if the browser did not, then consumes
211
+ # the attempt and calls Rodauth's login.
212
+ route(:bankid_login) do |r|
213
+ bankid_no_store
214
+ check_already_logged_in
215
+ before_bankid_login_route
216
+
217
+ r.get do
218
+ bankid_login_view
219
+ end
220
+
221
+ r.post do
222
+ bankid_guard do
223
+ token = session[bankid_session_key]
224
+ row = bankid_flow.read(token)
225
+
226
+ unless row[:completed_at]
227
+ status = bankid_collect_attempt(token)
228
+ bankid_html_status_response(status) unless status == 'complete'
229
+ row = bankid_flow.read(token)
230
+ end
231
+
232
+ @account = row[:account_id] && account_from_id(row[:account_id])
233
+ unless @account && open_account?
234
+ bankid_flow.remove(token)
235
+ remove_session_value(bankid_session_key)
236
+ set_redirect_error_flash bankid_no_account_error_flash
237
+ redirect bankid_failed_redirect
238
+ end
239
+
240
+ @bankid_completion = bankid_parse_stored_completion(row[:completion])
241
+ before_bankid_login
242
+
243
+ # Rodauth's login transaction wraps before_login, the session update,
244
+ # proof consumption, login recording, and the after hooks. A rejecting
245
+ # before_login halts before anything is consumed or recorded. If a
246
+ # later step raises, the transaction rolls back and the half-built
247
+ # session is cleared, so nothing records a login that did not happen.
248
+ begin
249
+ login('bankid') do
250
+ bankid_flow.consume(token)
251
+ bankid_record_login(row)
252
+ bankid_mark_authenticated
253
+ after_bankid_login
254
+ end
255
+ rescue StandardError
256
+ clear_session
257
+ raise
258
+ end
259
+ end
260
+ end
261
+ end
262
+
263
+ # POST. Starts an order. JSON for XHR, redirect to the page for forms.
264
+ route(:bankid_auth) do |r|
265
+ bankid_no_store
266
+ before_bankid_auth_route
267
+
268
+ r.post do
269
+ bankid_guard do
270
+ bankid_already_logged_in_response if logged_in?
271
+ bankid_cancel_current_attempt
272
+
273
+ nonce = Rodauth::BankID::Store.generate_token[0, 32]
274
+ token, row = bankid_flow.start(
275
+ end_user_ip: bankid_end_user_ip,
276
+ nonce:,
277
+ **bankid_auth_options(nonce)
278
+ )
279
+ set_session_value(bankid_session_key, token)
280
+ bankid_start_response(row, bankid_login_path)
281
+ end
282
+ end
283
+ end
284
+
285
+ # POST, JSON. Call every second for a fresh QR code.
286
+ route(:bankid_qr) do |r|
287
+ bankid_no_store
288
+ before_bankid_qr_route
289
+
290
+ r.post do
291
+ bankid_qr_response
292
+ end
293
+ end
294
+
295
+ # POST, JSON. Call every pollAfter seconds. Early calls get 429.
296
+ route(:bankid_collect) do |r|
297
+ bankid_no_store
298
+ before_bankid_collect_route
299
+
300
+ r.post do
301
+ bankid_guard do
302
+ bankid_already_logged_in_response if logged_in?
303
+ status = bankid_collect_attempt(session[bankid_session_key])
304
+ result = @bankid_collect_result
305
+
306
+ case status
307
+ when 'pending'
308
+ bankid_json_response(status: 'pending', hint: bankid_hint_message(result['hintCode']),
309
+ pollAfter: result['pollAfter'] || bankid_collect_interval)
310
+ when 'failed'
311
+ remove_session_value(bankid_session_key)
312
+ bankid_json_response(status: 'failed', hint: bankid_hint_message(result['hintCode']))
313
+ when 'complete'
314
+ bankid_json_response(status: 'complete')
315
+ else
316
+ remove_session_value(bankid_session_key)
317
+ bankid_json_response({ error: 'account_unavailable', hint: bankid_no_account_error_flash }, 403)
318
+ end
319
+ end
320
+ end
321
+ end
322
+
323
+ # POST. Cancels the current attempt locally and at BankID.
324
+ route(:bankid_cancel) do |r|
325
+ bankid_no_store
326
+ before_bankid_cancel_route
327
+
328
+ r.post do
329
+ bankid_cancel_current_attempt
330
+ bankid_cancel_response(bankid_cancelled_error_flash, bankid_cancelled_redirect)
331
+ end
332
+ end
333
+
334
+ # GET. The page script, with an ETag so repeat views get a 304.
335
+ route(:bankid_script, 'bankid.js') do |r|
336
+ before_bankid_script_route
337
+
338
+ r.get do
339
+ etag = Rodauth::BankID.script_etag
340
+ response['Cache-Control'] = bankid_script_cache_control
341
+ response['ETag'] = etag
342
+
343
+ if request.env['HTTP_IF_NONE_MATCH'] == etag
344
+ response.status = 304
345
+ return_response('')
346
+ end
347
+
348
+ response['Content-Type'] = 'text/javascript; charset=utf-8'
349
+ return_response(Rodauth::BankID.script)
350
+ end
351
+ end
352
+
353
+ def post_configure
354
+ super
355
+ secret = bankid_identity_secret
356
+ return if secret.is_a?(String) && secret.bytesize >= 32
357
+
358
+ raise ConfigurationError, 'bankid_identity_secret must be a string of at least 32 bytes'
359
+ end
360
+
361
+ # --- Attempt state -------------------------------------------------
362
+
363
+ # Returns the session key holding the current attempt. The login flow
364
+ # uses the default; the sign and confirm features switch it at the top
365
+ # of their routes via bankid_scope.
366
+ def bankid_session_key
367
+ @bankid_session_key || bankid_attempt_session_key
368
+ end
369
+
370
+ # Returns where form errors send the browser for the current flow.
371
+ def bankid_error_redirect
372
+ @bankid_error_redirect || bankid_failed_redirect
373
+ end
374
+
375
+ # Switches the attempt session key and error redirect for a flow that
376
+ # runs alongside login (signing, confirmation).
377
+ def bankid_scope(session_key:, error_redirect:)
378
+ @bankid_session_key = session_key
379
+ @bankid_error_redirect = error_redirect
380
+ remove_instance_variable(:@bankid_current_attempt) if defined?(@bankid_current_attempt)
381
+ end
382
+
383
+ # Answers a start request: launch data as JSON for XHR, a redirect to
384
+ # +page_path+ for plain forms.
385
+ def bankid_start_response(row, page_path)
386
+ if bankid_json_request?
387
+ bankid_json_response(
388
+ status: 'pending',
389
+ autoStartToken: row[:auto_start_token],
390
+ autostartUrl: bankid_autostart_url(row),
391
+ universalUrl: bankid_universal_url(row),
392
+ pollAfter: bankid_collect_interval
393
+ )
394
+ else
395
+ redirect page_path
396
+ end
397
+ end
398
+
399
+ # Answers a QR request with <tt>{ svg: ... }</tt>, +null+ once completed.
400
+ def bankid_qr_response
401
+ bankid_guard do
402
+ data = bankid_flow.qr(session[bankid_session_key])
403
+ bankid_json_response(svg: data && bankid_qr_svg(data))
404
+ end
405
+ end
406
+
407
+ # Answers a cancel request: JSON for XHR, flash and redirect for forms.
408
+ def bankid_cancel_response(flash, redirect_to)
409
+ if bankid_json_request?
410
+ bankid_json_response(status: 'cancelled')
411
+ else
412
+ set_redirect_error_flash flash
413
+ redirect redirect_to
414
+ end
415
+ end
416
+
417
+ # Returns the +data-*+ attributes the page script reads, as one HTML
418
+ # attribute string. Paths differ per flow.
419
+ def bankid_data_attributes(start_path:, qr_path:, collect_path:)
420
+ row = bankid_current_attempt
421
+ values = {
422
+ 'state' => bankid_attempt_state,
423
+ 'auth-url' => start_path,
424
+ 'qr-url' => qr_path,
425
+ 'collect-url' => collect_path,
426
+ 'csrf-field' => bankid_csrf_field,
427
+ 'csrf-auth' => bankid_csrf_token(start_path),
428
+ 'csrf-qr' => bankid_csrf_token(qr_path),
429
+ 'csrf-collect' => bankid_csrf_token(collect_path),
430
+ 'poll-after' => bankid_collect_interval,
431
+ 'nonce' => row ? row[:nonce] : '',
432
+ 'autostart-url' => row ? bankid_autostart_url(row) : '',
433
+ 'universal-url' => row ? bankid_universal_url(row) : '',
434
+ 'error-text' => bankid_unavailable_error_flash,
435
+ 'mismatch-text' => bankid_hint_session_mismatch
436
+ }
437
+ values.map { |k, v| %(data-#{k}="#{scope.h(v.to_s)}") }.join(' ')
438
+ end
439
+
440
+ # Returns the current attempt row, or +nil+ (clearing a stale session
441
+ # key) when there is none.
442
+ def bankid_current_attempt
443
+ return @bankid_current_attempt if defined?(@bankid_current_attempt)
444
+
445
+ token = session[bankid_session_key]
446
+ @bankid_current_attempt = token && begin
447
+ bankid_flow.read(token)
448
+ rescue Rodauth::BankID::InvalidAttempt
449
+ remove_session_value(bankid_session_key)
450
+ nil
451
+ end
452
+ end
453
+
454
+ # Returns +idle+, +pending+, or +complete+ for the page's +data-state+.
455
+ def bankid_attempt_state
456
+ row = bankid_current_attempt
457
+ return 'idle' unless row
458
+
459
+ row[:completed_at] ? 'complete' : 'pending'
460
+ end
461
+
462
+ # Drops the session's attempt and cancels it at BankID, ignoring remote
463
+ # failures — the attempt is gone locally either way.
464
+ def bankid_cancel_current_attempt
465
+ token = remove_session_value(bankid_session_key)
466
+ return unless token
467
+
468
+ begin
469
+ bankid_flow.cancel(token)
470
+ rescue Rodauth::BankID::Error
471
+ nil
472
+ end
473
+ end
474
+
475
+ # Runs collect and, on completion, verifies the identity and binds the
476
+ # attempt to an account. Returns +pending+, +failed+, +complete+, or
477
+ # +account_unavailable+.
478
+ def bankid_collect_attempt(token)
479
+ result = bankid_flow.collect(token)
480
+ @bankid_collect_result = result
481
+ return result['status'] unless result['status'] == 'complete'
482
+
483
+ completion = result['completionData']
484
+ return 'complete' unless completion
485
+
486
+ bankid_handle_completion(token, completion)
487
+ end
488
+
489
+ # One transaction. The claim comes first, so a cancelled or expired
490
+ # attempt rolls back every side effect, and a concurrent collector that
491
+ # loses the claim writes nothing. Hooks that must not roll back with the
492
+ # transaction should use +db.after_commit+ inside +after_bankid_collect+.
493
+ def bankid_handle_completion(token, completion)
494
+ @bankid_completion = completion
495
+ digest = bankid_identity_digest(completion['user']['personalNumber'])
496
+ stored = bankid_completion_to_store(completion)
497
+
498
+ transaction do
499
+ unless bankid_flow.claim(token, identity_digest: digest, completion: stored)
500
+ bankid_flow.read(token)
501
+ next 'complete'
502
+ end
503
+
504
+ account = bankid_account_from_completion(completion)
505
+ account ||= bankid_register_account(completion) if bankid_create_account?
506
+ @account = account
507
+
508
+ unless account && open_account?
509
+ bankid_flow.remove(token)
510
+ next 'account_unavailable'
511
+ end
512
+
513
+ bankid_update_identity(completion)
514
+ after_bankid_collect
515
+ bankid_flow.assign_account(token, account_id: account_id)
516
+ 'complete'
517
+ end
518
+ end
519
+
520
+ # Returns BankID's +completionData+. In +after_bankid_collect+ and the
521
+ # account hooks this is the full payload; in +after_bankid_login+ it is
522
+ # the stored subset (+ipAddress+, +uhi+, +mrtd+, +risk+, and
523
+ # +signature+ / +ocspResponse+ when enabled).
524
+ def bankid_completion
525
+ @bankid_completion
526
+ end
527
+
528
+ # Returns the JSON subset of +completionData+ kept on the attempt row
529
+ # until the finishing POST.
530
+ def bankid_completion_to_store(completion)
531
+ device = completion['device'].is_a?(Hash) ? completion['device'] : {}
532
+ step_up = completion['stepUp'].is_a?(Hash) ? completion['stepUp'] : {}
533
+ data = {
534
+ 'ipAddress' => device['ipAddress'],
535
+ 'uhi' => device['uhi'],
536
+ 'mrtd' => step_up['mrtd'],
537
+ 'risk' => completion['risk']
538
+ }
539
+ if bankid_log_signature?
540
+ data['signature'] = completion['signature']
541
+ data['ocspResponse'] = completion['ocspResponse']
542
+ end
543
+ JSON.generate(data.compact)
544
+ end
545
+
546
+ def bankid_parse_stored_completion(json)
547
+ return {} if json.nil? || json.empty?
548
+
549
+ JSON.parse(json)
550
+ rescue JSON::ParserError
551
+ {}
552
+ end
553
+
554
+ # Records in the session when this account last proved its identity
555
+ # with BankID. Read by the +bankid_confirm+ feature's grace period.
556
+ def bankid_mark_authenticated
557
+ set_session_value(bankid_authenticated_at_session_key, Time.now.to_i)
558
+ end
559
+
560
+ # --- Account resolution --------------------------------------------
561
+
562
+ # Returns the environment Symbol requests go to. Comes from the client,
563
+ # so an injected test client never hashes identities under the
564
+ # production namespace.
565
+ def bankid_effective_environment
566
+ client = bankid_client || bankid_default_client
567
+ client.respond_to?(:environment) ? client.environment.to_sym : bankid_environment
568
+ end
569
+
570
+ # Returns the hex HMAC-SHA256 that stands in for +personal_number+ in
571
+ # the identities table. The environment is part of the input, so test
572
+ # and production identities never collide.
573
+ def bankid_identity_digest(personal_number)
574
+ OpenSSL::HMAC.hexdigest('SHA256', bankid_identity_secret,
575
+ "se.bankid:#{bankid_effective_environment}:#{personal_number}")
576
+ end
577
+
578
+ # Returns the identities dataset filtered to +personal_number+.
579
+ def bankid_identity_ds(personal_number)
580
+ db[bankid_identities_table].where(
581
+ bankid_identities_digest_column => bankid_identity_digest(personal_number)
582
+ )
583
+ end
584
+
585
+ # Returns the account Hash linked to the completion's personnummer, or
586
+ # +nil+. Override to resolve accounts your own way.
587
+ def bankid_account_from_completion(completion)
588
+ id = bankid_identity_ds(completion['user']['personalNumber']).get(bankid_identities_account_id_column)
589
+ id && account_ds(id).first
590
+ end
591
+
592
+ # Override when +bankid_create_account?+ is true. Must return the
593
+ # account Hash (or +nil+ to refuse).
594
+ def bankid_new_account(_completion)
595
+ raise ConfigurationError, 'define bankid_new_account to create accounts from BankID logins'
596
+ end
597
+
598
+ # Creates an account inside a savepoint. If another request linked the
599
+ # same identity first, the savepoint rolls back and the winner is used.
600
+ def bankid_register_account(completion)
601
+ account = nil
602
+ error = raises_uniqueness_violation? do
603
+ account = bankid_new_account(completion)
604
+ end
605
+ return account unless error
606
+
607
+ account = bankid_account_from_completion(completion)
608
+ raise error unless account
609
+
610
+ account
611
+ end
612
+
613
+ # Links +personal_number+ to +account_id+. Raises a uniqueness
614
+ # violation when that BankID is already linked.
615
+ def bankid_link_identity(account_id, personal_number)
616
+ db[bankid_identities_table].insert(
617
+ bankid_identities_account_id_column => account_id,
618
+ bankid_identities_digest_column => bankid_identity_digest(personal_number)
619
+ )
620
+ end
621
+
622
+ # Refreshes the identity row's name, issue date, and verification time
623
+ # from +completion+. Runs at collect time, inside the claim transaction.
624
+ def bankid_update_identity(completion)
625
+ user = completion['user']
626
+ values = {}
627
+ values[bankid_identities_name_column] = user['name'] if bankid_identities_name_column
628
+ values[bankid_identities_given_name_column] = user['givenName'] if bankid_identities_given_name_column
629
+ values[bankid_identities_surname_column] = user['surname'] if bankid_identities_surname_column
630
+
631
+ if bankid_identities_issue_date_column && (date = bankid_parse_date(completion['bankIdIssueDate']))
632
+ values[bankid_identities_issue_date_column] = date
633
+ end
634
+
635
+ if (col = bankid_identities_verified_at_column)
636
+ values[col] = Sequel::CURRENT_TIMESTAMP
637
+ end
638
+
639
+ return if values.empty?
640
+
641
+ bankid_identity_ds(user['personalNumber']).update(values)
642
+ end
643
+
644
+ # Stamps first/last login on the identity row and writes the login log.
645
+ # Runs in the transaction that consumes the attempt.
646
+ def bankid_record_login(row)
647
+ values = {}
648
+ if (col = bankid_identities_last_login_column)
649
+ values[col] = Sequel::CURRENT_TIMESTAMP
650
+ end
651
+ if (col = bankid_identities_first_login_column)
652
+ values[col] = Sequel.function(:coalesce, col, Sequel::CURRENT_TIMESTAMP)
653
+ end
654
+ unless values.empty?
655
+ db[bankid_identities_table].where(bankid_identities_digest_column => row[:identity_digest]).update(values)
656
+ end
657
+
658
+ bankid_log_login(bankid_completion)
659
+ end
660
+
661
+ # Inserts the login log row from +data+, the stored subset
662
+ # (+ipAddress+, +uhi+, +mrtd+, +risk+, +signature+, +ocspResponse+).
663
+ # A +nil+ +bankid_logins_table+ disables the log.
664
+ def bankid_log_login(data)
665
+ return unless bankid_logins_table
666
+
667
+ values = { bankid_logins_account_id_column => account_id }
668
+ values[bankid_logins_ip_address_column] = data['ipAddress'] if bankid_logins_ip_address_column
669
+ values[bankid_logins_uhi_column] = data['uhi'] if bankid_logins_uhi_column
670
+ values[bankid_logins_risk_column] = data['risk'] if bankid_logins_risk_column
671
+
672
+ if bankid_logins_step_up_mrtd_column && data.key?('mrtd')
673
+ values[bankid_logins_step_up_mrtd_column] = data['mrtd'] ? true : false
674
+ end
675
+
676
+ if bankid_log_signature?
677
+ values[bankid_logins_signature_column] = data['signature'] if bankid_logins_signature_column
678
+ values[bankid_logins_ocsp_response_column] = data['ocspResponse'] if bankid_logins_ocsp_response_column
679
+ end
680
+
681
+ values[bankid_logins_created_at_column] = Sequel::CURRENT_TIMESTAMP if bankid_logins_created_at_column
682
+ db[bankid_logins_table].insert(values)
683
+ end
684
+
685
+ # --- Order options -------------------------------------------------
686
+
687
+ # Returns the client IP sent to BankID. Must be the real one: behind a
688
+ # proxy, make sure Roda sees +X-Forwarded-For+ from a trusted hop only,
689
+ # or override this method.
690
+ def bankid_end_user_ip
691
+ request.ip
692
+ end
693
+
694
+ # Returns the BankID +requirement+ object for login orders, e.g.
695
+ # <tt>{ 'pinCode' => true }</tt>. +nil+ means none.
696
+ def bankid_auth_requirement
697
+ nil
698
+ end
699
+
700
+ # Returns the BankID v6.1 +web+ object (+referringDomain+, +userAgent+,
701
+ # +deviceIdentifier+). +nil+ sends nothing. See the README before
702
+ # turning it on.
703
+ def bankid_web_parameters
704
+ nil
705
+ end
706
+
707
+ # Returns the keyword options Flow#start forwards to Client#auth.
708
+ def bankid_auth_options(nonce)
709
+ opts = {
710
+ requirement: bankid_auth_requirement,
711
+ return_risk: bankid_return_risk?,
712
+ web: bankid_web_parameters
713
+ }
714
+ opts[:return_url] = bankid_attempt_return_url(nonce) if bankid_return_url
715
+ opts
716
+ end
717
+
718
+ # Returns the return URL for an order +kind+. The sign and confirm
719
+ # features answer for theirs.
720
+ def bankid_return_url_for(_kind)
721
+ bankid_return_url
722
+ end
723
+
724
+ # Returns the return URL with the attempt's +nonce+ in the fragment, or
725
+ # +nil+ when no return URL is configured.
726
+ def bankid_attempt_return_url(nonce, kind = 'auth')
727
+ base = bankid_return_url_for(kind)
728
+ return unless base
729
+
730
+ "#{base}#bankid=#{nonce}"
731
+ end
732
+
733
+ # Returns the desktop/Android launch URL. The app closes and the
734
+ # browser keeps focus.
735
+ def bankid_autostart_url(row = bankid_current_attempt)
736
+ "bankid:///?autostarttoken=#{row[:auto_start_token]}&redirect=null"
737
+ end
738
+
739
+ # Returns the mobile launch URL. iOS requires a redirect value, so this
740
+ # uses the return URL.
741
+ def bankid_universal_url(row = bankid_current_attempt)
742
+ redirect = bankid_attempt_return_url(row[:nonce], row[:kind] || 'auth')
743
+ target = redirect ? CGI.escape(redirect) : 'null'
744
+ "https://app.bankid.com/?autostarttoken=#{row[:auto_start_token]}&redirect=#{target}"
745
+ end
746
+
747
+ # --- Rendering -----------------------------------------------------
748
+
749
+ # Returns +data+ as an inline SVG.
750
+ def bankid_qr_svg(data)
751
+ RQRCode::QRCode.new(data, level: :m).as_svg(
752
+ module_size: bankid_qr_module_size,
753
+ standalone: true,
754
+ use_path: true,
755
+ viewbox: true
756
+ ).sub(/\A<\?xml[^>]*\?>/, '')
757
+ end
758
+
759
+ # Returns the SVG for the current attempt, or an empty String when
760
+ # there is none or it already completed.
761
+ def bankid_current_qr_svg
762
+ row = bankid_current_attempt
763
+ return '' if !row || row[:completed_at]
764
+
765
+ bankid_qr_svg(bankid_flow.qr(session[bankid_session_key]))
766
+ rescue Rodauth::BankID::InvalidAttempt
767
+ ''
768
+ end
769
+
770
+ # Returns the user-facing text for a BankID hint +code+.
771
+ def bankid_hint_message(code)
772
+ case code
773
+ when 'outstandingTransaction' then bankid_hint_outstanding_transaction
774
+ when 'noClient' then bankid_hint_no_client
775
+ when 'started' then bankid_hint_started
776
+ when 'userSign', 'userCallConfirm' then bankid_hint_user_sign
777
+ when 'userMrtd' then bankid_hint_user_mrtd
778
+ when 'userCancel', 'cancelled' then bankid_hint_user_cancel
779
+ when 'expiredTransaction' then bankid_hint_expired_transaction
780
+ when 'certificateErr' then bankid_hint_certificate_err
781
+ when 'startFailed' then bankid_hint_start_failed
782
+ else bankid_hint_default
783
+ end
784
+ end
785
+
786
+ def bankid_csrf_token(path)
787
+ scope.csrf_token(path) if scope.respond_to?(:csrf_token)
788
+ end
789
+
790
+ def bankid_csrf_field
791
+ scope.respond_to?(:csrf_field) ? scope.csrf_field : '_csrf'
792
+ end
793
+
794
+ def bankid_no_store
795
+ response['Cache-Control'] = 'no-store'
796
+ end
797
+
798
+ # True for XHR: an +Accept+ of +application/json+ or the
799
+ # +X-Requested-With+ header. Independent of Rodauth's +json+ feature,
800
+ # which keys off +Content-Type+.
801
+ def bankid_json_request?
802
+ request.env['HTTP_ACCEPT'].to_s.include?('application/json') ||
803
+ request.env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'
804
+ end
805
+
806
+ def bankid_json_response(hash, status = 200)
807
+ response.status = status
808
+ response['Content-Type'] = 'application/json'
809
+ bankid_no_store
810
+ return_response(JSON.generate(hash))
811
+ end
812
+
813
+ private
814
+
815
+ def bankid_default_client
816
+ return @bankid_default_client if defined?(@bankid_default_client)
817
+
818
+ @bankid_default_client = _bankid_default_client
819
+ end
820
+
821
+ def _bankid_default_client
822
+ opts = {
823
+ environment: bankid_environment,
824
+ ca_file: bankid_ca_file,
825
+ open_timeout: bankid_open_timeout,
826
+ read_timeout: bankid_read_timeout,
827
+ write_timeout: bankid_write_timeout
828
+ }
829
+
830
+ if bankid_p12_path
831
+ Rodauth::BankID::Client.from_p12(bankid_p12_path, bankid_p12_password, **opts)
832
+ elsif bankid_cert_pem && bankid_key_pem
833
+ Rodauth::BankID::Client.new(
834
+ certificate: OpenSSL::X509::Certificate.new(bankid_cert_pem),
835
+ private_key: OpenSSL::PKey.read(bankid_key_pem),
836
+ **opts
837
+ )
838
+ else
839
+ raise ConfigurationError, 'set bankid_client, bankid_p12_path, or bankid_cert_pem and bankid_key_pem'
840
+ end
841
+ end
842
+
843
+ def _bankid_flow
844
+ Rodauth::BankID::Flow.new(
845
+ client: bankid_client || bankid_default_client,
846
+ store: Rodauth::BankID::Store.new(db, table: bankid_attempts_table),
847
+ ttl: bankid_attempt_ttl,
848
+ completion_ttl: bankid_completion_ttl,
849
+ collect_interval: bankid_collect_interval
850
+ )
851
+ end
852
+
853
+ def bankid_parse_date(value)
854
+ value && Date.parse(value.to_s)
855
+ rescue ArgumentError, TypeError
856
+ nil
857
+ end
858
+
859
+ # Maps BankID errors to JSON codes for XHR and to flash + redirect for forms.
860
+ def bankid_guard
861
+ yield
862
+ rescue Rodauth::BankID::TooFrequent
863
+ bankid_error_response(429, 'poll_too_fast', bankid_hint_wait, retry_after: bankid_collect_interval)
864
+ rescue Rodauth::BankID::InvalidAttempt
865
+ remove_session_value(bankid_session_key)
866
+ bankid_error_response(410, 'attempt_unavailable', bankid_expired_error_flash)
867
+ rescue Rodauth::BankID::Error
868
+ bankid_error_response(502, 'bankid_unavailable', bankid_unavailable_error_flash)
869
+ end
870
+
871
+ def bankid_error_response(status, code, message, retry_after: nil)
872
+ if bankid_json_request?
873
+ response['Retry-After'] = retry_after.to_s if retry_after
874
+ body = { error: code, hint: message }
875
+ body[:pollAfter] = retry_after if retry_after
876
+ bankid_json_response(body, status)
877
+ else
878
+ set_redirect_error_flash message
879
+ redirect bankid_error_redirect
880
+ end
881
+ end
882
+
883
+ def bankid_already_logged_in_response
884
+ if bankid_json_request?
885
+ bankid_json_response({ error: 'already_logged_in' }, 409)
886
+ else
887
+ redirect login_redirect
888
+ end
889
+ end
890
+
891
+ # Form-based Continue button pressed before the order finished.
892
+ def bankid_html_status_response(status)
893
+ result = @bankid_collect_result || {}
894
+ case status
895
+ when 'pending'
896
+ set_redirect_error_flash bankid_hint_message(result['hintCode'])
897
+ redirect bankid_login_path
898
+ when 'failed'
899
+ remove_session_value(bankid_session_key)
900
+ set_redirect_error_flash bankid_hint_message(result['hintCode'])
901
+ redirect bankid_failed_redirect
902
+ else
903
+ remove_session_value(bankid_session_key)
904
+ set_redirect_error_flash bankid_no_account_error_flash
905
+ redirect bankid_failed_redirect
906
+ end
907
+ end
908
+
909
+ # Serve the gem's template unless the app provides its own.
910
+ def template_path(page)
911
+ path = File.expand_path("../../../templates/#{page}.erb", __dir__)
912
+ File.file?(path) ? path : super
913
+ end
914
+ end
915
+ end