Files
sure/app/views/snaptrade_items/setup_accounts.html.erb
T
Juan José MataandClaude Opus 5 d6462f5fc9 feat(snaptrade): add device-flow OAuth alongside the browser redirect (#3126)
* feat(snaptrade): add device-flow OAuth alongside the browser redirect

SnapTrade could only be connected through the authorization-code + PKCE
flow, which needs a confidential OAuth client: SNAPTRADE_OAUTH_CLIENT_SECRET
and a redirect URI registered on the OAuth app. A deployment that cannot
register one had no path at all.

Add the device grant (RFC 8628) as a second way to obtain the same token,
so people can pick the flow that suits their deployment. Both grants end at
SnaptradeItem#apply_oauth_tokens!, so a device-authorized item is
indistinguishable from a redirect-authorized one from there on -- same
Bearer data calls, refresh, revocation and sync. Nothing about existing
authorized items changes: no schema change, no migration, and the PKCE path
is untouched.

- Provider::Snaptrade gains start_device_authorization and poll_device_token,
  with endpoints read from SnapTrade's OAuth metadata document (cached).
- oauth_configured? now means "some flow is available" (public client id),
  which is what gates syncing and the provider panel; the new
  authorization_code_configured? gates the redirect flow specifically.
- Token and revocation requests authenticate as a public client when no
  secret is configured -- client_id in the body instead of HTTP Basic.
  Without this a device-authorized item would authorize fine and then fail
  at its first token rotation.
- The settings panel offers both when both are available; every other entry
  point picks one through SnaptradeItemsHelper#snaptrade_authorize_path.
- The device page carries a failed attempt's code back into the form, so
  "not confirmed yet" is a retry rather than a restart.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): keep the provider panel's setup-step keys and cover both flows

Two test_unit failures from the panel change.

The setup steps were reordered and their keys renamed, which orphaned the
translations twelve locales already had for them and broke the test asserting
`oauth_setup_step_3`. The rename bought nothing: reword the steps in place
instead, leaving the callback URL on step 2 where the interpolation lives.

The panel tests stubbed `oauth_configured?`, which no longer decides which
buttons render -- that is now `authorization_code_configured?`. Stub both, so
the "configured" cases test the deployment they name, and add the device-only
case that was previously unreachable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): address device-flow review findings

Two real bugs from the bot reviews, plus consistency work.

The completion form posts into the `drawer` frame so errors re-render in place,
but a successful redirect was then followed as a frame navigation. Both
destinations carry the layout's empty `drawer` frame, so Turbo swapped that in
and merely closed the dialog: the notice was lost and `return_to=setup_accounts`
never advanced. Success now breaks out with a redirect stream action, the same
mechanism holdings and categorizes already use, while errors keep rendering in
the drawer.

RFC 8628 §3.1 requires a confidential client to authenticate its device
authorization request, and the panel offers the device code on deployments that
configured a secret. That request now carries the same client authentication as
the token request.

Token endpoint resolution is now shared by all three grants, since whatever
issued a token has to be what refreshes it. It reads the discovery document only
when already cached and never fetches it, so the browser flow keeps working off
the constant it has always used -- no new network call on refresh and no new way
for an existing authorized item to fail.

Also: the drawer no longer asks the provider whether it is configured, the
controller tells it; and the test helpers restore the previous OAuth config
rather than clearing it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): reject a device authorization response that cannot drive the flow

A 2xx missing device_code, user_code or a verification URI was passed straight
to the drawer, which then rendered a blank code and a link to nowhere -- a dead
end the user could only abandon. Every one of those fields is load-bearing, and
a response without them is partial or schema-changed, so fail with a message
instead. Same reasoning as the results-array check in get_positions.

verification_uri_complete substitutes for verification_uri when present, since
the drawer prefers it for the link anyway.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): filter device-flow codes from request logs

complete_oauth_device_flow receives the device code as a request parameter,
and none of the existing filter_parameters patterns is a substring of
"device_code" -- ParameterFilter matches on substrings, and "token", "_key",
"secret", "code_verifier" and "code_challenge" all miss it. So Rails' default
"Processing by ... Parameters: {...}" line was writing it in plaintext.

That matters more here than ordinary log hygiene: the device code is the only
capability check on redemption. Unlike the redirect flow's state, nothing binds
a device code to the family that requested it, so anyone who can read the logs
could redeem another family's in-flight authorization into their own item and
pick up a token for that family's brokerage data.

