Skip to content

armgit / sure

Public Imported from GitHub
0

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.rb
index 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.erb
index 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.erb
new file mode 100644
index 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.rb
new file mode 100644
index 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
+end
diff --git a/app/controllers/trade_republic_items_controller.rb b/app/controllers/trade_republic_items_controller.rb
index 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 < ApplicationController
def update
attrs = 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 < ApplicationController
end
def 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 queued
if 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))
end
respond_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_failed
redirect_to account_path(account), notice: t(".success"), alert: t(".processing_failed"), status: :see_other
else
@@ -434,7 +440,7 @@ class TradeRepublicItemsController < ApplicationController
latest_sync = @trade_republic_item.syncs.ordered.first
should_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_later
end
@@ -504,7 +510,8 @@ class TradeRepublicItemsController < ApplicationController
end
@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.rb
index cb765cb198..9e392d76b7 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -120,7 +120,7 @@ module SettingsHelper
sync_based_summary(key)
when "trade_republic"
return { status: :off } unless @trade_republic_items&.any?
- sync_based_summary(key)
+ trade_republic_summary
when "indexa_capital"
return { status: :off } unless @indexa_capital_items&.any?
sync_based_summary(key)
@@ -278,6 +278,27 @@ module SettingsHelper
end
end
+ # 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?
end
diff --git a/app/helpers/trade_republic_helper.rb b/app/helpers/trade_republic_helper.rb
new file mode 100644
index 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
+end
diff --git a/app/javascript/controllers/trade_republic_qr_controller.js b/app/javascript/controllers/trade_republic_qr_controller.js
index 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.rb
new file mode 100644
index 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
+end
diff --git a/app/models/provider/trade_republic_client.rb b/app/models/provider/trade_republic_client.rb
index 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::TradeRepublicClient
attr_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_id
end
def initiate_login
@@ -346,7 +347,11 @@ class Provider::TradeRepublicClient
end
def 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"
+ end
pending = decode_pending(pending_login_b64)
if pending["required_action"] == "AUTHENTICATOR_VERIFICATION" && !pending["authenticator_verified"]
@@ -380,7 +385,9 @@ class Provider::TradeRepublicClient
def 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" })
+ end
raise_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::TradeRepublicClient
end
def 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/)
end
def require_pin!
@@ -757,7 +768,7 @@ class Provider::TradeRepublicClient
def 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"
end
raise_login_error(response) if login
@@ -799,6 +810,8 @@ class Provider::TradeRepublicClient
def response_error_code(response)
body = parse_json(response)
+ return unless body.is_a?(Hash)
+
body["errorCode"].presence || body.dig("errors", 0, "errorCode").presence
rescue MalformedResponse
nil
diff --git a/app/models/provider/trade_republic_session.rb b/app/models/provider/trade_republic_session.rb
index 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::TradeRepublicSession
attr_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::TradeRepublicSession
request(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_blob
JSON.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_id
return Digest::SHA512.hexdigest(configured) if configured
Digest::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.rb
index 06b05333dd..e525d24c2d 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -119,13 +119,16 @@ class ProviderConnectionStatus
def item_status
return 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)
end
def 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?)
end
def pending_account_setup?
diff --git a/app/models/trade_republic_item.rb b/app/models/trade_republic_item.rb
index 87a49ae702..5014b5718e 100644
--- a/app/models/trade_republic_item.rb
+++ b/app/models/trade_republic_item.rb
@@ -22,10 +22,18 @@ class TradeRepublicItem < ApplicationRecord
validates :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 < ApplicationRecord
session_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?
end
def import_latest_data
@@ -223,4 +239,14 @@ class TradeRepublicItem < ApplicationRecord
days: 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)
+ end
end
diff --git a/app/models/trade_republic_item/provided.rb b/app/models/trade_republic_item/provided.rb
index 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::Provided
Provider::TradeRepublicClient.new(
phone_number: phone_number,
- pin: pin
+ pin: pin,
+ device_id: device_id
)
end
diff --git a/app/views/trade_republic_items/_trade_republic_item.html.erb b/app/views/trade_republic_items/_trade_republic_item.html.erb
index 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.yml
index 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} dia
other: Cal renovar el consentiment en %{count} dies
reconsent_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 autoritzat
not_found: Proveïdor no trobat.
@@ -667,9 +669,11 @@ ca:
qr_cancel: Cancel·la l'inici de sessió amb QR
qr_back_to_credentials: Torna al número de telèfon i PIN
qr_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.yml
index 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ötig
other: Erneute Zustimmung in %{count} Tagen nötig
reconsent_required: Erneute Zustimmung nötig
+ login_required: "Anmeldung erforderlich"
+ login_expires_soon: "Anmeldung läuft in %{time} ab (%{at})"
sync_error: Sync-Fehler
not_authorized: Nicht berechtigt
not_found: Anbieter nicht gefunden.
@@ -548,9 +550,11 @@ de:
qr_cancel: QR-Login abbrechen
qr_back_to_credentials: Zurück zu Telefonnummer und PIN oder Passwort
qr_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ügen
save_configuration: Speichern und Login starten
update_configuration: Konfiguration aktualisieren
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 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 error
no_recent_sync: Sync overdue
reconsent_required: Re-consent required
+ login_required: Login required
+ login_expires_soon: "Login expires in %{time} (%{at})"
reconsent_needed:
one: Re-consent needed in 1 day
other: Re-consent needed in %{count} days
@@ -754,9 +756,11 @@ en:
qr_cancel: Cancel QR login
qr_back_to_credentials: Back to phone number and PIN or password
qr_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 connection
save_configuration: Save & Start Login
update_configuration: Update Configuration
diff --git a/config/locales/views/settings/es.yml b/config/locales/views/settings/es.yml
index 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 pendiente
registration_needed: Registro necesario
reconsent_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ía
other: Renovar consentimiento en %{count} días
diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.yml
index 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 jour
other: Consentement requis dans %{count} jours
reconsent_required: Consentement requis
+ login_required: "Connexion requise"
+ login_expires_soon: "La connexion expire dans %{time} (%{at})"
sync_error: Erreur de synchro
not_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 passe
qr_cancel: Annuler la connexion par QR code
qr_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 code
qr_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.yml
index 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 hiba
no_recent_sync: Szinkronizálás lejárt
reconsent_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ül
other: Újrahozzájárulás szükséges %{count} napon belül
diff --git a/config/locales/views/settings/it.yml b/config/locales/views/settings/it.yml
index 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 ritardo
registration_needed: Registrazione richiesta
reconsent_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 giorno
other: Nuovo consenso richiesto tra %{count} giorni
diff --git a/config/locales/views/settings/pl.yml b/config/locales/views/settings/pl.yml
index 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} dni
reconsent_required: Wymagana ponowna zgoda
+ login_required: "Wymagane logowanie"
+ login_expires_soon: "Logowanie wygasa za %{time} (%{at})"
sync_error: Błąd synchronizacji
monobank_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ła
qr_cancel: Anuluj logowanie kodem QR
qr_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 QR
qr_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.yml
index 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ção
no_recent_sync: Sincronização em atraso
reconsent_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 dia
other: Necessário novo consentimento em %{count} dias
diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.yml
index 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.yml
index 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 gerekiyor
sync_error: Senkronizasyon hatası
not_authorized: Yetkiniz yok
@@ -713,9 +715,11 @@ tr:
qr_cancel: QR girişini iptal et
qr_back_to_credentials: Telefon numarası ve PIN'e veya şifreye dön
qr_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şlat
update_configuration: Yapılandırmayı Güncelle
diff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.yml
index 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.yml
index 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ạn
reconsent_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ày
other: Cần đồng ý lại sau %{count} ngày
diff --git a/config/locales/views/settings/zh-CN.yml b/config/locales/views/settings/zh-CN.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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 progress
syncing: Syncing
requires_update: Re-authentication required
+ session_expires_in: "Login expires in %{time} (%{at})."
error: Error
synced: 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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 rachunki
synced: Zsynchronizowano %{time} temu. %{summary}.
syncing: Synchronizowanie
diff --git a/config/locales/views/trade_republic_items/pt-BR.yml b/config/locales/views/trade_republic_items/pt-BR.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.yml
index 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.rb
new file mode 100644
index 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
+end
diff --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.rb
new file mode 100644
index 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
+end
diff --git a/db/schema.rb b/db/schema.rb
index 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 database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -2683,6 +2683,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) do
t.string "brokerage_account_id"
t.datetime "created_at", null: false
t.string "currency"
+ t.uuid "device_id", default: -> { "gen_random_uuid()" }, null: false
t.uuid "family_id", null: false
t.string "name"
t.string "newest_event_id"
@@ -2691,6 +2692,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) do
t.string "phone_number"
t.boolean "scheduled_for_deletion", default: false, null: false
t.text "session_blob"
+ t.datetime "session_expires_at"
t.string "status", default: "good", null: false
t.jsonb "timeline_cursors", default: {}, null: false
t.datetime "updated_at", null: false
diff --git a/test/components/trade_republic/account_editor_component_test.rb b/test/components/trade_republic/account_editor_component_test.rb
index 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::TestCase
assert_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")
+ end
end
diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rb
index 8b6fc804a5..01456273fd 100644
--- a/test/controllers/accounts_controller_test.rb
+++ b/test/controllers/accounts_controller_test.rb
@@ -4,6 +4,7 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
include ActionView::RecordIdentifier
include OnchainTestHelper
include EntriesTestHelper
+ include TradeRepublicSessionTestHelper
setup do
sign_in @user = users(:family_admin)
@@ -377,6 +378,31 @@ class AccountsControllerTest < ActionDispatch::IntegrationTest
assert_includes response.body, title
end
+ 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" do
trading212_item = trading212_items(:configured_item)
get accounts_url
diff --git a/test/controllers/trade_republic_items_controller_test.rb b/test/controllers/trade_republic_items_controller_test.rb
index 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::IntegrationTest
assert_equal existing_item.session_blob, existing_item.reload.session_blob
end
+ 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" do
parameter_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)
filtered_params = parameter_filter.filter(
@@ -112,6 +134,19 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTest
assert_equal original_session_blob, item.session_blob
end
+ 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" do
item = trade_republic_items(:configured_item)
original_session_blob = item.session_blob
@@ -155,6 +190,39 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTest
assert_not_nil provider_account.current_account
end
+ 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" do
item = 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.rb
index 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::TestCase
assert_empty off
end
+
+ 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"))
+ end
end
diff --git a/test/helpers/trade_republic_helper_test.rb b/test/helpers/trade_republic_helper_test.rb
new file mode 100644
index 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
+end
diff --git a/test/jobs/trade_republic_pre_expiry_sync_job_test.rb b/test/jobs/trade_republic_pre_expiry_sync_job_test.rb
new file mode 100644
index 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
+end
diff --git a/test/models/provider_connection_status_test.rb b/test/models/provider_connection_status_test.rb
index 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::TestCase
assert_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]
+ end
end
diff --git a/test/models/trade_republic_client_test.rb b/test/models/trade_republic_client_test.rb
index 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::TestCase
assert_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" do
response_class = Struct.new(:code, :body) do
def is_a?(klass)
@@ -2795,6 +2802,26 @@ class TradeRepublicClientTest < ActiveSupport::TestCase
events.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::TestCase
end
end
end
+
+ 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)
+ end
end
diff --git a/test/models/trade_republic_item_syncer_test.rb b/test/models/trade_republic_item_syncer_test.rb
index 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, TradeRepublicSessionTestHelper
setup do
@item = trade_republic_items(:configured_item)
@@ -89,6 +89,18 @@ class TradeRepublicItemSyncerTest < ActiveSupport::TestCase
assert_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
+
private
def client_result(data)
diff --git a/test/models/trade_republic_item_test.rb b/test/models/trade_republic_item_test.rb
index 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" do
item = trade_republic_items(:configured_item)
@@ -56,6 +58,18 @@ class TradeRepublicItemTest < ActiveSupport::TestCase
assert_not_includes TradeRepublicItem.syncable, item
end
+ 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" do
assert_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::TestCase
assert_equal %w[portfolio cash], processed_kinds
end
+
+ 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
+ end
end
diff --git a/test/models/trade_republic_session_test.rb b/test/models/trade_republic_session_test.rb
index 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" do
session = Provider::TradeRepublicSession.new(phone_number: "+491701234567", pin: "1234")
headers = session.login_headers
@@ -23,4 +25,28 @@ class TradeRepublicSessionTest < ActiveSupport::TestCase
assert_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"))
+ end
end
diff --git a/test/support/trade_republic_session_test_helper.rb b/test/support/trade_republic_session_test_helper.rb
new file mode 100644
index 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
+end
diff --git a/test/system/settings/providers_test.rb b/test/system/settings/providers_test.rb
index 4a64307700..c5940f2352 100644
--- a/test/system/settings/providers_test.rb
+++ b/test/system/settings/providers_test.rb
@@ -143,6 +143,9 @@ class Settings::ProvidersTest < ApplicationSystemTestCase
test "connected providers are grouped under Your connections in alphabetical title order" do
SimplefinItem.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_path
diff --git a/test/system/trade_republic_qr_login_test.rb b/test/system/trade_republic_qr_login_test.rb
new file mode 100644
index 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