The personal finance app for everyone (by everyone)
Ruby
fix(trade-republic): track the 24-hour login and fix login edge cases (#4232)
Niels Eulinkbc2af4d1a3c2
diff --git a/app/components/trade_republic/account_editor_component.rb b/app/components/trade_republic/account_editor_component.rbindex aeacc623c2..db8d52fe36 100644--- a/app/components/trade_republic/account_editor_component.rb+++ b/app/components/trade_republic/account_editor_component.rb@@ -20,7 +20,7 @@ class TradeRepublic::AccountEditorComponent < ApplicationComponent# healthy, fully linked connections among several start closed.def open?(item)items.size == 1 || qr_login_active?(item) || item.pending_login_state.present? ||- !item.good? || setup_cta_visible?(item)+ item.needs_login? || setup_cta_visible?(item)end# Mirrors the card template's condition for the "X accounts discovered —diff --git a/app/components/trade_republic/connection_card_component.html.erb b/app/components/trade_republic/connection_card_component.html.erbindex c2f7166337..621dfda0f9 100644--- a/app/components/trade_republic/connection_card_component.html.erb+++ b/app/components/trade_republic/connection_card_component.html.erb@@ -43,7 +43,7 @@icon: "refresh-cw",href: helpers.sync_trade_republic_item_path(item, source: "panel"),method: :post,- disabled: item.syncing?+ disabled: item.syncing? || !item.ready_for_sync?) %><% end %>@@ -59,36 +59,14 @@) %></div>- <% if item.pending_login_state.blank? || login_stage == "qr_pending" %>- <div class="space-y-3" data-controller="trade-republic-qr"- data-trade-republic-qr-auto-poll-value="<%= qr_active %>"- data-trade-republic-qr-initiate-url-value="<%= helpers.initiate_qr_login_trade_republic_item_path(item) %>"- data-trade-republic-qr-poll-url-value="<%= helpers.poll_qr_login_trade_republic_item_path(item) %>"- data-trade-republic-qr-cancel-url-value="<%= helpers.cancel_qr_login_trade_republic_item_path(item) %>"- data-trade-republic-qr-return-url-value="<%= helpers.settings_providers_path(anchor: "trade-republic") %>"- data-trade-republic-qr-loading-text-value="<%= translation("qr_loading") %>"- data-trade-republic-qr-instruction-text-value="<%= translation("qr_instruction") %>"- data-trade-republic-qr-success-text-value="<%= translation("qr_success") %>"- data-trade-republic-qr-error-text-value="<%= translation("qr_error") %>"- data-trade-republic-qr-login-text-value="<%= translation("qr_login") %>"- data-trade-republic-qr-cancel-text-value="<%= translation("qr_cancel") %>">- <%= render DS::Button.new(- text: qr_active ? translation("qr_cancel") : translation("qr_login"),- variant: :outline,- size: :sm,- icon: "qr-code",- type: "button",- data: {- action: "trade-republic-qr#toggle",- trade_republic_qr_target: "button"- }+ <%# A lapsed login can start again with a QR code, as on Accounts. %>+ <% if item.pending_login_state.blank? || login_stage.in?(%w[qr_pending expired]) %>+ <%= render TradeRepublic::QrLoginComponent.new(+ item: item,+ return_url: helpers.settings_providers_path(anchor: "trade-republic"),+ active: qr_active,+ code_svg: qr_code_svg) %>-- <div data-trade-republic-qr-target="panel" <%= "hidden" unless qr_active %> class="rounded-lg border border-secondary bg-container-inset p-4 space-y-3">- <p data-trade-republic-qr-target="status" class="text-sm text-secondary"></p>- <div data-trade-republic-qr-target="code" class="qrcode flex justify-center min-h-48"><%= qr_code_svg %></div>- </div>- </div><% end %><% if login_stage == "authenticator_code" %>@@ -169,7 +147,7 @@<%= login_stage == "authenticator_code" ? translation("awaiting_authenticator_code") : translation("awaiting_confirmation") %></p><% end %>- <% elsif item.status == "good" && item.session_configured? %>+ <% elsif item.ready_for_sync? %><div class="w-2 h-2 bg-success rounded-full"></div><p class="text-sm text-secondary"><% if item.unlinked_accounts_count.positive? %>@@ -187,14 +165,18 @@<%= translation("status_configured_suffix") %><% end %></p>- <% elsif item.status == "requires_update" %>+ <% elsif item.needs_login? %><div class="w-2 h-2 bg-warning rounded-full"></div>- <p class="text-sm text-secondary"><%= translation("requires_update") %></p>+ <p class="text-sm text-destructive"><%= translation("requires_update") %></p><% else %><div class="w-2 h-2 bg-surface-inset rounded-full"></div><p class="text-sm text-secondary"><%= translation("not_configured") %></p><% end %></div>++ <% if item.ready_for_sync? && item.session_expires_at.present? %>+ <p class="text-xs text-secondary"><%= helpers.trade_republic_session_expiry("settings.providers.trade_republic_panel.session_expires_in", item.session_expires_at) %></p>+ <% end %></div><% end %></div>diff --git a/app/components/trade_republic/qr_login_component.html.erb b/app/components/trade_republic/qr_login_component.html.erbnew file mode 100644index 0000000000..5534df2cbb--- /dev/null+++ b/app/components/trade_republic/qr_login_component.html.erb@@ -0,0 +1,29 @@+<div class="space-y-3" data-controller="trade-republic-qr"+ data-trade-republic-qr-auto-poll-value="<%= active %>"+ data-trade-republic-qr-initiate-url-value="<%= helpers.initiate_qr_login_trade_republic_item_path(item) %>"+ data-trade-republic-qr-poll-url-value="<%= helpers.poll_qr_login_trade_republic_item_path(item) %>"+ data-trade-republic-qr-cancel-url-value="<%= helpers.cancel_qr_login_trade_republic_item_path(item) %>"+ data-trade-republic-qr-return-url-value="<%= return_url %>"+ data-trade-republic-qr-loading-text-value="<%= translation("qr_loading") %>"+ data-trade-republic-qr-instruction-text-value="<%= translation("qr_instruction") %>"+ data-trade-republic-qr-success-text-value="<%= translation("qr_success") %>"+ data-trade-republic-qr-error-text-value="<%= translation("qr_error") %>"+ data-trade-republic-qr-login-text-value="<%= translation("qr_login") %>"+ data-trade-republic-qr-cancel-text-value="<%= translation("qr_cancel") %>">+ <%= render DS::Button.new(+ text: active ? translation("qr_cancel") : translation("qr_login"),+ variant: :outline,+ size: :sm,+ icon: "qr-code",+ type: "button",+ data: {+ action: "trade-republic-qr#toggle",+ trade_republic_qr_target: "button"+ }+ ) %>++ <div data-trade-republic-qr-target="panel" <%= "hidden" unless active %> class="rounded-lg border border-secondary bg-container-inset p-4 space-y-3">+ <p data-trade-republic-qr-target="status" class="text-sm text-secondary"></p>+ <div data-trade-republic-qr-target="code" class="qrcode flex justify-center min-h-48"><%= code_svg %></div>+ </div>+</div>diff --git a/app/components/trade_republic/qr_login_component.rb b/app/components/trade_republic/qr_login_component.rbnew file mode 100644index 0000000000..50cf429f80--- /dev/null+++ b/app/components/trade_republic/qr_login_component.rb@@ -0,0 +1,14 @@+# The QR login button and panel, shared by the settings connection card and+# the Accounts page so a connection can log in again from either place.+class TradeRepublic::QrLoginComponent < ApplicationComponent+ include TradeRepublic::PanelTranslatable++ def initialize(item:, return_url:, active: false, code_svg: nil)+ @item = item+ @return_url = return_url+ @active = active+ @code_svg = code_svg+ end++ attr_reader :item, :return_url, :active, :code_svg+enddiff --git a/app/controllers/trade_republic_items_controller.rb b/app/controllers/trade_republic_items_controller.rbindex 0f2d529214..b452b7d490 100644--- a/app/controllers/trade_republic_items_controller.rb+++ b/app/controllers/trade_republic_items_controller.rb@@ -276,6 +276,8 @@ class TradeRepublicItemsController < ApplicationControllerdef updateattrs = trade_republic_item_params.to_h+ # The form leaves the phone number blank to keep the current one.+ attrs.delete("phone_number") if attrs["phone_number"].blank?login_pin = attrs["pin"]reauthentication_required = reauthentication_needed?(attrs)@@ -319,10 +321,13 @@ class TradeRepublicItemsController < ApplicationControllerenddef sync- @trade_republic_item.sync_later unless @trade_republic_item.syncing?+ # A connection that needs a new login can only fail to sync.+ syncing = @trade_republic_item.syncing?+ queued = @trade_republic_item.ready_for_sync? && !syncing+ @trade_republic_item.sync_later if queuedif provider_panel_form? && turbo_panel_request?# Only this card, as the login steps do, so the other cards keep their state.- return render_login_panel(notice: t("settings.providers.sync_provider_in_progress"))+ return render_login_panel(notice: (t("settings.providers.sync_provider_in_progress") if queued || syncing))endrespond_to do |format|@@ -407,7 +412,8 @@ class TradeRepublicItemsController < ApplicationController)end- tr_account.trade_republic_item.sync_later unless tr_account.trade_republic_item.syncing?+ linked_item = tr_account.trade_republic_item+ linked_item.sync_later if linked_item.ready_for_sync? && !linked_item.syncing?if processing_failedredirect_to account_path(account), notice: t(".success"), alert: t(".processing_failed"), status: :see_otherelse@@ -434,7 +440,7 @@ class TradeRepublicItemsController < ApplicationControllerlatest_sync = @trade_republic_item.syncs.ordered.firstshould_sync = latest_sync.nil? || !latest_sync.completed?- if no_accounts && !@trade_republic_item.syncing? && should_sync && @trade_republic_item.session_configured?+ if no_accounts && !@trade_republic_item.syncing? && should_sync && @trade_republic_item.ready_for_sync?@trade_republic_item.sync_laterend@@ -504,7 +510,8 @@ class TradeRepublicItemsController < ApplicationControllerend@trade_republic_item.update!(pending_account_setup: @trade_republic_item.unlinked_accounts_count.positive?)- @trade_republic_item.sync_later if created_accounts.any?+ # The accounts are set up from stored data; syncing them needs a login.+ @trade_republic_item.sync_later if created_accounts.any? && @trade_republic_item.ready_for_sync?if created_accounts.any?options = { notice: t(".success", count: created_accounts.count), status: :see_other }diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rbindex cb765cb198..9e392d76b7 100644--- a/app/helpers/settings_helper.rb+++ b/app/helpers/settings_helper.rb@@ -120,7 +120,7 @@ module SettingsHelpersync_based_summary(key)when "trade_republic"return { status: :off } unless @trade_republic_items&.any?- sync_based_summary(key)+ trade_republic_summarywhen "indexa_capital"return { status: :off } unless @indexa_capital_items&.any?sync_based_summary(key)@@ -278,6 +278,27 @@ module SettingsHelperendend+ # Like Enable Banking, the row warns before a session ends and once a+ # connection has to log in again. A Trade Republic login lasts only+ # 24 hours, so the warning starts two hours before the end. A login+ # comes first: an ended session no longer syncs, so a failed last sync+ # would otherwise show until the next login.+ def trade_republic_summary+ summary = sync_based_summary("trade_republic")++ if @trade_republic_items.any?(&:needs_login?)+ return summary.merge(status: :warn, meta: t("settings.providers.meta.login_required"))+ end+ return summary if summary[:status] == :err++ expiring = @trade_republic_items+ .select { |item| item.ready_for_sync? && item.session_expires_at.present? && item.session_expires_at < 2.hours.from_now }+ .min_by(&:session_expires_at)+ return summary unless expiring++ summary.merge(status: :warn, meta: trade_republic_session_expiry("settings.providers.meta.login_expires_soon", expiring.session_expires_at))+ end+def not_self_hosted?!self_hosted?enddiff --git a/app/helpers/trade_republic_helper.rb b/app/helpers/trade_republic_helper.rbnew file mode 100644index 0000000000..9f3fdc0a05--- /dev/null+++ b/app/helpers/trade_republic_helper.rb@@ -0,0 +1,11 @@+module TradeRepublicHelper+ # "Login expires in about 5 hours (16 Oct 18:45)." Where the sentence has no+ # translation it falls back to English, and so do its time words, so the+ # sentence never mixes two languages.+ def trade_republic_session_expiry(key, expires_at)+ locale = I18n.t(key, default: nil, fallback: false) ? I18n.locale : I18n.default_locale+ I18n.with_locale(locale) do+ t(key, time: distance_of_time_in_words_to_now(expires_at), at: l(expires_at, format: :short))+ end+ end+enddiff --git a/app/javascript/controllers/trade_republic_qr_controller.js b/app/javascript/controllers/trade_republic_qr_controller.jsindex dac0cee896..1f3b318c31 100644--- a/app/javascript/controllers/trade_republic_qr_controller.js+++ b/app/javascript/controllers/trade_republic_qr_controller.js@@ -53,22 +53,31 @@ export default class extends Controller {this.codeTarget.replaceChildren();this.statusTarget.textContent = this.loadingTextValue;+ let initiation = null;try {- const response = await fetch(this.initiateUrlValue, {+ // A cancel waits for this request: sent earlier, it would be overtaken+ // by the login this request stores.+ initiation = fetch(this.initiateUrlValue, {method: "POST",headers: { ...this.headers(), Accept: "text/vnd.turbo-stream.html" },credentials: "same-origin",body: this.body(),});+ this.initiation = initiation;+ const response = await initiation;+ if (this.stopped) return;if (!response.ok)throw new Error(`QR login initiation failed: ${response.status}`);const result = await response.json();+ if (this.stopped) return;this.renderQr(result);await this.poll();} catch (error) {this.showError(error);+ } finally {+ if (this.initiation === initiation) this.initiation = null;}}@@ -186,25 +195,49 @@ export default class extends Controller {this.polling = false;this.panelTarget.hidden = true;this.codeTarget.replaceChildren();- this.buttonTarget.disabled = false;+ // A login started before the server confirms the cancellation would be+ // cleared by it, so the button stays disabled until then.+ this.buttonTarget.disabled = true;+ this.setButtonLabel(this.loginTextValue);try {+ await this.initiation?.catch(() => {});const response = await fetch(this.cancelUrlValue, {method: "POST",- headers: this.headers(),+ headers: { ...this.headers(), Accept: "text/vnd.turbo-stream.html" },credentials: "same-origin",body: this.body(),});if (!response.ok)throw new Error(`QR login cancellation failed: ${response.status}`);- Turbo.renderStreamMessage(await response.text());+ const stream = await response.text();+ if (!this.element.isConnected) return;++ // In Settings this replaces the connection card, which brings back the+ // credentials form hidden while the login was pending. Turbo replaces+ // it on the next repaint, so the old button stays disabled until the+ // new card brings an enabled one. The Accounts page has no such card.+ const replacesCard = this.streamReplacesElement(stream);+ Turbo.renderStreamMessage(stream);+ if (!replacesCard) this.buttonTarget.disabled = false;} catch (error) {this.stopped = false;+ this.buttonTarget.disabled = false;console.warn("[Trade Republic] QR login cancellation failed", error);}}+ streamReplacesElement(stream) {+ const template = document.createElement("template");+ template.innerHTML = stream;+ const targetId = template.content+ .querySelector("turbo-stream")+ ?.getAttribute("target");+ const target = targetId && document.getElementById(targetId);+ return Boolean(target?.contains(this.element));+ }+renderQr(result) {if (!result.qr_code_svg) return;this.codeTarget.innerHTML = result.qr_code_svg;@@ -220,7 +253,12 @@ export default class extends Controller {}setButtonLabel(label) {- if (this.hasLabelTarget) this.labelTarget.textContent = label;+ // DS::Button renders its text in a span, so without a label target the+ // button's own text is updated.+ const target = this.hasLabelTarget+ ? this.labelTarget+ : this.buttonTarget.querySelector("span");+ if (target) target.textContent = label;}headers() {diff --git a/app/jobs/trade_republic_pre_expiry_sync_job.rb b/app/jobs/trade_republic_pre_expiry_sync_job.rbnew file mode 100644index 0000000000..d1e3a55987--- /dev/null+++ b/app/jobs/trade_republic_pre_expiry_sync_job.rb@@ -0,0 +1,23 @@+# A Trade Republic session ends 24 hours after login, whatever time the daily+# auto-sync runs. One sync shortly before the end picks up the day's activity+# while the session still works.+class TradeRepublicPreExpirySyncJob < ApplicationJob+ queue_as :scheduled++ LEAD_TIME = 1.hour++ def self.schedule_for(item)+ run_at = item.session_expires_at - LEAD_TIME+ return if run_at.past?++ set(wait_until: run_at).perform_later(item, session_expires_at: item.session_expires_at.to_i)+ end++ def perform(item, session_expires_at:)+ # A newer login has scheduled its own sync.+ return unless item.session_expires_at&.to_i == session_expires_at+ return if item.scheduled_for_deletion? || item.syncing? || !item.ready_for_sync?++ item.sync_later+ end+enddiff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rbindex e7711d1d71..b73a180cc8 100644--- a/app/models/provider/trade_republic_client.rb+++ b/app/models/provider/trade_republic_client.rb@@ -178,9 +178,10 @@ class Provider::TradeRepublicClientattr_reader :phone_number, :pin- def initialize(phone_number:, pin: nil)+ def initialize(phone_number:, pin: nil, device_id: nil)@phone_number = phone_number.to_s.strip@pin = pin.to_s+ @device_id = device_idenddef initiate_login@@ -346,7 +347,11 @@ class Provider::TradeRepublicClientenddef login_stage(pending_login_b64:)- return "qr_pending" if qr_login?(pending_login_b64: pending_login_b64)+ if qr_login?(pending_login_b64: pending_login_b64)+ # Raises LoginExpired once the challenge has lapsed, as for a push login.+ decode_qr_pending(pending_login_b64)+ return "qr_pending"+ endpending = decode_pending(pending_login_b64)if pending["required_action"] == "AUTHENTICATOR_VERIFICATION" && !pending["authenticator_verified"]@@ -380,7 +385,9 @@ class Provider::TradeRepublicClientdef sync_once(session_txt:, known_newest_event_id:, timeline_max_pages:, timeline_cursors: {}, enrich_events: [], symbol_lookup_isins: [], known_instrument_symbols: {}, interrupted_backfills: {})session = new_session(session_blob: session_txt)account_response = session.get("/api/v2/auth/account")- return Result.new(data: { "status" => "session_expired" }) if [ 401, 403 ].include?(account_response.code.to_i)+ if [ 401, 403 ].include?(account_response.code.to_i) && !waf_error?(account_response)+ return Result.new(data: { "status" => "session_expired" })+ endraise_http_error(account_response)account = parse_json(account_response)raise MalformedResponse, "Trade Republic account response did not contain a securities account number" if account["securitiesAccountNumber"].blank?@@ -678,7 +685,11 @@ class Provider::TradeRepublicClientenddef new_session(session_blob: nil)- Provider::TradeRepublicSession.new(phone_number: phone_number, pin: pin, session_blob: session_blob)+ Provider::TradeRepublicSession.new(phone_number: phone_number, pin: pin, session_blob: session_blob, device_id: @device_id)+ end++ def waf_error?(response)+ response_error_code(response).to_s.match?(/WAF|MISSING_REQUIRED_HEADER/)enddef require_pin!@@ -757,7 +768,7 @@ class Provider::TradeRepublicClientdef raise_http_error(response, login: false)return if response.is_a?(Net::HTTPSuccess)error_code = response_error_code(response)- if error_code.to_s.match?(/WAF|MISSING_REQUIRED_HEADER/)+ if waf_error?(response)raise WafRequired, "Trade Republic requires an AWS WAF browser token"endraise_login_error(response) if login@@ -799,6 +810,8 @@ class Provider::TradeRepublicClientdef response_error_code(response)body = parse_json(response)+ return unless body.is_a?(Hash)+body["errorCode"].presence || body.dig("errors", 0, "errorCode").presencerescue MalformedResponsenildiff --git a/app/models/provider/trade_republic_session.rb b/app/models/provider/trade_republic_session.rbindex f595cfccda..daf37c1436 100644--- a/app/models/provider/trade_republic_session.rb+++ b/app/models/provider/trade_republic_session.rb@@ -20,10 +20,11 @@ class Provider::TradeRepublicSessionattr_reader :phone_number, :pin- def initialize(phone_number:, pin:, session_blob: nil)+ def initialize(phone_number:, pin:, session_blob: nil, device_id: nil)@phone_number = phone_number.to_s@pin = pin.to_s@cookies = decode_cookies(session_blob)+ @device_id = device_id.presence@device_info = nil@session_expires_at = Time.at(0)end@@ -36,6 +37,23 @@ class Provider::TradeRepublicSessionrequest(Net::HTTP::Get, path, body: body, headers: headers)end+ def self.expires_at(session_blob)+ new(phone_number: nil, pin: nil, session_blob: session_blob).expires_at+ end++ # A session ends when the tr_refresh JWT expires, 24 hours after login.+ # Refreshing renews only tr_session, never tr_refresh. The token is not+ # verified; the time is only used to show and plan around the expiry.+ def expires_at+ payload = @cookies["tr_refresh"].to_s.split(".")[1]+ return if payload.blank?++ claims = JSON.parse(Base64.urlsafe_decode64(payload))+ Time.zone.at(claims["exp"]) if claims.is_a?(Hash) && claims["exp"].is_a?(Integer)+ rescue ArgumentError, JSON::ParserError+ nil+ end+def cookies_blobJSON.generate(@cookies)end@@ -166,8 +184,10 @@ class Provider::TradeRepublicSession))end+ # A connection keeps its device identity when the container hostname+ # changes.def stable_device_id- configured = ENV["TRADE_REPUBLIC_DEVICE_ID"].presence+ configured = ENV["TRADE_REPUBLIC_DEVICE_ID"].presence || @device_idreturn Digest::SHA512.hexdigest(configured) if configuredDigest::SHA512.hexdigest([ Socket.gethostname, RUBY_PLATFORM, Etc.uname[:machine], Etc.uname[:sysname] ].join("|"))diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rbindex 06b05333dd..e525d24c2d 100644--- a/app/models/provider_connection_status.rb+++ b/app/models/provider_connection_status.rb@@ -119,13 +119,16 @@ class ProviderConnectionStatusdef item_statusreturn item.effective_status(latest_sync: latest_sync) if item.respond_to?(:setup_token_update_required?)+ # A session can end while the stored status is still good.+ return "requires_update" if item_boolean(:needs_login?)+item_value(:status)enddef item_requires_update?return item.setup_token_update_required?(latest_sync: latest_sync) if item.respond_to?(:setup_token_update_required?)- item_boolean(:requires_update?)+ item_boolean(:requires_update?) || item_boolean(:needs_login?)enddef pending_account_setup?diff --git a/app/models/trade_republic_item.rb b/app/models/trade_republic_item.rbindex 87a49ae702..5014b5718e 100644--- a/app/models/trade_republic_item.rb+++ b/app/models/trade_republic_item.rb@@ -22,10 +22,18 @@ class TradeRepublicItem < ApplicationRecordvalidates :phone_number, presence: true, unless: -> { requires_update? || session_configured? }scope :active, -> { where(scheduled_for_deletion: false) }- scope :syncable, -> { active.where(status: :good, pending_login_state: nil).where.not(session_blob: [ nil, "" ]) }+ # Matches ready_for_sync?: a session without a known end (stored before+ # session_expires_at existed) stays syncable until its next save sets one.+ scope :syncable, -> {+ active.where(status: :good, pending_login_state: nil).where.not(session_blob: [ nil, "" ])+ .where("trade_republic_items.session_expires_at IS NULL OR trade_republic_items.session_expires_at > ?", Time.current)+ }scope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }+ before_save :set_session_expires_at, if: -> { session_blob_changed? || (session_expires_at.nil? && session_configured?) }+ after_commit :schedule_sync_before_session_expires, if: -> { saved_change_to_session_expires_at? && session_expires_at.present? }+# Reloading represents a new persisted state; never carry an authentication# PIN across that boundary in the in-memory model instance.def reload(*)@@ -40,8 +48,16 @@ class TradeRepublicItem < ApplicationRecordsession_blob.present?end+ def session_expired?+ session_configured? && session_expires_at.present? && session_expires_at <= Time.current+ end++ def needs_login?+ requires_update? || session_expired?+ end+def ready_for_sync?- good? && pending_login_state.blank? && session_configured?+ good? && pending_login_state.blank? && session_configured? && !session_expired?enddef import_latest_data@@ -223,4 +239,14 @@ class TradeRepublicItem < ApplicationRecorddays: days}end++ private++ def set_session_expires_at+ self.session_expires_at = session_configured? ? Provider::TradeRepublicSession.expires_at(session_blob) : nil+ end++ def schedule_sync_before_session_expires+ TradeRepublicPreExpirySyncJob.schedule_for(self)+ endenddiff --git a/app/models/trade_republic_item/provided.rb b/app/models/trade_republic_item/provided.rbindex 4e006504fc..7acccfc949 100644--- a/app/models/trade_republic_item/provided.rb+++ b/app/models/trade_republic_item/provided.rb@@ -6,7 +6,8 @@ module TradeRepublicItem::ProvidedProvider::TradeRepublicClient.new(phone_number: phone_number,- pin: pin+ pin: pin,+ device_id: device_id)enddiff --git a/app/views/trade_republic_items/_trade_republic_item.html.erb b/app/views/trade_republic_items/_trade_republic_item.html.erbindex 0fa507d1f7..fb1631b88e 100644--- a/app/views/trade_republic_items/_trade_republic_item.html.erb+++ b/app/views/trade_republic_items/_trade_republic_item.html.erb@@ -23,7 +23,7 @@<%= icon "loader", size: "sm", class: "animate-spin" %><%= tag.span t(".syncing") %></div>- <% elsif trade_republic_item.requires_update? %>+ <% elsif trade_republic_item.needs_login? %><div class="text-warning flex items-center gap-1"><%= icon "alert-triangle", size: "sm", color: "warning" %><%= tag.span t(".requires_update") %>@@ -41,6 +41,9 @@<%= t(".never_synced") %><% end %></p>+ <% if trade_republic_item.ready_for_sync? && trade_republic_item.session_expires_at.present? %>+ <p class="text-secondary"><%= trade_republic_session_expiry("trade_republic_items.trade_republic_item.session_expires_in", trade_republic_item.session_expires_at) %></p>+ <% end %><% end %></div></div>@@ -51,7 +54,7 @@"refresh-cw",as_button: true,href: sync_trade_republic_item_path(trade_republic_item),- disabled: trade_republic_item.syncing?+ disabled: trade_republic_item.syncing? || !trade_republic_item.ready_for_sync?) %><%= render DS::Menu.new do |menu| %>@@ -80,6 +83,17 @@<% unless trade_republic_item.scheduled_for_deletion? %><div class="space-y-4 mt-4">+ <% if Current.user&.admin? && trade_republic_item.needs_login? %>+ <% login_stage = trade_republic_item.login_stage %>+ <% if trade_republic_item.pending_login_state.blank? || login_stage.in?(%w[qr_pending expired]) %>+ <%= render TradeRepublic::QrLoginComponent.new(+ item: trade_republic_item,+ return_url: accounts_path,+ active: login_stage == "qr_pending"+ ) %>+ <% end %>+ <% end %>+<% if visible_accounts.any? %><%= render "accounts/index/account_groups", accounts: visible_accounts %><% end %>diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.ymlindex 1171fde741..35f71afce4 100644--- a/config/locales/views/settings/ca.yml+++ b/config/locales/views/settings/ca.yml@@ -489,6 +489,8 @@ ca:one: Cal renovar el consentiment en %{count} diaother: Cal renovar el consentiment en %{count} diesreconsent_required: Cal renovar el consentiment+ login_required: "Cal iniciar sessió"+ login_expires_soon: "La sessió caduca d'aquí a %{time} (%{at})"sync_error: Error de sincronitzaciónot_authorized: No autoritzatnot_found: Proveïdor no trobat.@@ -667,9 +669,11 @@ ca:qr_cancel: Cancel·la l'inici de sessió amb QRqr_back_to_credentials: Torna al número de telèfon i PINqr_loading: Preparant el codi QR…- qr_instruction: Escaneja el codi QR amb l'aplicació de Trade Republic i aprova l'inici de sessió.+ qr_instruction: Escaneja el codi QR amb la càmera del telèfon i després aprova l'inici de sessió a l'aplicació de Trade Republic.qr_success: Inici de sessió aprovat. Sure està actualitzant la pàgina del proveïdor.qr_error: No s'ha pogut iniciar la sessió amb QR. Torna-ho a provar.+ requires_update: "Torna a iniciar sessió per reprendre la sincronització."+ session_expires_in: "La sessió caduca d'aquí a %{time} (%{at})."add_account: "Afegeix una altra connexió"save_configuration: Desa i inicia sessióupdate_configuration: Actualitza la configuraciódiff --git a/config/locales/views/settings/de.yml b/config/locales/views/settings/de.ymlindex 864f1e1c23..ea6a8c0860 100644--- a/config/locales/views/settings/de.yml+++ b/config/locales/views/settings/de.yml@@ -421,6 +421,8 @@ de:one: Erneute Zustimmung in 1 Tag nötigother: Erneute Zustimmung in %{count} Tagen nötigreconsent_required: Erneute Zustimmung nötig+ login_required: "Anmeldung erforderlich"+ login_expires_soon: "Anmeldung läuft in %{time} ab (%{at})"sync_error: Sync-Fehlernot_authorized: Nicht berechtigtnot_found: Anbieter nicht gefunden.@@ -548,9 +550,11 @@ de:qr_cancel: QR-Login abbrechenqr_back_to_credentials: Zurück zu Telefonnummer und PIN oder Passwortqr_loading: QR-Code wird vorbereitet …- qr_instruction: Scanne den QR-Code mit deiner Trade-Republic-App und bestätige die Anmeldung.+ qr_instruction: Scanne den QR-Code mit der Kamera deines Smartphones und bestätige die Anmeldung anschließend in der Trade-Republic-App.qr_success: Anmeldung bestätigt. Sure lädt die Provider-Übersicht neu.qr_error: Der QR-Login konnte nicht gestartet werden. Bitte versuche es erneut.+ requires_update: "Melde dich erneut an, um die Synchronisierung fortzusetzen."+ session_expires_in: "Anmeldung läuft in %{time} ab (%{at})."add_account: Weitere Verbindung hinzufügensave_configuration: Speichern und Login startenupdate_configuration: Konfiguration aktualisierendiff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 8cfdccaf7e..839706033f 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -441,6 +441,8 @@ en:sync_error: Sync errorno_recent_sync: Sync overduereconsent_required: Re-consent required+ login_required: Login required+ login_expires_soon: "Login expires in %{time} (%{at})"reconsent_needed:one: Re-consent needed in 1 dayother: Re-consent needed in %{count} days@@ -754,9 +756,11 @@ en:qr_cancel: Cancel QR loginqr_back_to_credentials: Back to phone number and PIN or passwordqr_loading: Preparing QR code …- qr_instruction: Scan the QR code with your Trade Republic app and approve the login.+ qr_instruction: Scan the QR code with your phone's camera, then approve the login in the Trade Republic app.qr_success: Login approved. Sure is refreshing the provider page.qr_error: QR login could not be started. Please try again.+ requires_update: Log in again to resume syncing.+ session_expires_in: "Login expires in %{time} (%{at})."add_account: Add another connectionsave_configuration: Save & Start Loginupdate_configuration: Update Configurationdiff --git a/config/locales/views/settings/es.yml b/config/locales/views/settings/es.ymlindex e889c2278b..15c2c8e923 100644--- a/config/locales/views/settings/es.yml+++ b/config/locales/views/settings/es.yml@@ -342,6 +342,8 @@ es:no_recent_sync: Sincronización pendienteregistration_needed: Registro necesarioreconsent_required: Se requiere renovar el consentimiento+ login_required: "Inicio de sesión requerido"+ login_expires_soon: "El inicio de sesión caduca en %{time} (%{at})"reconsent_needed:one: Renovar consentimiento en 1 díaother: Renovar consentimiento en %{count} díasdiff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.ymlindex 4c18e6a114..89934e2000 100644--- a/config/locales/views/settings/fr.yml+++ b/config/locales/views/settings/fr.yml@@ -478,6 +478,8 @@ fr:one: Consentement requis dans 1 jourother: Consentement requis dans %{count} joursreconsent_required: Consentement requis+ login_required: "Connexion requise"+ login_expires_soon: "La connexion expire dans %{time} (%{at})"sync_error: Erreur de synchronot_authorized: Non autorisénot_found: Fournisseur non trouvé.@@ -604,7 +606,9 @@ fr:qr_back_to_credentials: Revenir au numéro de téléphone et au code PIN ou mot de passeqr_cancel: Annuler la connexion par QR codeqr_error: La connexion par QR code n'a pas pu être lancée. Veuillez réessayer.- qr_instruction: Scannez le QR code avec votre application Trade Republic et approuvez la connexion.+ requires_update: "Reconnectez-vous pour reprendre la synchronisation."+ session_expires_in: "La connexion expire dans %{time} (%{at})."+ qr_instruction: Scannez le QR code avec l'appareil photo de votre téléphone, puis approuvez la connexion dans l'application Trade Republic.qr_loading: Préparation du QR code …qr_login: Se connecter avec un QR codeqr_success: Connexion approuvée. Sure actualise la page du fournisseur.diff --git a/config/locales/views/settings/hu.yml b/config/locales/views/settings/hu.ymlindex 72424b9cf9..82d24bda67 100644--- a/config/locales/views/settings/hu.yml+++ b/config/locales/views/settings/hu.yml@@ -263,6 +263,8 @@ hu:sync_error: Szinkronizálási hibano_recent_sync: Szinkronizálás lejártreconsent_required: Újrahozzájárulás szükséges+ login_required: "Bejelentkezés szükséges"+ login_expires_soon: "A bejelentkezés %{time} múlva lejár (%{at})"reconsent_needed:one: Újrahozzájárulás szükséges 1 napon belülother: Újrahozzájárulás szükséges %{count} napon belüldiff --git a/config/locales/views/settings/it.yml b/config/locales/views/settings/it.ymlindex 305a3bcf27..999980651c 100644--- a/config/locales/views/settings/it.yml+++ b/config/locales/views/settings/it.yml@@ -337,6 +337,8 @@ it:no_recent_sync: Sincronizzazione in ritardoregistration_needed: Registrazione richiestareconsent_required: Nuovo consenso richiesto+ login_required: "Accesso richiesto"+ login_expires_soon: "L'accesso scade tra %{time} (%{at})"reconsent_needed:one: Nuovo consenso richiesto tra 1 giornoother: Nuovo consenso richiesto tra %{count} giornidiff --git a/config/locales/views/settings/pl.yml b/config/locales/views/settings/pl.ymlindex 3b7010808b..f12a0963c6 100644--- a/config/locales/views/settings/pl.yml+++ b/config/locales/views/settings/pl.yml@@ -596,6 +596,8 @@ pl:one: Wymagana ponowna zgoda za 1 dzieńother: Wymagana ponowna zgoda za %{count} dnireconsent_required: Wymagana ponowna zgoda+ login_required: "Wymagane logowanie"+ login_expires_soon: "Logowanie wygasa za %{time} (%{at})"sync_error: Błąd synchronizacjimonobank_panel:step_1_html: Przejdź do %{link}, zaloguj się aplikacją Monobank i wygeneruj@@ -757,7 +759,9 @@ pl:qr_back_to_credentials: Wróć do numeru telefonu i PIN-u lub hasłaqr_cancel: Anuluj logowanie kodem QRqr_error: Nie udało się rozpocząć logowania kodem QR. Spróbuj ponownie.- qr_instruction: Zeskanuj kod QR aplikacją Trade Republic i zatwierdź logowanie.+ requires_update: "Zaloguj się ponownie, aby wznowić synchronizację."+ session_expires_in: "Logowanie wygasa za %{time} (%{at})."+ qr_instruction: Zeskanuj kod QR aparatem telefonu, a następnie zatwierdź logowanie w aplikacji Trade Republic.qr_loading: Przygotowywanie kodu QR…qr_login: Zaloguj się kodem QRqr_success: Logowanie zatwierdzone. Sure odświeża stronę dostawcy.diff --git a/config/locales/views/settings/pt-PT.yml b/config/locales/views/settings/pt-PT.ymlindex c2ba771cd7..589220222d 100644--- a/config/locales/views/settings/pt-PT.yml+++ b/config/locales/views/settings/pt-PT.yml@@ -404,6 +404,8 @@ pt-PT:sync_error: Erro de sincronizaçãono_recent_sync: Sincronização em atrasoreconsent_required: Necessário novo consentimento+ login_required: "Início de sessão necessário"+ login_expires_soon: "A sessão expira dentro de %{time} (%{at})"reconsent_needed:one: Necessário novo consentimento em 1 diaother: Necessário novo consentimento em %{count} diasdiff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.ymlindex 1a5376976c..65d8e7342a 100644--- a/config/locales/views/settings/ru.yml+++ b/config/locales/views/settings/ru.yml@@ -532,6 +532,8 @@ ru:one: Повторное согласие требуется через %{count} деньother: Повторное согласие требуется через %{count} дняreconsent_required: Требуется повторное согласие+ login_required: "Требуется вход"+ login_expires_soon: "Вход истекает через %{time} (%{at})"sync_error: Ошибка синхронизацииnot_authorized: Не авторизованnot_found: Провайдер не найден.@@ -701,9 +703,11 @@ ru:qr_cancel: Отменить вход по QR-кодуqr_back_to_credentials: Вернуться к номеру телефона и PIN-коду или паролюqr_loading: Подготовка QR-кода…- qr_instruction: Отсканируйте QR-код в приложении Trade Republic и подтвердите вход.+ qr_instruction: Отсканируйте QR-код камерой телефона, затем подтвердите вход в приложении Trade Republic.qr_success: Вход подтверждён. Sure обновляет страницу провайдера.qr_error: Не удалось начать вход по QR-коду. Пожалуйста, попробуйте снова.+ requires_update: "Войдите снова, чтобы возобновить синхронизацию."+ session_expires_in: "Вход истекает через %{time} (%{at})."add_account: "Добавить ещё одно подключение"save_configuration: Сохранить и войтиupdate_configuration: Обновить конфигурациюdiff --git a/config/locales/views/settings/tr.yml b/config/locales/views/settings/tr.ymlindex 9d757c9fd7..fbc033b63b 100644--- a/config/locales/views/settings/tr.yml+++ b/config/locales/views/settings/tr.yml@@ -537,6 +537,8 @@ tr:one: "%{count} gün içinde yeniden onay gerekiyor"other: "%{count} gün içinde yeniden onay gerekiyor"reconsent_required: Yeniden onay gerekiyor+ login_required: "Giriş gerekli"+ login_expires_soon: "Girişin süresi %{time} içinde doluyor (%{at})"registration_needed: Kayıt gerekiyorsync_error: Senkronizasyon hatasınot_authorized: Yetkiniz yok@@ -713,9 +715,11 @@ tr:qr_cancel: QR girişini iptal etqr_back_to_credentials: Telefon numarası ve PIN'e veya şifreye dönqr_loading: QR kod hazırlanıyor …- qr_instruction: QR kodu Trade Republic uygulamanızla tarayın ve girişi onaylayın.+ qr_instruction: QR kodu telefonunuzun kamerasıyla tarayın, ardından girişi Trade Republic uygulamasında onaylayın.qr_success: Giriş onaylandı. Sure sağlayıcı sayfasını yeniliyor.qr_error: QR girişi başlatılamadı. Lütfen tekrar deneyin.+ requires_update: "Senkronizasyona devam etmek için yeniden giriş yapın."+ session_expires_in: "Girişin süresi %{time} içinde doluyor (%{at})."add_account: "Başka bir bağlantı ekle"save_configuration: Kaydet ve Girişi Başlatupdate_configuration: Yapılandırmayı Güncellediff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.ymlindex dc488adb9c..d18c667416 100644--- a/config/locales/views/settings/uk.yml+++ b/config/locales/views/settings/uk.yml@@ -425,6 +425,8 @@ uk:no_recent_sync: Синхронізація простроченаregistration_needed: Потрібна реєстраціяreconsent_required: Потрібна повторна згода+ login_required: "Потрібен вхід"+ login_expires_soon: "Вхід завершиться через %{time} (%{at})"reconsent_needed:one: Повторна згода потрібна через %{count} деньother: Повторна згода потрібна через %{count} днів@@ -742,9 +744,11 @@ uk:qr_cancel: Скасувати вхід за QR-кодомqr_back_to_credentials: Назад до номера телефону та PIN-коду або пароляqr_loading: Підготовка QR-коду…- qr_instruction: Відскануйте QR-код у застосунку Trade Republic і підтвердьте вхід.+ qr_instruction: Відскануйте QR-код камерою телефона, а потім підтвердьте вхід у застосунку Trade Republic.qr_success: Вхід підтверджено. Sure оновлює сторінку постачальника.qr_error: Не вдалося розпочати вхід за QR-кодом. Спробуйте ще раз.+ requires_update: "Увійдіть знову, щоб відновити синхронізацію."+ session_expires_in: "Вхід завершиться через %{time} (%{at})."add_account: "Додати ще одне підключення"save_configuration: Зберегти й увійтиupdate_configuration: Оновити конфігураціюdiff --git a/config/locales/views/settings/vi.yml b/config/locales/views/settings/vi.ymlindex 145b239a0c..22bb71e102 100644--- a/config/locales/views/settings/vi.yml+++ b/config/locales/views/settings/vi.yml@@ -305,6 +305,8 @@ vi:sync_error: Lỗi đồng bộno_recent_sync: Đồng bộ quá hạnreconsent_required: Cần đồng ý lại+ login_required: "Cần đăng nhập"+ login_expires_soon: "Phiên đăng nhập hết hạn sau %{time} (%{at})"reconsent_needed:one: Cần đồng ý lại sau 1 ngàyother: Cần đồng ý lại sau %{count} ngàydiff --git a/config/locales/views/settings/zh-CN.yml b/config/locales/views/settings/zh-CN.ymlindex 75f40780de..73cb873bfe 100644--- a/config/locales/views/settings/zh-CN.yml+++ b/config/locales/views/settings/zh-CN.yml@@ -305,6 +305,8 @@ zh-CN:sync_error: 同步错误no_recent_sync: 同步已逾期reconsent_required: 需要重新授权+ login_required: "需要登录"+ login_expires_soon: "登录将在 %{time}后过期(%{at})"reconsent_needed:one: 1 天后需要重新授权other: "%{count} 天后需要重新授权"diff --git a/config/locales/views/settings/zh-TW.yml b/config/locales/views/settings/zh-TW.ymlindex 7599df4cff..b322478d32 100644--- a/config/locales/views/settings/zh-TW.yml+++ b/config/locales/views/settings/zh-TW.yml@@ -385,6 +385,8 @@ zh-TW:sync_error: 同步錯誤no_recent_sync: 同步逾期reconsent_required: 需要重新授權+ login_required: "需要登入"+ login_expires_soon: "登入將在 %{time}後過期(%{at})"reconsent_needed:one: 1 天後需要重新授權other: '%{count} 天後需要重新授權'diff --git a/config/locales/views/trade_republic_items/ca.yml b/config/locales/views/trade_republic_items/ca.ymlindex b7eb6d6fbb..ee7ea4a233 100644--- a/config/locales/views/trade_republic_items/ca.yml+++ b/config/locales/views/trade_republic_items/ca.yml@@ -15,6 +15,7 @@ ca:trade_republic_item:syncing: "S'està sincronitzant"requires_update: "Cal tornar a autenticar-se"+ session_expires_in: "La sessió caduca d'aquí a %{time} (%{at})."error: "Error"synced: "Sincronitzat fa %{time}. %{summary}."setup_accounts: "Configura els comptes"diff --git a/config/locales/views/trade_republic_items/de.yml b/config/locales/views/trade_republic_items/de.ymlindex 0de927cb2d..669d7d9be8 100644--- a/config/locales/views/trade_republic_items/de.yml+++ b/config/locales/views/trade_republic_items/de.yml@@ -17,6 +17,7 @@ de:trade_republic_item:syncing: "Wird synchronisiert"requires_update: "Erneute Authentifizierung erforderlich"+ session_expires_in: "Anmeldung läuft in %{time} ab (%{at})."error: "Fehler"synced: "Vor %{time} synchronisiert. %{summary}."setup_accounts: "Konten einrichten"diff --git a/config/locales/views/trade_republic_items/en.yml b/config/locales/views/trade_republic_items/en.ymlindex 5fcd2e9ea1..653e9b60ff 100644--- a/config/locales/views/trade_republic_items/en.yml+++ b/config/locales/views/trade_republic_items/en.yml@@ -18,6 +18,7 @@ en:deletion_in_progress: Deletion in progresssyncing: Syncingrequires_update: Re-authentication required+ session_expires_in: "Login expires in %{time} (%{at})."error: Errorsynced: Synced %{time} ago. %{summary}.never_synced: Never synced.diff --git a/config/locales/views/trade_republic_items/es.yml b/config/locales/views/trade_republic_items/es.ymlindex 01dab56c03..08f849bdd7 100644--- a/config/locales/views/trade_republic_items/es.yml+++ b/config/locales/views/trade_republic_items/es.yml@@ -15,6 +15,7 @@ es:trade_republic_item:syncing: "Sincronizando"requires_update: "Se requiere volver a autenticarse"+ session_expires_in: "El inicio de sesión caduca en %{time} (%{at})."error: "Error"synced: "Sincronizado hace %{time}. %{summary}."setup_accounts: "Configurar cuentas"diff --git a/config/locales/views/trade_republic_items/fr.yml b/config/locales/views/trade_republic_items/fr.ymlindex 0a99bcae88..c6f59f65ff 100644--- a/config/locales/views/trade_republic_items/fr.yml+++ b/config/locales/views/trade_republic_items/fr.yml@@ -40,6 +40,7 @@ fr:never_synced: Jamais synchronisé.syncing: "Synchronisation en cours"requires_update: "Réauthentification requise"+ session_expires_in: "La connexion expire dans %{time} (%{at})."error: "Erreur"synced: "Synchronisé il y a %{time}. %{summary}."setup_accounts: "Configurer les comptes"diff --git a/config/locales/views/trade_republic_items/hu.yml b/config/locales/views/trade_republic_items/hu.ymlindex d52df263d9..1dd685da98 100644--- a/config/locales/views/trade_republic_items/hu.yml+++ b/config/locales/views/trade_republic_items/hu.yml@@ -15,6 +15,7 @@ hu:trade_republic_item:syncing: "Szinkronizálás"requires_update: "Újrahitelesítés szükséges"+ session_expires_in: "A bejelentkezés %{time} múlva lejár (%{at})."error: "Hiba"synced: "Szinkronizálva: %{time}. %{summary}."setup_accounts: "Fiókok beállítása"diff --git a/config/locales/views/trade_republic_items/it.yml b/config/locales/views/trade_republic_items/it.ymlindex 1c092ed8f4..83cbead0c4 100644--- a/config/locales/views/trade_republic_items/it.yml+++ b/config/locales/views/trade_republic_items/it.yml@@ -15,6 +15,7 @@ it:trade_republic_item:syncing: "Sincronizzazione"requires_update: "Nuova autenticazione richiesta"+ session_expires_in: "L'accesso scade tra %{time} (%{at})."error: "Errore"synced: "Sincronizzato %{time} fa. %{summary}."setup_accounts: "Configura i conti"diff --git a/config/locales/views/trade_republic_items/nb.yml b/config/locales/views/trade_republic_items/nb.ymlindex 433cb80f0c..c6b35cee0a 100644--- a/config/locales/views/trade_republic_items/nb.yml+++ b/config/locales/views/trade_republic_items/nb.yml@@ -15,6 +15,7 @@ nb:trade_republic_item:syncing: "Synkroniserer"requires_update: "Ny autentisering kreves"+ session_expires_in: "Påloggingen utløper om %{time} (%{at})."error: "Feil"synced: "Synkronisert for %{time} siden. %{summary}."setup_accounts: "Konfigurer kontoer"diff --git a/config/locales/views/trade_republic_items/nl.yml b/config/locales/views/trade_republic_items/nl.ymlindex b3d8491326..ec999cbe37 100644--- a/config/locales/views/trade_republic_items/nl.yml+++ b/config/locales/views/trade_republic_items/nl.yml@@ -15,6 +15,7 @@ nl:trade_republic_item:syncing: "Bezig met synchroniseren"requires_update: "Opnieuw authenticeren vereist"+ session_expires_in: "Login verloopt over %{time} (%{at})."error: "Fout"synced: "Gesynchroniseerd %{time} geleden. %{summary}."setup_accounts: "Rekeningen instellen"diff --git a/config/locales/views/trade_republic_items/pl.yml b/config/locales/views/trade_republic_items/pl.ymlindex b54bcb3c15..a8fd3bc0cb 100644--- a/config/locales/views/trade_republic_items/pl.yml+++ b/config/locales/views/trade_republic_items/pl.yml@@ -209,6 +209,7 @@ pl:no_accounts_discovered_description: Zakończ logowanie i uruchom synchronizację,aby wykryć rachunek.requires_update: Wymagana ponowna autoryzacja+ session_expires_in: "Logowanie wygasa za %{time} (%{at})."setup_accounts: Skonfiguruj rachunkisynced: Zsynchronizowano %{time} temu. %{summary}.syncing: Synchronizowaniediff --git a/config/locales/views/trade_republic_items/pt-BR.yml b/config/locales/views/trade_republic_items/pt-BR.ymlindex 195eca70b1..83cc0a7724 100644--- a/config/locales/views/trade_republic_items/pt-BR.yml+++ b/config/locales/views/trade_republic_items/pt-BR.yml@@ -15,6 +15,7 @@ pt-BR:trade_republic_item:syncing: "Sincronizando"requires_update: "É necessário reautenticar"+ session_expires_in: "O login expira em %{time} (%{at})."error: "Erro"synced: "Sincronizado há %{time}. %{summary}."setup_accounts: "Configurar contas"diff --git a/config/locales/views/trade_republic_items/ro.yml b/config/locales/views/trade_republic_items/ro.ymlindex a2c4e0ec5e..bf894cd74d 100644--- a/config/locales/views/trade_republic_items/ro.yml+++ b/config/locales/views/trade_republic_items/ro.yml@@ -15,6 +15,7 @@ ro:trade_republic_item:syncing: "Se sincronizează"requires_update: "Este necesară reautentificarea"+ session_expires_in: "Autentificarea expiră în %{time} (%{at})."error: "Eroare"synced: "Sincronizat acum %{time}. %{summary}."setup_accounts: "Configurează conturile"diff --git a/config/locales/views/trade_republic_items/ru.yml b/config/locales/views/trade_republic_items/ru.ymlindex 8c50486cca..a5c3464367 100644--- a/config/locales/views/trade_republic_items/ru.yml+++ b/config/locales/views/trade_republic_items/ru.yml@@ -14,6 +14,7 @@ ru:trade_republic_item:syncing: "Синхронизация"requires_update: "Требуется повторная аутентификация"+ session_expires_in: "Вход истекает через %{time} (%{at})."error: "Ошибка"synced: "Синхронизировано %{time} назад. %{summary}."setup_accounts: "Настроить счета"diff --git a/config/locales/views/trade_republic_items/tr.yml b/config/locales/views/trade_republic_items/tr.ymlindex 2da28b148c..e0cf29de04 100644--- a/config/locales/views/trade_republic_items/tr.yml+++ b/config/locales/views/trade_republic_items/tr.yml@@ -14,6 +14,7 @@ tr:trade_republic_item:syncing: "Senkronize ediliyor"requires_update: "Yeniden kimlik doğrulama gerekli"+ session_expires_in: "Girişin süresi %{time} içinde doluyor (%{at})."error: "Hata"synced: "%{time} önce senkronize edildi. %{summary}."setup_accounts: "Hesapları kur"diff --git a/config/locales/views/trade_republic_items/uk.yml b/config/locales/views/trade_republic_items/uk.ymlindex f517ae7651..c9ec0819df 100644--- a/config/locales/views/trade_republic_items/uk.yml+++ b/config/locales/views/trade_republic_items/uk.yml@@ -14,6 +14,7 @@ uk:trade_republic_item:syncing: "Синхронізація"requires_update: "Потрібна повторна автентифікація"+ session_expires_in: "Вхід завершиться через %{time} (%{at})."error: "Помилка"synced: "Синхронізовано %{time} тому. %{summary}."setup_accounts: "Налаштувати рахунки"diff --git a/config/locales/views/trade_republic_items/vi.yml b/config/locales/views/trade_republic_items/vi.ymlindex fea32f34bb..2e0b5b3b34 100644--- a/config/locales/views/trade_republic_items/vi.yml+++ b/config/locales/views/trade_republic_items/vi.yml@@ -15,6 +15,7 @@ vi:trade_republic_item:syncing: "Đang đồng bộ"requires_update: "Cần xác thực lại"+ session_expires_in: "Phiên đăng nhập hết hạn sau %{time} (%{at})."error: "Lỗi"synced: "Đã đồng bộ %{time} trước. %{summary}."setup_accounts: "Thiết lập tài khoản"diff --git a/config/locales/views/trade_republic_items/zh-CN.yml b/config/locales/views/trade_republic_items/zh-CN.ymlindex c38f1b0796..1f82fc657b 100644--- a/config/locales/views/trade_republic_items/zh-CN.yml+++ b/config/locales/views/trade_republic_items/zh-CN.yml@@ -15,6 +15,7 @@ zh-CN:trade_republic_item:syncing: "正在同步"requires_update: "需要重新认证"+ session_expires_in: "登录将在 %{time}后过期(%{at})。"error: "错误"synced: "%{time}前同步。%{summary}。"setup_accounts: "设置账户"diff --git a/config/locales/views/trade_republic_items/zh-TW.yml b/config/locales/views/trade_republic_items/zh-TW.ymlindex 1cd10851cc..f898ae5327 100644--- a/config/locales/views/trade_republic_items/zh-TW.yml+++ b/config/locales/views/trade_republic_items/zh-TW.yml@@ -15,6 +15,7 @@ zh-TW:trade_republic_item:syncing: "正在同步"requires_update: "需要重新驗證"+ session_expires_in: "登入將在 %{time}後過期(%{at})。"error: "錯誤"synced: "%{time}前同步。%{summary}。"setup_accounts: "設定帳戶"diff --git a/db/migrate/20261013180000_add_device_id_to_trade_republic_items.rb b/db/migrate/20261013180000_add_device_id_to_trade_republic_items.rbnew file mode 100644index 0000000000..e4cac6315c--- /dev/null+++ b/db/migrate/20261013180000_add_device_id_to_trade_republic_items.rb@@ -0,0 +1,6 @@+class AddDeviceIdToTradeRepublicItems < ActiveRecord::Migration[8.1]+ def change+ # A volatile default gives every existing row its own device ID.+ add_column :trade_republic_items, :device_id, :uuid, default: -> { "gen_random_uuid()" }, null: false+ end+enddiff --git a/db/migrate/20261015090000_add_session_expires_at_to_trade_republic_items.rb b/db/migrate/20261015090000_add_session_expires_at_to_trade_republic_items.rbnew file mode 100644index 0000000000..0d48705f6b--- /dev/null+++ b/db/migrate/20261015090000_add_session_expires_at_to_trade_republic_items.rb@@ -0,0 +1,5 @@+class AddSessionExpiresAtToTradeRepublicItems < ActiveRecord::Migration[8.1]+ def change+ add_column :trade_republic_items, :session_expires_at, :datetime+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex b71bab726a..a0823baae4 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) do+ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -2683,6 +2683,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) dot.string "brokerage_account_id"t.datetime "created_at", null: falset.string "currency"+ t.uuid "device_id", default: -> { "gen_random_uuid()" }, null: falset.uuid "family_id", null: falset.string "name"t.string "newest_event_id"@@ -2691,6 +2692,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) dot.string "phone_number"t.boolean "scheduled_for_deletion", default: false, null: falset.text "session_blob"+ t.datetime "session_expires_at"t.string "status", default: "good", null: falset.jsonb "timeline_cursors", default: {}, null: falset.datetime "updated_at", null: falsediff --git a/test/components/trade_republic/account_editor_component_test.rb b/test/components/trade_republic/account_editor_component_test.rbindex 2a0c51bc0e..3f0ecd6049 100644--- a/test/components/trade_republic/account_editor_component_test.rb+++ b/test/components/trade_republic/account_editor_component_test.rb@@ -1,6 +1,8 @@require "test_helper"class TradeRepublic::AccountEditorComponentTest < ViewComponent::TestCase+ include TradeRepublicSessionTestHelper+# The account fixtures ship unlinked (no account_providers rows); pairing# each with a Sure account puts an item into the fully set up state.def link_all_accounts(item)@@ -171,4 +173,34 @@ class TradeRepublic::AccountEditorComponentTest < ViewComponent::TestCaseassert_selector "input[name='trade_republic_item[phone_number]'][value='+491701234567']"end++ test "a connected card shows when its login expires" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 5.hours.from_now))++ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: families(:dylan_family)))++ assert_text I18n.t("settings.providers.trade_republic_panel.session_expires_in", time: "about 5 hours", at: I18n.l(item.session_expires_at, format: :short))+ end++ test "a card whose session expired asks to log in again" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))++ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: families(:dylan_family)))++ assert_selector "p.text-destructive", text: I18n.t("settings.providers.trade_republic_panel.requires_update")+ assert_no_text I18n.t("settings.providers.trade_republic_panel.status_configured_prefix")+ end++ test "a card whose QR login lapsed can start a QR login again" do+ item = trade_republic_items(:requires_update_item)+ item.update!(pending_login_state: "lapsed-qr")+ item.stubs(:login_stage).returns("expired")++ render_inline(TradeRepublic::ConnectionCardComponent.new(item: item))++ assert_text I18n.t("settings.providers.trade_republic_panel.login_expired")+ assert_button I18n.t("settings.providers.trade_republic_panel.qr_login")+ endenddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 8b6fc804a5..01456273fd 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -4,6 +4,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestinclude ActionView::RecordIdentifierinclude OnchainTestHelperinclude EntriesTestHelper+ include TradeRepublicSessionTestHelpersetup dosign_in @user = users(:family_admin)@@ -377,6 +378,31 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_includes response.body, titleend+ test "index offers a QR login on a Trade Republic connection that needs one" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))++ get accounts_url++ assert_response :success+ assert_select "##{dom_id(item)} [data-trade-republic-qr-initiate-url-value='#{initiate_qr_login_trade_republic_item_path(item)}']"+ assert_select "##{dom_id(item)} [data-trade-republic-qr-return-url-value='#{accounts_path}']"+ # Until then a sync can only fail.+ assert_select "##{dom_id(item)} form[action='#{sync_trade_republic_item_path(item)}'] button[disabled]"+ end++ test "index shows when a Trade Republic login expires" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 5.hours.from_now))++ get accounts_url++ assert_response :success+ assert_includes response.body, I18n.t("trade_republic_items.trade_republic_item.session_expires_in",+ time: "about 5 hours", at: I18n.l(item.reload.session_expires_at, format: :short))+ assert_select "##{dom_id(item)} [data-controller='trade-republic-qr']", count: 0+ end+test "index renders trading212 items" dotrading212_item = trading212_items(:configured_item)get accounts_urldiff --git a/test/controllers/trade_republic_items_controller_test.rb b/test/controllers/trade_republic_items_controller_test.rbindex f5726c7611..995a74f647 100644--- a/test/controllers/trade_republic_items_controller_test.rb+++ b/test/controllers/trade_republic_items_controller_test.rb@@ -80,6 +80,28 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTestassert_equal existing_item.session_blob, existing_item.reload.session_blobend+ test "a connection whose session ended is not synced" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)++ assert_no_difference "Sync.count" do+ post sync_trade_republic_item_url(item), headers: { "Referer" => accounts_url }+ end++ assert_redirected_to accounts_url+ end++ test "sync from the panel says nothing started for a connection whose session ended" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)++ post sync_trade_republic_item_url(item, source: "panel"), as: :turbo_stream++ assert_turbo_stream action: "replace", target: TradeRepublic::ConnectionCardComponent.dom_id_for(item)+ assert_not_includes response.body, I18n.t("settings.providers.sync_provider_in_progress")+ assert_select "form[action='#{sync_trade_republic_item_path(item, source: "panel")}'] button[disabled]"+ end+test "Trade Republic PIN is filtered from logs" doparameter_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)filtered_params = parameter_filter.filter(@@ -112,6 +134,19 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTestassert_equal original_session_blob, item.session_blobend+ test "update keeps the phone number when it is left blank" do+ item = trade_republic_items(:requires_update_item)+ provider = mock+ provider.expects(:initiate_login).returns(+ Provider::TradeRepublicClient::Result.new(data: { "status" => "verification_required", "pending_login_b64" => "pending" })+ )+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)++ patch trade_republic_item_url(item), params: { trade_republic_item: { phone_number: "", pin: "1234" } }++ assert_equal "+491709876543", item.reload.phone_number+ end+test "initiate login does not destroy a working session when the PIN is missing" doitem = trade_republic_items(:configured_item)original_session_blob = item.session_blob@@ -155,6 +190,39 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTestassert_not_nil provider_account.current_accountend+ test "complete account setup after the session ended leaves the sync for the next login" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)++ assert_no_difference "Sync.count" do+ post complete_account_setup_trade_republic_item_url(item), params: { account_ids: [ trade_republic_accounts(:main_account).id ] }+ end++ assert_not_nil trade_republic_accounts(:main_account).reload.current_account+ end++ test "linking an existing account after the session ended leaves the sync for the next login" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)+ account = families(:dylan_family).accounts.create!(name: "Manual brokerage", balance: 0, currency: "EUR", accountable: Investment.new)++ assert_no_difference "Sync.count" do+ post link_existing_account_trade_republic_items_url, params: { account_id: account.id, trade_republic_account_id: trade_republic_accounts(:main_account).id }+ end++ assert_equal account, trade_republic_accounts(:main_account).reload.current_account+ end++ test "opening account setup after the session ended starts no sync" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)+ item.trade_republic_accounts.destroy_all++ assert_no_difference "Sync.count" do+ get setup_accounts_trade_republic_item_url(item)+ end+ end+test "complete account setup creates a Crypto exchange account for the Crypto account" doitem = trade_republic_items(:configured_item)provider_account = item.trade_republic_accounts.create!(diff --git a/test/helpers/settings_helper_test.rb b/test/helpers/settings_helper_test.rbindex 8e60e61092..0161866981 100644--- a/test/helpers/settings_helper_test.rb+++ b/test/helpers/settings_helper_test.rb@@ -3,6 +3,9 @@require "test_helper"class SettingsHelperTest < ActionView::TestCase+ # Views get every helper; the Trade Republic summary uses its expiry helper.+ include TradeRepublicHelper+test "provider_summary for snaptrade is off when family has no snaptrade items" do@snaptrade_items = []@@ -62,4 +65,52 @@ class SettingsHelperTest < ActionView::TestCaseassert_empty offend++ test "provider_summary for trade_republic asks for a new login once a session has expired" do+ @trade_republic_items = [ TradeRepublicItem.new(session_blob: "session", session_expires_at: 1.minute.ago) ]+ @provider_sync_health = {}++ summary = provider_summary("trade_republic")++ assert_equal :warn, summary[:status]+ assert_equal I18n.t("settings.providers.meta.login_required"), summary[:meta]+ end++ test "provider_summary for trade_republic asks for a new login after a failed last sync" do+ @trade_republic_items = [ TradeRepublicItem.new(session_blob: "session", session_expires_at: 1.minute.ago) ]+ @provider_sync_health = { "trade_republic" => { error: true } }++ summary = provider_summary("trade_republic")++ assert_equal :warn, summary[:status]+ assert_equal I18n.t("settings.providers.meta.login_required"), summary[:meta]+ end++ test "provider_summary for trade_republic reports a failed sync while the login is valid" do+ @trade_republic_items = [ TradeRepublicItem.new(session_blob: "session", session_expires_at: 5.hours.from_now) ]+ @provider_sync_health = { "trade_republic" => { error: true } }++ summary = provider_summary("trade_republic")++ assert_equal :err, summary[:status]+ assert_equal I18n.t("settings.providers.meta.sync_error"), summary[:meta]+ end++ test "provider_summary for trade_republic warns shortly before a login expires" do+ expires_at = 90.minutes.from_now+ @trade_republic_items = [ TradeRepublicItem.new(session_blob: "session", session_expires_at: expires_at) ]+ @provider_sync_health = {}++ summary = provider_summary("trade_republic")++ assert_equal :warn, summary[:status]+ assert_equal I18n.t("settings.providers.meta.login_expires_soon", time: "about 2 hours", at: I18n.l(expires_at, format: :short)), summary[:meta]+ end++ test "provider_summary for trade_republic reports sync-based status while the login is valid" do+ @trade_republic_items = [ TradeRepublicItem.new(session_blob: "session", session_expires_at: 5.hours.from_now) ]+ @provider_sync_health = {}++ assert_equal({ status: :ok, last_synced_at: nil }, provider_summary("trade_republic"))+ endenddiff --git a/test/helpers/trade_republic_helper_test.rb b/test/helpers/trade_republic_helper_test.rbnew file mode 100644index 0000000000..b40d3f5c75--- /dev/null+++ b/test/helpers/trade_republic_helper_test.rb@@ -0,0 +1,35 @@+require "test_helper"++class TradeRepublicHelperTest < ActionView::TestCase+ KEY = "settings.providers.trade_republic_panel.session_expires_in".freeze++ test "the expiry shows how long the login lasts and when it ends" do+ expires_at = 5.hours.from_now++ assert_equal "Login expires in about 5 hours (#{I18n.l(expires_at, format: :short)}).",+ trade_republic_session_expiry(KEY, expires_at)+ end++ test "the expiry is written in the language of the sentence" do+ I18n.backend.store_translations(:nl, settings: { providers: { trade_republic_panel: { session_expires_in: "Login verloopt over %{time} (%{at})." } } })+ expires_at = 5.hours.from_now++ text = I18n.with_locale(:nl) { trade_republic_session_expiry(KEY, expires_at) }++ assert_equal "Login verloopt over ongeveer 5 uur (#{I18n.l(expires_at, format: :short, locale: :nl)}).", text+ ensure+ I18n.reload!+ end++ test "an untranslated sentence keeps its time words in English" do+ expires_at = 5.hours.from_now+ key = "settings.providers.trade_republic_panel.only_in_english_for_this_test"+ I18n.backend.store_translations(:en, settings: { providers: { trade_republic_panel: { only_in_english_for_this_test: "Login expires in %{time} (%{at})." } } })++ text = I18n.with_locale(:nl) { trade_republic_session_expiry(key, expires_at) }++ assert_equal "Login expires in about 5 hours (#{I18n.l(expires_at, format: :short, locale: :en)}).", text+ ensure+ I18n.reload!+ end+enddiff --git a/test/jobs/trade_republic_pre_expiry_sync_job_test.rb b/test/jobs/trade_republic_pre_expiry_sync_job_test.rbnew file mode 100644index 0000000000..c6e2f7c746--- /dev/null+++ b/test/jobs/trade_republic_pre_expiry_sync_job_test.rb@@ -0,0 +1,35 @@+require "test_helper"++class TradeRepublicPreExpirySyncJobTest < ActiveJob::TestCase+ include TradeRepublicSessionTestHelper++ setup do+ @item = trade_republic_items(:configured_item)+ @item.update!(session_blob: trade_republic_session_blob(expires_at: 30.minutes.from_now))+ end++ test "syncs while the session it was planned for is still valid" do+ @item.expects(:sync_later).once++ TradeRepublicPreExpirySyncJob.perform_now(@item, session_expires_at: @item.session_expires_at.to_i)+ end++ test "leaves the sync to the newer login once the session was replaced" do+ @item.expects(:sync_later).never++ TradeRepublicPreExpirySyncJob.perform_now(@item, session_expires_at: 1.hour.ago.to_i)+ end++ test "does not sync a connection that needs a new login" do+ @item.update!(status: :requires_update)+ @item.expects(:sync_later).never++ TradeRepublicPreExpirySyncJob.perform_now(@item, session_expires_at: @item.session_expires_at.to_i)+ end++ test "plans nothing when the sync time has already passed" do+ assert_no_enqueued_jobs only: TradeRepublicPreExpirySyncJob do+ TradeRepublicPreExpirySyncJob.schedule_for(@item)+ end+ end+enddiff --git a/test/models/provider_connection_status_test.rb b/test/models/provider_connection_status_test.rbindex b5449793a9..f247f7ae7e 100644--- a/test/models/provider_connection_status_test.rb+++ b/test/models/provider_connection_status_test.rb@@ -127,4 +127,21 @@ class ProviderConnectionStatusTest < ActiveSupport::TestCaseassert_equal true, status[:pending_account_setup]assert_equal "17 synced, 1 need setup", status.dig(:sync, :status_summary)end++ test "trade republic provider status requires an update once its session ended" do+ item = trade_republic_items(:configured_item)+ item.update_columns(status: "good", session_expires_at: 1.minute.ago)+ provider = ProviderConnectionStatus::PROVIDERS.find { |entry| entry[:association] == :trade_republic_items }++ status = ProviderConnectionStatus.new(provider, item, syncing: false).to_h++ assert_equal "requires_update", status[:status]+ assert_equal true, status[:requires_update]++ item.update_columns(session_expires_at: 1.hour.from_now)+ status = ProviderConnectionStatus.new(provider, item.reload, syncing: false).to_h++ assert_equal "good", status[:status]+ assert_equal false, status[:requires_update]+ endenddiff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rbindex ebedf62912..5cb76f8c56 100644--- a/test/models/trade_republic_client_test.rb+++ b/test/models/trade_republic_client_test.rb@@ -659,6 +659,13 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseassert_equal "qr_pending", @client.login_stage(pending_login_b64: encoded)end+ test "an abandoned QR login is expired once its challenge lapsed" do+ pending = { "challenge_id" => "challenge-1", "session_blob" => "session=1", "expires_at" => 1.minute.ago.iso8601 }+ encoded = Base64.strict_encode64(JSON.generate(pending))++ assert_raises(Provider::TradeRepublicClient::LoginExpired) { @client.login_stage(pending_login_b64: encoded) }+ end+test "rotates the QR payload and token expiry while polling" doresponse_class = Struct.new(:code, :body) dodef is_a?(klass)@@ -2795,6 +2802,26 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseevents.map { |event| event.dig("detail", "instrument_name") }end+ test "a WAF rejection of the account request is not an expired session" do+ session = mock+ session.expects(:get).with("/api/v2/auth/account").returns(waf_rejection)+ @client.define_singleton_method(:new_session) { |**| session }++ assert_raises(Provider::TradeRepublicClient::WafRequired) do+ @client.sync(session_txt: '{"tr_session":"s"}')+ end+ end++ test "a rejected account request without an error object is an expired session" do+ [ "null", "[]" ].each do |body|+ session = mock+ session.expects(:get).with("/api/v2/auth/account").returns(rejection("403", body))+ @client.define_singleton_method(:new_session) { |**| session }++ assert_equal "session_expired", @client.sync(session_txt: '{"tr_session":"s"}').data["status"]+ end+ end+private# Same shape as bond_purchase_detail, in English, as Sure receives it.@@ -2948,4 +2975,19 @@ class TradeRepublicClientTest < ActiveSupport::TestCaseendendend++ def waf_rejection+ rejection("403", { "errorCode" => "WAF_TOKEN_REQUIRED" }.to_json)+ end++ def rejection(code, body)+ response_class = Struct.new(:code, :body) do+ def is_a?(klass)+ klass == Net::HTTPSuccess ? false : super+ end++ def [](_header) = nil+ end+ response_class.new(code, body)+ endenddiff --git a/test/models/trade_republic_item_syncer_test.rb b/test/models/trade_republic_item_syncer_test.rbindex 8fa2cb9210..1da5233c23 100644--- a/test/models/trade_republic_item_syncer_test.rb+++ b/test/models/trade_republic_item_syncer_test.rb@@ -1,7 +1,7 @@require "test_helper"class TradeRepublicItemSyncerTest < ActiveSupport::TestCase- include ActiveJob::TestHelper+ include ActiveJob::TestHelper, TradeRepublicSessionTestHelpersetup do@item = trade_republic_items(:configured_item)@@ -89,6 +89,18 @@ class TradeRepublicItemSyncerTest < ActiveSupport::TestCaseassert_equal 2, sync.reload.sync_stats["tr_timeline_backfills"]end+ test "an expired session asks for a new login without contacting Trade Republic" do+ @item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))+ sync = Sync.create!(syncable: @item)+ @item.expects(:import_latest_data).never++ assert_raises(Provider::TradeRepublicClient::AuthenticationRequired) do+ TradeRepublicItem::Syncer.new(@item).perform_sync(sync)+ end++ assert @item.reload.requires_update?+ end+privatedef client_result(data)diff --git a/test/models/trade_republic_item_test.rb b/test/models/trade_republic_item_test.rbindex fdb7a8c004..15af541030 100644--- a/test/models/trade_republic_item_test.rb+++ b/test/models/trade_republic_item_test.rb@@ -1,6 +1,8 @@require "test_helper"class TradeRepublicItemTest < ActiveSupport::TestCase+ include TradeRepublicSessionTestHelper, ActiveJob::TestHelper+test "database enforces one account of each kind per item" doitem = trade_republic_items(:configured_item)@@ -56,6 +58,18 @@ class TradeRepublicItemTest < ActiveSupport::TestCaseassert_not_includes TradeRepublicItem.syncable, itemend+ test "syncable scope excludes an ended session but keeps one without a known end" do+ item = trade_republic_items(:configured_item)+ item.update_columns(session_expires_at: 1.minute.ago)+ assert_not_includes TradeRepublicItem.syncable, item++ item.update_columns(session_expires_at: nil)+ assert_includes TradeRepublicItem.syncable, item++ item.update_columns(session_expires_at: 1.hour.from_now)+ assert_includes TradeRepublicItem.syncable, item+ end+test "session_configured? reflects stored session" doassert_predicate trade_republic_items(:configured_item), :session_configured?assert_not_predicate trade_republic_items(:no_session_item), :session_configured?@@ -221,4 +235,55 @@ class TradeRepublicItemTest < ActiveSupport::TestCaseassert_equal %w[portfolio cash], processed_kindsend++ test "gives each connection its own device ID" do+ assert_not_equal trade_republic_items(:configured_item).device_id, trade_republic_items(:requires_update_item).device_id+ end++ test "a new connection logs in with its device ID right away" do+ item = TradeRepublicItem.create!(family: families(:dylan_family), phone_number: "+491700000000")++ assert item.device_id.present?+ Provider::TradeRepublicClient.expects(:new).with(has_entry(device_id: item.device_id))+ item.trade_republic_provider(pin: "1234")+ end++ test "a new session records when it expires and plans a sync before then" do+ item = trade_republic_items(:configured_item)+ expires_at = 23.hours.from_now.change(usec: 0)++ assert_enqueued_with job: TradeRepublicPreExpirySyncJob, at: expires_at - TradeRepublicPreExpirySyncJob::LEAD_TIME do+ item.update!(session_blob: trade_republic_session_blob(expires_at: expires_at))+ end+ assert_equal expires_at, item.reload.session_expires_at+ end++ test "a refreshed session with the same expiry plans no extra sync" do+ item = trade_republic_items(:configured_item)+ expires_at = 23.hours.from_now.change(usec: 0)+ item.update!(session_blob: trade_republic_session_blob(expires_at: expires_at))++ assert_no_enqueued_jobs only: TradeRepublicPreExpirySyncJob do+ item.update!(session_blob: trade_republic_session_blob(expires_at: expires_at).sub("session", "renewed"))+ end+ end++ test "an expired session needs a new login" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))++ assert item.good?+ assert item.session_expired?+ assert item.needs_login?+ assert_not item.ready_for_sync?+ end++ test "clearing the session forgets its expiry" do+ item = trade_republic_items(:configured_item)+ item.update!(session_blob: trade_republic_session_blob(expires_at: 5.hours.from_now))++ item.update!(session_blob: nil, status: :requires_update)++ assert_nil item.reload.session_expires_at+ endenddiff --git a/test/models/trade_republic_session_test.rb b/test/models/trade_republic_session_test.rbindex 8c11c99977..721a2621f9 100644--- a/test/models/trade_republic_session_test.rb+++ b/test/models/trade_republic_session_test.rb@@ -1,6 +1,8 @@require "test_helper"class TradeRepublicSessionTest < ActiveSupport::TestCase+ include TradeRepublicSessionTestHelper+test "builds a desktop device fingerprint with a current browser version" dosession = Provider::TradeRepublicSession.new(phone_number: "+491701234567", pin: "1234")headers = session.login_headers@@ -23,4 +25,28 @@ class TradeRepublicSessionTest < ActiveSupport::TestCaseassert_equal first_device.fetch("stableDeviceId"), second_device.fetch("stableDeviceId")end++ test "derives the device identity from the connection's device ID" do+ first = Provider::TradeRepublicSession.new(phone_number: "+491701234567", pin: "1234", device_id: "device-a")+ second = Provider::TradeRepublicSession.new(phone_number: "+491701234567", pin: "1234", device_id: "device-b")++ first_device = JSON.parse(Base64.strict_decode64(first.login_headers.fetch("X-TR-Device-Info")))+ second_device = JSON.parse(Base64.strict_decode64(second.login_headers.fetch("X-TR-Device-Info")))++ assert_equal Digest::SHA512.hexdigest("device-a"), first_device.fetch("stableDeviceId")+ assert_not_equal first_device.fetch("stableDeviceId"), second_device.fetch("stableDeviceId")+ end++ test "reads the session expiry from the tr_refresh token" do+ expires_at = Time.zone.parse("2026-10-16 20:45:58")++ assert_equal expires_at, Provider::TradeRepublicSession.expires_at(trade_republic_session_blob(expires_at: expires_at))+ end++ test "has no session expiry without a readable tr_refresh token" do+ assert_nil Provider::TradeRepublicSession.expires_at(nil)+ assert_nil Provider::TradeRepublicSession.expires_at(trade_republic_items(:configured_item).session_blob)+ assert_nil Provider::TradeRepublicSession.expires_at(JSON.generate("tr_refresh" => "not-a-jwt"))+ assert_nil Provider::TradeRepublicSession.expires_at(JSON.generate("tr_refresh" => "a.#{Base64.urlsafe_encode64("[]")}.c"))+ endenddiff --git a/test/support/trade_republic_session_test_helper.rb b/test/support/trade_republic_session_test_helper.rbnew file mode 100644index 0000000000..1eba7b7684--- /dev/null+++ b/test/support/trade_republic_session_test_helper.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true++# A stored Trade Republic session whose tr_refresh JWT expires at the given+# time. The header and signature are placeholders; Sure only reads the exp.+module TradeRepublicSessionTestHelper+ def trade_republic_session_blob(expires_at:)+ payload = Base64.urlsafe_encode64(JSON.generate(exp: expires_at.to_i), padding: false)+ JSON.generate("tr_session" => "session", "tr_refresh" => "header.#{payload}.signature")+ end+enddiff --git a/test/system/settings/providers_test.rb b/test/system/settings/providers_test.rbindex 4a64307700..c5940f2352 100644--- a/test/system/settings/providers_test.rb+++ b/test/system/settings/providers_test.rb@@ -143,6 +143,9 @@ class Settings::ProvidersTest < ApplicationSystemTestCasetest "connected providers are grouped under Your connections in alphabetical title order" doSimplefinItem.create!(family: @family, name: "Test SimpleFIN", access_url: "https://bridge.simplefin.org/simplefin/access")+ # A connection that needs attention is listed first, so keep the Trade+ # Republic one logged in and let only the alphabetical order count.+ trade_republic_items(:requires_update_item).update!(status: :good)visit settings_providers_pathdiff --git a/test/system/trade_republic_qr_login_test.rb b/test/system/trade_republic_qr_login_test.rbnew file mode 100644index 0000000000..a6c836459d--- /dev/null+++ b/test/system/trade_republic_qr_login_test.rb@@ -0,0 +1,98 @@+require "application_system_test_case"++class TradeRepublicQrLoginTest < ApplicationSystemTestCase+ include TradeRepublicSessionTestHelper++ setup do+ sign_in users(:family_admin)+ @item = trade_republic_items(:configured_item)+ @item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))++ pending = Provider::TradeRepublicClient::Result.new(data: {+ "status" => "pending",+ "pending_login_b64" => "pending",+ "qr_code_payload" => "https://example.com/qr"+ })+ Provider::TradeRepublicClient.any_instance.stubs(:initiate_qr_login).returns(pending)+ Provider::TradeRepublicClient.any_instance.stubs(:poll_qr_login).returns(pending)+ end++ test "a QR login on Accounts can be cancelled and started again" do+ visit accounts_path++ within card do+ click_on qr_login+ assert_selector ".qrcode svg"+ assert_button qr_cancel++ click_on qr_cancel+ # The button is enabled again only once the server confirmed the cancel.+ assert_button qr_login+ assert_no_selector ".qrcode svg"+ end+ assert_nil @item.reload.pending_login_state++ within card do+ click_on qr_login+ assert_selector ".qrcode svg"+ assert_button qr_cancel+ end+ end++ test "cancelling a QR login while it is still starting leaves no login behind" do+ pending = Provider::TradeRepublicClient::Result.new(data: { "status" => "pending", "pending_login_b64" => "pending" })+ # Trade Republic answers slowly, so the cancel is sent while the login starts.+ Provider::TradeRepublicClient.any_instance.stubs(:initiate_qr_login).with { sleep 1.5 }.returns(pending)++ visit accounts_path++ within card do+ click_on qr_login+ click_on qr_cancel+ assert_button qr_login, disabled: false, wait: 10+ end+ # Give a start that was not waited for the time to store its login.+ sleep 2+ assert_nil @item.reload.pending_login_state+ end++ test "cancelling a QR login that was already running when the page loaded" do+ @item.update!(pending_login_state: "pending", status: :requires_update)+ Provider::TradeRepublicClient.any_instance.stubs(:login_stage).returns("qr_pending")++ visit accounts_path++ within card do+ assert_selector ".qrcode svg"+ click_on qr_cancel+ assert_button qr_login+ assert_no_selector ".qrcode svg"+ end+ assert_nil @item.reload.pending_login_state+ end++ test "cancelling a running QR login in Settings brings back the credentials form" do+ @item.update!(pending_login_state: "pending", status: :requires_update)+ Provider::TradeRepublicClient.any_instance.stubs(:login_stage).returns("qr_pending")++ visit settings_providers_path+ find("summary", text: "Trade Republic").click++ within "##{TradeRepublic::ConnectionCardComponent.dom_id_for(@item)}" do+ assert_no_field "trade_republic_item[phone_number]"+ click_on qr_cancel+ assert_field "trade_republic_item[phone_number]"+ assert_button qr_login+ end+ assert_nil @item.reload.pending_login_state+ end++ private++ def card+ "##{ActionView::RecordIdentifier.dom_id(@item)}"+ end++ def qr_login = I18n.t("settings.providers.trade_republic_panel.qr_login")+ def qr_cancel = I18n.t("settings.providers.trade_republic_panel.qr_cancel")+end