Adds :device_code, :user_code and :verification_uri_complete (which embeds the
user code) to the filter list, with a regression test in the style of the
existing Sophtron credential-filtering test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): bind a pending device authorization to its session

The device code was posted back from the drawer as a form field, so the
request body was the only thing deciding which item a pending authorization
redeemed into. Nothing tied a code to the family that asked for it -- the
guarantee `state` gives the redirect flow -- so a code recovered from
anywhere could be redeemed into an item belonging to someone else, handing
them a token for the victim's brokerage data.

Hold the pending authorization in the session instead, where oauth_callback
already keeps its code_verifier and state:

- start_oauth_device_flow records the code, what the page displays, the
  family, the item and the return_to context under :snaptrade_device_flow.
- complete_oauth_device_flow reads the code from there and refuses unless
  the flow was started by this session for this family and this item. A
  device_code parameter is no longer read at all, so there is no longer a
  way to inject one.
- return_to and accountable_type come from the session too, so completion
  needs nothing from the form to find its way back.

The code now never reaches the browser, which also makes the previous
commit's log filtering a second line of defence rather than the only one.

A failed attempt keeps the code only while it is still redeemable: expired_token
and access_denied clear it so the page offers a fresh start, while a transient
failure leaves it in place to retry. expires_in and interval are no longer
carried anywhere, since nothing ever read them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

* fix(snaptrade): use one token endpoint for every grant

poll_device_token resolved the token endpoint from the cached discovery
document while exchange_code and refresh_tokens used TOKEN_URL, so which
URL a device-issued token was refreshed at depended on whether the 12h
metadata cache was still warm. If the discovered endpoint ever differed
from the constant, a device-authorized item would work until the cache
lapsed and then fail its first rotation -- and fail invisibly, since a
refresh failure marks the connection requires_update.

Resolve it by removing the choice rather than by making refresh depend on
discovery. RFC 8628 §3.4 redeems a device code at the authorization
server's token endpoint, the same one the authorization code grant uses:
there is one token endpoint, not one per grant, and nothing to keep in
sync between issuing a token and refreshing it. TOKEN_URL is also the
endpoint the browser flow has been using in production, so it is the one
with evidence behind it. Discovery is still consulted, but only for
device_authorization_endpoint, which has no hardcoded equivalent.

This also keeps refresh free of any network dependency it did not already
have: reintroducing discovery there would have put a fetch, with retries
and backoff, in front of every token rotation on items that never needed
one.

Also restore the previous OAuth configuration in the missing-client-id
test instead of leaving the client id nil, which made it order-dependent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3f2UyefTKJrgvNjPnhMRk

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-25 04:28:25 +02:00

256 lines
13 KiB
ERB

<% content_for :title, t("snaptrade_items.setup_accounts.title", default: "Set Up SnapTrade Accounts") %>
<%= render DS::Dialog.new(disable_click_outside: true) do |dialog| %>
<% dialog.with_header(title: t("snaptrade_items.setup_accounts.header", default: "Set Up Your SnapTrade Accounts")) do %>
<div class="flex items-center gap-2">
<%= icon "trending-up", class: "text-primary" %>
<span class="text-primary"><%= t("snaptrade_items.setup_accounts.subtitle", default: "Select which brokerage accounts to link") %></span>
</div>
<% end %>
<% dialog.with_body do %>
<div class="space-y-6">
<%# Always show the info box %>
<div class="bg-surface border border-primary p-4 rounded-lg">
<div class="flex items-start gap-3">
<%= icon "info", size: "sm", class: "text-primary mt-0.5 flex-shrink-0" %>
<div>
<p class="text-sm text-primary mb-2">
<strong><%= t("snaptrade_items.setup_accounts.info_title", default: "SnapTrade Investment Data") %></strong>
</p>
<ul class="text-xs text-secondary space-y-1 list-disc list-inside">
<li><%= t("snaptrade_items.setup_accounts.info_holdings", default: "Holdings with current prices and quantities") %></li>
<li><%= t("snaptrade_items.setup_accounts.info_cost_basis", default: "Cost basis per position (when available)") %></li>
<li><%= t("snaptrade_items.setup_accounts.info_activities", default: "Trade history with activity labels (Buy, Sell, Dividend, etc.)") %></li>
<li><%= t("snaptrade_items.setup_accounts.info_history", default: "Up to 3 years of transaction history") %></li>
</ul>
<p class="text-xs text-warning mt-2">
<%= icon "alert-triangle", size: "xs", class: "inline-block mr-1" %>
<%= t("snaptrade_items.setup_accounts.free_tier_note", default: "SnapTrade free tier allows 20 brokerage connections.") %>
</p>
</div>
</div>
</div>
<% if @waiting_for_sync %>
<%# Syncing state - show spinner with manual refresh option %>
<div id="snaptrade-sync-spinner" class="flex flex-col items-center justify-center py-6 space-y-3">
<div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
<p class="text-secondary text-center">
<%= t("snaptrade_items.setup_accounts.loading", default: "Fetching accounts from SnapTrade...") %>
</p>
<p class="text-xs text-secondary text-center">
<%= t("snaptrade_items.setup_accounts.loading_hint", default: "Click Refresh to check for accounts.") %>
</p>
</div>
<div class="flex gap-3 justify-center">
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.refresh", default: "Refresh"),
variant: "secondary",
icon: "refresh-cw",
href: setup_accounts_snaptrade_item_path(@snaptrade_item),
frame: "_top"
) %>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.cancel_button", default: "Cancel"),
variant: "ghost",
href: accounts_path,
frame: "_top"
) %>
</div>
<% elsif @no_accounts_found %>
<%# No accounts found after sync completed %>
<div class="no-accounts-found flex flex-col items-center justify-center py-6 space-y-3">
<%= icon "alert-circle", size: "lg", class: "text-warning" %>
<p class="text-primary text-center font-medium">
<%= t("snaptrade_items.setup_accounts.no_accounts_title", default: "No Accounts Found") %>
</p>
<p class="text-secondary text-center text-sm">
<%= t("snaptrade_items.setup_accounts.no_accounts_message", default: "No brokerage accounts were found. This can happen if you cancelled the connection or if your brokerage isn't supported.") %>
</p>
</div>
<div class="flex gap-3 justify-center">
<%
brokerage_connect_href = if @snaptrade_item.oauth_configured?
connect_snaptrade_item_path(
@snaptrade_item,
return_to: "setup_accounts",
accountable_type: params[:accountable_type]
)
else
snaptrade_authorize_path(
item_id: @snaptrade_item.id,
accountable_type: params[:accountable_type],
return_to: params[:return_to]
)
end
brokerage_connect_frame = @snaptrade_item.oauth_configured? ? "_top" : snaptrade_authorize_frame
%>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.try_again", default: "Connect Brokerage"),
variant: "primary",
href: brokerage_connect_href,
frame: brokerage_connect_frame
) %>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.back_to_settings", default: "Back to Settings"),
variant: "secondary",
href: settings_providers_path,
frame: "_top"
) %>
</div>
<% else %>
<%= form_with url: complete_account_setup_snaptrade_item_path(@snaptrade_item),
method: :post,
data: {
controller: "loading-button",
action: "submit->loading-button#showLoading",
loading_button_loading_text_value: t("snaptrade_items.setup_accounts.creating", default: "Creating Accounts..."),
turbo_frame: "_top"
} do |form| %>
<% if @unlinked_accounts.any? %>
<div class="space-y-4">
<h3 class="font-medium text-primary"><%= t("snaptrade_items.setup_accounts.available_accounts", default: "Available Accounts") %></h3>
<% @unlinked_accounts.each do |snaptrade_account| %>
<div class="border border-primary rounded-lg p-4 hover:bg-surface transition-colors">
<div class="flex items-center gap-3">
<input type="checkbox"
id="account_<%= snaptrade_account.id %>"
name="account_ids[]"
value="<%= snaptrade_account.id %>"
checked
class="cursor-pointer">
<label for="account_<%= snaptrade_account.id %>" class="flex-1 cursor-pointer">
<h4 class="font-medium text-primary"><%= snaptrade_account.name %></h4>
<p class="text-sm text-secondary">
<% if snaptrade_account.brokerage_name.present? %>
<%= snaptrade_account.brokerage_name %>
<% end %>
<% if snaptrade_account.account_type.present? %>
<%= snaptrade_account.account_type.titleize %>
<% end %>
<%= t("snaptrade_items.setup_accounts.balance_label", default: "Balance:") %>
<%= number_to_currency(snaptrade_account.current_balance || 0, unit: Money::Currency.new(snaptrade_account.currency || "USD").symbol) %>
</p>
<% if snaptrade_account.account_number.present? %>
<p class="text-xs text-secondary"><%= t("snaptrade_items.setup_accounts.account_number", default: "Account:") %> •••<%= snaptrade_account.account_number.last(4) %></p>
<% end %>
</label>
</div>
<div class="mt-3 pl-7" onclick="event.stopPropagation();">
<%= render DS::Select.new(
form: form,
method: "account_types[#{snaptrade_account.id}]",
items: @account_type_options.map { |label, value| { label: label, value: value } },
selected: snaptrade_account.suggested_account_type,
label: t("snaptrade_items.setup_accounts.account_type_label")
) %>
<label for="sync_start_<%= snaptrade_account.id %>" class="block text-xs text-secondary mb-1">
<%= t("snaptrade_items.setup_accounts.sync_start_date_label", default: "Import transactions from:") %>
</label>
<input type="date"
id="sync_start_<%= snaptrade_account.id %>"
name="sync_start_dates[<%= snaptrade_account.id %>]"
value="<%= snaptrade_account.sync_start_date %>"
onclick="event.stopPropagation();"
autocomplete="off"
class="bg-container border border-primary rounded px-2 py-1 text-sm text-primary">
<p class="text-xs text-secondary mt-1">
<%= t("snaptrade_items.setup_accounts.sync_start_date_help", default: "Leave blank for all available history") %>
</p>
</div>
</div>
<% end %>
</div>
<div class="flex gap-3 mt-6">
<%= render DS::Button.new(
text: t("snaptrade_items.setup_accounts.create_button", default: "Create Selected Accounts"),
variant: "primary",
icon: "plus",
type: "submit",
class: "flex-1",
data: { loading_button_target: "button" }
) %>
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.cancel_button", default: "Cancel"),
variant: "secondary",
href: accounts_path,
frame: "_top"
) %>
</div>
<% end %>
<% end %>
<%# Link-to-existing forms rendered OUTSIDE the create form to avoid nested <form> %>
<% if @unlinked_accounts.any? && @linkable_accounts.any? %>
<div class="border-t border-secondary pt-4 mt-2">
<p class="text-xs text-secondary mb-3">
<%= t("snaptrade_items.setup_accounts.or_link_existing", default: "Or link to an existing account instead of creating a new one:") %>
</p>
<div class="space-y-2">
<% @unlinked_accounts.each do |snaptrade_account| %>
<%= form_with url: link_existing_account_snaptrade_items_path, method: :post, data: { turbo_frame: "_top" } do |link_form| %>
<%= link_form.hidden_field :snaptrade_account_id, value: snaptrade_account.id %>
<%= link_form.hidden_field :snaptrade_item_id, value: @snaptrade_item.id %>
<p class="text-xs text-primary mb-1"><%= snaptrade_account.name %></p>
<div class="flex items-center gap-2">
<%= link_form.select :account_id,
options_for_select(@linkable_accounts.map { |a| ["#{a.name} (#{number_to_currency(a.balance, unit: Money::Currency.new(a.currency || "USD").symbol)})", a.id] }),
{ prompt: t("snaptrade_items.setup_accounts.select_account", default: "Select an account...") },
class: "bg-container border border-primary rounded px-2 py-1 text-sm text-primary flex-1 min-w-0" %>
<%= render DS::Button.new(
text: t("snaptrade_items.setup_accounts.link_button", default: "Link"),
variant: "secondary",
size: "sm",
type: "submit"
) %>
</div>
<% end %>
<% end %>
</div>
</div>
<% end %>
<% if @linked_accounts.any? %>
<div class="<%= "border-t border-primary pt-6 mt-4" if @unlinked_accounts.any? %>">
<h3 class="font-medium text-primary mb-4"><%= t("snaptrade_items.setup_accounts.linked_accounts", default: "Already Linked") %></h3>
<% @linked_accounts.each do |snaptrade_account| %>
<div class="border border-success/20 bg-success/5 rounded-lg p-4 mb-2">
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<%= icon "check-circle", class: "text-success" %>
<div>
<h4 class="font-medium text-primary"><%= snaptrade_account.name %></h4>
<p class="text-sm text-secondary">
<%= t("snaptrade_items.setup_accounts.linked_to", default: "Linked to:") %>
<%= link_to snaptrade_account.current_account.name, account_path(snaptrade_account.current_account), class: "link" %>
</p>
</div>
</div>
</div>
</div>
<% end %>
</div>
<%# Show Done button when all accounts are linked (no unlinked) %>
<% if @unlinked_accounts.blank? %>
<div class="flex justify-end mt-4">
<%= render DS::Link.new(
text: t("snaptrade_items.setup_accounts.done_button", default: "Done"),
variant: "primary",
href: accounts_path,
frame: "_top"
) %>
</div>
<% end %>
<% end %>
<% end %>
</div>
<% end %>
<% end %>