Open-source personal finance manager. Self-hosted, privacy-first.
feat: add SimpleFIN Bridge connector for US/international banks (#231)
Tássio Noronhafe19f44e5010
diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex e911b160..809cec2d 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -27,6 +27,12 @@ class Settings(BaseSettings):enable_banking_api_url: str = "https://api.enablebanking.com"enable_banking_oauth_redirect_uri: str = "http://localhost:5173/oauth/callback"+ # SimpleFIN Bridge (US/intl banks, paste-a-token flow). Off by default.+ # The bridge URL defaults to the beta/sandbox host so users can test with+ # the demo token; flip to https://bridge.simplefin.org for production.+ simplefin_enabled: bool = False+ simplefin_api_url: str = "https://beta-bridge.simplefin.org"+# Frontendfrontend_url: str = "http://localhost:5173"diff --git a/backend/app/providers/__init__.py b/backend/app/providers/__init__.pyindex b253a9cc..221aa075 100644--- a/backend/app/providers/__init__.py+++ b/backend/app/providers/__init__.py@@ -31,6 +31,13 @@ KNOWN_PROVIDERS = ["flow_type": "oauth","requires_institution_select": True,},+ {+ "name": "simplefin",+ "display_name": "SimpleFIN",+ "description": "US and international banks via SimpleFIN Bridge",+ "flow_type": "token",+ "requires_institution_select": False,+ },]@@ -80,6 +87,10 @@ def _auto_register_providers() -> None:from app.providers.enable_banking import EnableBankingProviderregister_provider("enable_banking", EnableBankingProvider)+ if settings.simplefin_enabled:+ from app.providers.simplefin import SimpleFinProvider+ register_provider("simplefin", SimpleFinProvider)+_auto_register_providers()diff --git a/backend/app/providers/simplefin.py b/backend/app/providers/simplefin.pynew file mode 100644index 00000000..9dea0c57--- /dev/null+++ b/backend/app/providers/simplefin.py@@ -0,0 +1,421 @@+"""SimpleFIN Bridge provider.++SimpleFIN (https://www.simplefin.org) is a read-only financial interchange+protocol. The user gets a Setup Token from a SimpleFIN server (typically the+SimpleFIN Bridge at https://bridge.simplefin.org), pastes it into Securo,+and Securo claims an Access URL that embeds Basic Auth credentials. From then+on, ``GET {access_url}/accounts?version=2`` returns accounts + transactions++ holdings in a single JSON document.++The protocol is intentionally simple: there's no OAuth dance, no widget, no+on-demand refresh, no MFA. Every read goes to the bridge, which pulls from+the bank on its own schedule. Rate limits (24 req/day per access token for+the all-accounts endpoint, plus per-account quotas) are documented at+https://beta-bridge.simplefin.org/info/developers — we don't try to enforce+them client-side; the bridge surfaces warnings in the ``errlist`` response.++All SimpleFIN-specific shapes (Setup Token base64, ``errlist`` codes, 90-day+window, ``balance-date`` epoch seconds) are contained in this module.+"""+from __future__ import annotations++import base64+import binascii+import logging+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal, InvalidOperation+from typing import Any, Optional++import httpx++from app.agents.services.crypto import decrypt, encrypt+from app.providers.base import (+ AccountData,+ BankProvider,+ ConnectionData,+ HoldingData,+ ProviderUserActionRequired,+ SessionExpiredError,+ TransactionData,+)++logger = logging.getLogger(__name__)++# SimpleFIN constrains each ``/accounts`` call to a 90-day window. For the+# initial sync (since=None) we walk backwards in chunks of this size; for+# follow-up syncs the sync layer's typical 30-90 day window fits in one call.+SIMPLEFIN_MAX_WINDOW_DAYS = 90+SIMPLEFIN_DEFAULT_HISTORY_DAYS = 90+SIMPLEFIN_INITIAL_HISTORY_DAYS = 365 # ~1 year backfill on first connect+SIMPLEFIN_HTTP_TIMEOUT = 60.0++# Error codes that signal the user must re-authorize via the Bridge (the+# stored Access URL is no longer valid). Everything else under con.* / act.*+# is treated as transient and surfaces as a warning, not a hard failure.+_REAUTH_ERROR_CODES = frozenset({"gen.auth", "con.auth"})+++def _decode_setup_token(raw: str) -> str:+ """Decode a SimpleFIN Setup Token (Base64-encoded URL).++ The token comes straight from the Bridge's setup page; users paste it in+ with surrounding whitespace and sometimes line breaks, so we normalize.+ """+ cleaned = "".join(raw.split())+ if not cleaned:+ raise ValueError("SimpleFIN setup token is empty")+ # Re-pad to a multiple of 4; SimpleFIN tokens are technically already+ # padded but pasted versions sometimes lose the trailing '='.+ padding = (-len(cleaned)) % 4+ cleaned = cleaned + ("=" * padding)+ try:+ decoded = base64.b64decode(cleaned, validate=True).decode("utf-8")+ except (binascii.Error, UnicodeDecodeError) as exc:+ raise ValueError("SimpleFIN setup token is not valid base64") from exc+ if not decoded.startswith(("http://", "https://")):+ raise ValueError("SimpleFIN setup token did not decode to a URL")+ return decoded+++def _epoch_to_date(value: Any) -> Optional[date]:+ if value is None or value == "":+ return None+ try:+ return datetime.fromtimestamp(int(value), tz=timezone.utc).date()+ except (ValueError, TypeError, OSError):+ return None+++def _to_decimal(value: Any) -> Optional[Decimal]:+ if value is None or value == "":+ return None+ try:+ return Decimal(str(value))+ except (InvalidOperation, ValueError):+ return None+++def _surface_errors(errlist: list[dict], context: str) -> None:+ """Raise a typed exception for auth errors; log everything else.++ SimpleFIN's spec says: *Always show those errors to your end users.* For+ the codes the user can act on (re-auth), we raise so the API layer can+ flip the connection status. For the rest we log and continue — the+ response usually still has usable data alongside the warnings.+ """+ if not errlist:+ return+ reauth = [e for e in errlist if (e.get("code") or "").lower() in _REAUTH_ERROR_CODES]+ if reauth:+ first = reauth[0]+ raise ProviderUserActionRequired(+ first.get("msg") or first.get("message") or "Reauthorize at SimpleFIN Bridge",+ code="credentials_invalid",+ help_url="https://bridge.simplefin.org/",+ )+ for entry in errlist:+ logger.warning(+ "SimpleFIN %s warning code=%s msg=%s",+ context,+ entry.get("code"),+ entry.get("msg") or entry.get("message"),+ )+++class SimpleFinProvider(BankProvider):+ """SimpleFIN Bridge connector."""++ @property+ def name(self) -> str:+ return "simplefin"++ @property+ def flow_type(self) -> str:+ return "token"++ # ----- credentials / access URL handling --------------------------------++ @staticmethod+ def _access_url(credentials: dict) -> str:+ enc = (credentials or {}).get("access_url_enc")+ if enc:+ decoded = decrypt(enc)+ if decoded:+ return decoded+ # Backward compat / dev: also accept plaintext.+ return (credentials or {}).get("access_url") or ""++ async def _client(self, credentials: dict | None = None) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ timeout=SIMPLEFIN_HTTP_TIMEOUT,+ headers={+ "Accept": "application/json",+ "User-Agent": "Securo/0.1 (+https://usesecuro.com)",+ },+ )++ async def _fetch_accounts(+ self,+ credentials: dict,+ *,+ start_date: Optional[date] = None,+ end_date: Optional[date] = None,+ account_id: Optional[str] = None,+ pending: bool = True,+ ) -> dict:+ access_url = self._access_url(credentials)+ if not access_url:+ raise SessionExpiredError("SimpleFIN access URL is missing")+ params: dict[str, Any] = {"version": "2"}+ if pending:+ params["pending"] = "1"+ if start_date:+ params["start-date"] = str(int(datetime.combine(+ start_date, datetime.min.time(), tzinfo=timezone.utc,+ ).timestamp()))+ if end_date:+ params["end-date"] = str(int(datetime.combine(+ end_date, datetime.min.time(), tzinfo=timezone.utc,+ ).timestamp()))+ if account_id:+ params["account"] = account_id+ async with await self._client(credentials) as client:+ resp = await client.get(f"{access_url}/accounts", params=params)+ if resp.status_code in (401, 403):+ raise ProviderUserActionRequired(+ f"SimpleFIN refused the request ({resp.status_code})",+ code="credentials_invalid",+ help_url="https://bridge.simplefin.org/",+ )+ resp.raise_for_status()+ return resp.json() or {}++ # ----- connection flow ---------------------------------------------------++ def get_oauth_url(self, *args, **kwargs): # type: ignore[override]+ raise NotImplementedError("SimpleFIN uses paste-a-token flow, not OAuth redirect")++ async def handle_oauth_callback(self, code: str) -> ConnectionData:+ """Claim a SimpleFIN Access URL from a Setup Token.++ The endpoint name is a leftover from the OAuth flow but the contract+ — "given an opaque code, produce a ConnectionData" — applies cleanly+ to token-paste providers. The Setup Token is a single-use base64+ string from a SimpleFIN server; claiming it yields an Access URL that+ embeds Basic Auth credentials for subsequent reads.+ """+ claim_url = _decode_setup_token(code)+ async with await self._client() as client:+ try:+ claim_resp = await client.post(+ claim_url, headers={"Content-Length": "0"}+ )+ except httpx.HTTPError as exc:+ raise RuntimeError(+ f"SimpleFIN claim request failed: {exc}"+ ) from exc+ if claim_resp.status_code == 403:+ # The bridge returns 403 when a setup token is reused.+ raise ProviderUserActionRequired(+ "SimpleFIN setup token has already been used or expired. "+ "Generate a fresh token from the SimpleFIN Bridge.",+ code="setup_token_used",+ help_url="https://bridge.simplefin.org/",+ )+ if claim_resp.status_code >= 400:+ raise RuntimeError(+ f"SimpleFIN claim returned {claim_resp.status_code}: "+ f"{claim_resp.text[:200]}"+ )+ access_url = (claim_resp.text or "").strip().strip('"')+ if not access_url.startswith(("http://", "https://")):+ raise RuntimeError("SimpleFIN claim did not return a URL")++ credentials: dict[str, Any] = {+ "access_url_enc": encrypt(access_url) or access_url,+ "claimed_at": datetime.now(timezone.utc).isoformat(),+ }++ # Pull the account list once so we can return an institution name and+ # the initial AccountData list. Filter out transactions here — they're+ # fetched per-account by ``get_transactions``.+ payload = await self._fetch_accounts(credentials, pending=False)+ _surface_errors(payload.get("errlist") or [], context="claim")+ institution_name, accounts = self._parse_accounts(payload)+ return ConnectionData(+ external_id=self._stable_external_id(payload, claim_url),+ institution_name=institution_name,+ credentials=credentials,+ accounts=accounts,+ )++ @staticmethod+ def _stable_external_id(payload: dict, fallback: str) -> str:+ """Produce a stable external id for this connection.++ Prefer the first connection's ``conn_id`` (per the SimpleFIN spec each+ Access URL is one Connection at most), else the first account's+ ``conn_id``, else fall back to the claim URL hash. Falling back to the+ claim URL keeps the id deterministic across re-claims of the same+ setup token.+ """+ conns = payload.get("connections") or []+ if conns and conns[0].get("conn_id"):+ return str(conns[0]["conn_id"])+ for acc in payload.get("accounts") or []:+ if acc.get("conn_id"):+ return str(acc["conn_id"])+ # Hash the claim URL so we don't leak it.+ import hashlib++ return "simplefin-" + hashlib.sha256(fallback.encode("utf-8")).hexdigest()[:24]++ # ----- account / transaction reads --------------------------------------++ @staticmethod+ def _parse_accounts(payload: dict) -> tuple[str, list[AccountData]]:+ connections = payload.get("connections") or []+ institution_name = (+ connections[0].get("name") if connections else "SimpleFIN Connection"+ )+ accounts: list[AccountData] = []+ for raw in payload.get("accounts") or []:+ balance = _to_decimal(raw.get("balance")) or Decimal("0")+ currency = raw.get("currency") or "USD"+ account_id = str(raw.get("id") or "")+ if not account_id:+ continue+ name = raw.get("name") or "Account"+ accounts.append(+ AccountData(+ external_id=account_id,+ name=name,+ type="checking", # SimpleFIN doesn't expose an account type+ balance=balance,+ currency=currency,+ )+ )+ return institution_name or "SimpleFIN Connection", accounts++ async def get_accounts(self, credentials: dict) -> list[AccountData]:+ payload = await self._fetch_accounts(credentials, pending=False)+ _surface_errors(payload.get("errlist") or [], context="get_accounts")+ _, accounts = self._parse_accounts(payload)+ return accounts++ async def get_transactions(+ self,+ credentials: dict,+ account_external_id: str,+ since: Optional[date] = None,+ payee_source: str = "auto",+ ) -> list[TransactionData]:+ end_date = date.today()+ if since is None:+ start_date = end_date - timedelta(days=SIMPLEFIN_INITIAL_HISTORY_DAYS)+ else:+ start_date = since+ # Walk the request window in 90-day chunks (SimpleFIN's per-call cap).+ transactions: list[TransactionData] = []+ seen_ids: set[str] = set()+ cursor = start_date+ while cursor <= end_date:+ chunk_end = min(cursor + timedelta(days=SIMPLEFIN_MAX_WINDOW_DAYS), end_date)+ payload = await self._fetch_accounts(+ credentials,+ start_date=cursor,+ end_date=chunk_end + timedelta(days=1),+ account_id=account_external_id,+ pending=True,+ )+ _surface_errors(payload.get("errlist") or [], context="get_transactions")+ for raw_acc in payload.get("accounts") or []:+ if str(raw_acc.get("id") or "") != account_external_id:+ continue+ for raw_txn in raw_acc.get("transactions") or []:+ parsed = self._build_transaction(raw_txn, payee_source)+ if parsed and parsed.external_id not in seen_ids:+ seen_ids.add(parsed.external_id)+ transactions.append(parsed)+ cursor = chunk_end + timedelta(days=1)+ return transactions++ @staticmethod+ def _build_transaction(raw: dict, payee_source: str) -> Optional[TransactionData]:+ txn_id = str(raw.get("id") or "")+ if not txn_id:+ return None+ amount_raw = _to_decimal(raw.get("amount"))+ if amount_raw is None:+ return None+ txn_type = "debit" if amount_raw < 0 else "credit"+ amount = amount_raw.copy_abs()+ posted = _epoch_to_date(raw.get("posted"))+ transacted = _epoch_to_date(raw.get("transacted_at"))+ txn_date = posted or transacted+ if not txn_date:+ return None+ description = (+ raw.get("description")+ or raw.get("payee")+ or raw.get("memo")+ or "Transaction"+ ).strip()[:500]+ status = "pending" if raw.get("pending") else "posted"+ payee: Optional[str]+ if payee_source == "none":+ payee = None+ else:+ payee = (raw.get("payee") or "").strip() or None+ return TransactionData(+ external_id=txn_id,+ description=description,+ amount=amount,+ date=txn_date,+ type=txn_type,+ currency=raw.get("currency"),+ status=status,+ payee=payee,+ raw_data=raw,+ )++ async def get_holdings(self, credentials: dict) -> list[HoldingData]:+ payload = await self._fetch_accounts(credentials, pending=False)+ _surface_errors(payload.get("errlist") or [], context="get_holdings")+ holdings: list[HoldingData] = []+ for raw_acc in payload.get("accounts") or []:+ acc_currency = raw_acc.get("currency") or "USD"+ for raw in raw_acc.get("holdings") or []:+ holding_id = str(raw.get("id") or "")+ if not holding_id:+ continue+ market_value = _to_decimal(raw.get("market_value"))+ if market_value is None:+ continue+ holdings.append(+ HoldingData(+ external_id=holding_id,+ name=raw.get("description") or raw.get("symbol") or holding_id,+ currency=raw.get("currency") or acc_currency,+ current_value=market_value,+ quantity=_to_decimal(raw.get("shares")),+ unit_price=_to_decimal(raw.get("market_value")) / _to_decimal(+ raw.get("shares")+ ) if _to_decimal(raw.get("shares")) else None,+ purchase_price=_to_decimal(raw.get("purchase_price")),+ purchase_date=_epoch_to_date(raw.get("created")),+ isin=raw.get("isin"),+ metadata={+ "symbol": raw.get("symbol"),+ "cost_basis": str(raw.get("cost_basis"))+ if raw.get("cost_basis") is not None+ else None,+ },+ )+ )+ return holdings++ async def refresh_credentials(self, credentials: dict) -> dict:+ if not self._access_url(credentials):+ raise SessionExpiredError("SimpleFIN access URL missing")+ return credentialsdiff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex e2c266ec..47c36689 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -59,6 +59,7 @@ omit = ["app/tasks/*","app/providers/pluggy.py","app/providers/enable_banking.py",+ "app/providers/simplefin.py","app/providers/market_price.py",]diff --git a/backend/tests/test_providers_simplefin.py b/backend/tests/test_providers_simplefin.pynew file mode 100644index 00000000..930d3751--- /dev/null+++ b/backend/tests/test_providers_simplefin.py@@ -0,0 +1,368 @@+"""Unit tests for the SimpleFIN provider.++The bridge is fully fakeable via ``httpx.MockTransport`` — no SimpleFIN+credentials needed, no network. Each test stands up the smallest payload+required and asserts the parse / dispatch behavior we care about.+"""+from __future__ import annotations++import base64+from datetime import date, timedelta+from decimal import Decimal+from unittest.mock import patch++import httpx+import pytest++from app.providers.base import ProviderUserActionRequired, SessionExpiredError+from app.providers.simplefin import (+ SimpleFinProvider,+ _decode_setup_token,+ _epoch_to_date,+)+++def _encode_token(url: str) -> str:+ return base64.b64encode(url.encode("utf-8")).decode("ascii")+++def _patched_client(handler):+ """Replace SimpleFinProvider._client with one wired to a MockTransport."""++ transport = httpx.MockTransport(handler)++ async def fake_client(self, credentials=None): # noqa: ANN001+ return httpx.AsyncClient(transport=transport, timeout=30)++ return patch.object(SimpleFinProvider, "_client", fake_client)+++# ----- pure helpers -----------------------------------------------------------+++def test_decode_setup_token_round_trips():+ raw = _encode_token("https://bridge.simplefin.org/simplefin/claim/abc123")+ assert (+ _decode_setup_token(raw)+ == "https://bridge.simplefin.org/simplefin/claim/abc123"+ )+++def test_decode_setup_token_strips_whitespace_and_repads():+ raw = _encode_token("https://bridge.simplefin.org/simplefin/claim/xyz")+ # Strip padding to simulate a copy-pasted token, surround with whitespace.+ sloppy = " " + raw.rstrip("=") + "\n "+ assert "claim/xyz" in _decode_setup_token(sloppy)+++def test_decode_setup_token_rejects_empty():+ with pytest.raises(ValueError):+ _decode_setup_token(" ")+++def test_decode_setup_token_rejects_non_url():+ with pytest.raises(ValueError):+ _decode_setup_token(_encode_token("ftp://nope.example"))+++def test_decode_setup_token_rejects_garbage():+ with pytest.raises(ValueError):+ _decode_setup_token("this-is-not-base64!!!@@@")+++def test_epoch_to_date_handles_unset():+ assert _epoch_to_date(None) is None+ assert _epoch_to_date("") is None+++def test_epoch_to_date_parses_seconds():+ assert _epoch_to_date(1672531200) == date(2023, 1, 1)+++# ----- claim flow -------------------------------------------------------------+++async def test_handle_oauth_callback_claims_and_parses_accounts():+ """Token paste → claim → first /accounts → ConnectionData."""++ state = {"step": "claim"}++ def handler(request: httpx.Request) -> httpx.Response:+ if state["step"] == "claim":+ assert request.method == "POST"+ assert request.url.path.endswith("/simplefin/claim/demo")+ state["step"] = "accounts"+ return httpx.Response(200, text="https://u:[email protected]/simplefin")+ # /accounts request+ assert request.method == "GET"+ assert request.url.path == "/simplefin/accounts"+ return httpx.Response(+ 200,+ json={+ "errlist": [],+ "connections": [+ {"conn_id": "CON-1", "name": "Demo Bank"}+ ],+ "accounts": [+ {+ "id": "acc-1",+ "name": "Checking",+ "currency": "USD",+ "balance": "1234.56",+ "conn_id": "CON-1",+ "transactions": [],+ "holdings": [],+ }+ ],+ },+ )++ provider = SimpleFinProvider()+ token = _encode_token("https://bridge.example/simplefin/claim/demo")+ with _patched_client(handler):+ conn = await provider.handle_oauth_callback(token)++ assert conn.external_id == "CON-1"+ assert conn.institution_name == "Demo Bank"+ assert "access_url_enc" in conn.credentials+ # The plaintext URL must never end up in credentials.+ assert "u:p@" not in str(conn.credentials.get("access_url_enc"))+ assert len(conn.accounts) == 1+ acc = conn.accounts[0]+ assert acc.external_id == "acc-1"+ assert acc.balance == Decimal("1234.56")+ assert acc.currency == "USD"+++async def test_handle_oauth_callback_403_signals_reused_token():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(403, text="token already used")++ provider = SimpleFinProvider()+ token = _encode_token("https://bridge.example/simplefin/claim/demo")+ with _patched_client(handler):+ with pytest.raises(ProviderUserActionRequired) as exc:+ await provider.handle_oauth_callback(token)+ assert exc.value.code == "setup_token_used"+++# ----- error mapping ----------------------------------------------------------+++async def test_auth_errlist_raises_user_action_required():+ """SimpleFIN ``con.auth`` / ``gen.auth`` → user must regenerate the token."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "errlist": [+ {"code": "con.auth", "msg": "Authentication failed", "conn_id": "C"}+ ],+ "accounts": [],+ },+ )++ creds = {"access_url_enc": None, "access_url": "https://u:[email protected]/simplefin"}+ provider = SimpleFinProvider()+ with _patched_client(handler):+ with pytest.raises(ProviderUserActionRequired) as exc:+ await provider.get_accounts(creds)+ assert exc.value.code == "credentials_invalid"+++async def test_act_failed_is_soft_warning(caplog):+ """``act.failed`` is transient — keep going, just log."""+ import logging as stdlogging++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "errlist": [+ {"code": "act.failed", "msg": "transient", "account_id": "X"}+ ],+ "accounts": [+ {+ "id": "acc-1",+ "name": "Checking",+ "currency": "USD",+ "balance": "10.00",+ }+ ],+ },+ )++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ provider = SimpleFinProvider()+ with caplog.at_level(stdlogging.WARNING, logger="app.providers.simplefin"), _patched_client(handler):+ accounts = await provider.get_accounts(creds)+ assert len(accounts) == 1+ assert any("act.failed" in rec.getMessage() for rec in caplog.records)+++async def test_401_response_signals_credentials_invalid():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text="nope")++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ with _patched_client(handler):+ with pytest.raises(ProviderUserActionRequired):+ await SimpleFinProvider().get_accounts(creds)+++async def test_missing_access_url_raises_session_expired():+ with pytest.raises(SessionExpiredError):+ await SimpleFinProvider().get_accounts({})+++# ----- transactions -----------------------------------------------------------+++async def test_get_transactions_filters_by_account_and_parses_signs():+ """Negative amount → debit; positive → credit."""++ def handler(request: httpx.Request) -> httpx.Response:+ assert request.url.path == "/simplefin/accounts"+ # We always request a specific account+ assert request.url.params.get("account") == "acc-1"+ assert request.url.params.get("pending") == "1"+ return httpx.Response(+ 200,+ json={+ "accounts": [+ {+ "id": "acc-1",+ "currency": "USD",+ "balance": "0",+ "transactions": [+ {+ "id": "t1",+ "amount": "-12.34",+ "posted": 1672531200, # 2023-01-01 UTC+ "description": "Coffee",+ "payee": "Cafe",+ },+ {+ "id": "t2",+ "amount": "100.00",+ "posted": 1672617600, # 2023-01-02 UTC+ "description": "Payroll",+ "pending": True,+ },+ ],+ },+ { # noise — a different account in the same response+ "id": "acc-2",+ "transactions": [+ {"id": "tX", "amount": "5", "posted": 1672531200},+ ],+ },+ ]+ },+ )++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ provider = SimpleFinProvider()+ with _patched_client(handler):+ txns = await provider.get_transactions(+ creds, "acc-1", since=date(2023, 1, 1)+ )+ by_id = {t.external_id: t for t in txns}+ assert set(by_id) == {"t1", "t2"}+ assert by_id["t1"].type == "debit"+ assert by_id["t1"].amount == Decimal("12.34")+ assert by_id["t1"].status == "posted"+ assert by_id["t2"].status == "pending"+ assert by_id["t2"].type == "credit"+++async def test_get_transactions_chunks_long_windows():+ """``since`` more than 90 days ago → multiple requests with shifting windows."""++ calls: list[tuple[str, str]] = []++ def handler(request: httpx.Request) -> httpx.Response:+ calls.append(+ (+ request.url.params.get("start-date", ""),+ request.url.params.get("end-date", ""),+ )+ )+ return httpx.Response(+ 200, json={"accounts": [{"id": "acc-1", "transactions": []}]}+ )++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ today = date.today()+ long_ago = today - timedelta(days=200)+ with _patched_client(handler):+ await SimpleFinProvider().get_transactions(creds, "acc-1", since=long_ago)+ assert len(calls) >= 3 # 200 days / 90-day window+++# ----- holdings ---------------------------------------------------------------+++async def test_get_holdings_parses_investment_data():+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "accounts": [+ {+ "id": "acc-1",+ "currency": "USD",+ "holdings": [+ {+ "id": "h-1",+ "description": "Apple",+ "symbol": "AAPL",+ "market_value": "105884.80",+ "shares": "550.0",+ "purchase_price": "0.10",+ "cost_basis": "55.00",+ },+ { # no market value → dropped+ "id": "h-2",+ "description": "Mystery",+ "shares": "1",+ },+ ],+ }+ ]+ },+ )++ creds = {"access_url": "https://u:[email protected]/simplefin"}+ with _patched_client(handler):+ holdings = await SimpleFinProvider().get_holdings(creds)+ assert len(holdings) == 1+ h = holdings[0]+ assert h.external_id == "h-1"+ assert h.current_value == Decimal("105884.80")+ assert h.quantity == Decimal("550.0")+ assert (h.metadata or {}).get("symbol") == "AAPL"+++# ----- misc -------------------------------------------------------------------+++def test_flow_type_is_token():+ p = SimpleFinProvider()+ assert p.flow_type == "token"+ assert p.name == "simplefin"+++def test_get_oauth_url_raises_for_token_flow():+ with pytest.raises(NotImplementedError):+ SimpleFinProvider().get_oauth_url("https://x", "state")diff --git a/frontend/src/components/token-connect-dialog.tsx b/frontend/src/components/token-connect-dialog.tsxnew file mode 100644index 00000000..4ba03d2f--- /dev/null+++ b/frontend/src/components/token-connect-dialog.tsx@@ -0,0 +1,117 @@+import { useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useQueryClient } from '@tanstack/react-query'+import axios from 'axios'+import { connections } from '@/lib/api'+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { ExternalLink } from 'lucide-react'+import { toast } from 'sonner'++interface TokenConnectDialogProps {+ open: boolean+ onClose: () => void+ provider: string+}++const PROVIDER_BRIDGE_URLS: Record<string, string> = {+ simplefin: 'https://bridge.simplefin.org/simplefin/create',+}++export function TokenConnectDialog({ open, onClose, provider }: TokenConnectDialogProps) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const [token, setToken] = useState('')+ const [submitting, setSubmitting] = useState(false)++ useEffect(() => {+ if (!open) {+ setToken('')+ setSubmitting(false)+ }+ }, [open])++ const bridgeUrl = PROVIDER_BRIDGE_URLS[provider]+ const i18nKey = `accounts.tokenConnect.${provider}`++ const handleSubmit = async () => {+ if (!token.trim()) return+ setSubmitting(true)+ try {+ await connections.handleCallback(token.trim(), provider)+ invalidateFinancialQueries(queryClient)+ queryClient.invalidateQueries({ queryKey: ['connections'] })+ toast.success(t('accounts.connected'))+ onClose()+ } catch (err) {+ const detail =+ axios.isAxiosError(err) && err.response?.data?.detail+ ? typeof err.response.data.detail === 'string'+ ? err.response.data.detail+ : err.response.data.detail.message+ : null+ toast.error(detail || t('accounts.connectError'))+ } finally {+ setSubmitting(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={(v) => !v && !submitting && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(`${i18nKey}.title`, t('accounts.tokenConnect.defaultTitle'))}</DialogTitle>+ <p className="text-sm text-muted-foreground">+ {t(`${i18nKey}.description`, t('accounts.tokenConnect.defaultDescription'))}+ </p>+ </DialogHeader>++ {bridgeUrl && (+ <Button asChild variant="outline" className="w-full justify-between">+ <a href={bridgeUrl} target="_blank" rel="noreferrer">+ <span>{t('accounts.tokenConnect.openBridge')}</span>+ <ExternalLink size={14} />+ </a>+ </Button>+ )}++ <div className="space-y-1.5">+ <label className="text-sm font-medium" htmlFor="securo-token-input">+ {t('accounts.tokenConnect.tokenLabel')}+ </label>+ <textarea+ id="securo-token-input"+ className="w-full min-h-[110px] rounded-md border border-input bg-background px-3 py-2 text-sm font-mono resize-y focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-0"+ placeholder={t('accounts.tokenConnect.tokenPlaceholder')}+ value={token}+ onChange={(e) => setToken(e.target.value)}+ spellCheck={false}+ autoComplete="off"+ disabled={submitting}+ />+ <p className="text-xs text-muted-foreground">+ {t('accounts.tokenConnect.tokenHelp')}+ </p>+ </div>++ <DialogFooter>+ <Button variant="outline" onClick={onClose} disabled={submitting}>+ {t('common.cancel')}+ </Button>+ <Button onClick={handleSubmit} disabled={!token.trim() || submitting}>+ {submitting+ ? t('accounts.tokenConnect.connecting')+ : t('accounts.tokenConnect.connect')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex b38d6ed6..f738c3b2 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -507,12 +507,29 @@"missingState": "OAuth state is missing or invalid. Please start the connection again.","providerError": "The bank reported an error: {{message}}"},+ "tokenConnect": {+ "defaultTitle": "Connect with a token",+ "defaultDescription": "Generate a setup token at the provider and paste it below to link your accounts.",+ "openBridge": "Generate token at SimpleFIN Bridge",+ "tokenLabel": "Setup token",+ "tokenPlaceholder": "Paste the token you received…",+ "tokenHelp": "The setup token is single-use. Securo claims a private access URL from it and stores it encrypted.",+ "connect": "Connect",+ "connecting": "Connecting…",+ "simplefin": {+ "title": "Connect via SimpleFIN",+ "description": "SimpleFIN is a read-only bank data protocol. Go to the SimpleFIN Bridge, pick your bank, and copy the setup token back here."+ }+ },"providers": {"pluggy": {"description": "Open finance provider for Brazilian banks"},"enable_banking": {"description": "European banks via PSD2 open banking"+ },+ "simplefin": {+ "description": "US and international banks via SimpleFIN Bridge"}}},diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 06c15dc5..a4c9cd15 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -507,12 +507,29 @@"missingState": "O estado do OAuth está ausente ou inválido. Inicie a conexão novamente.","providerError": "O banco reportou um erro: {{message}}"},+ "tokenConnect": {+ "defaultTitle": "Conectar com um token",+ "defaultDescription": "Gere um token de configuração no provedor e cole abaixo para conectar suas contas.",+ "openBridge": "Gerar token no SimpleFIN Bridge",+ "tokenLabel": "Token de configuração",+ "tokenPlaceholder": "Cole o token que você recebeu…",+ "tokenHelp": "O token é de uso único. O Securo gera uma URL de acesso privada a partir dele e a armazena criptografada.",+ "connect": "Conectar",+ "connecting": "Conectando…",+ "simplefin": {+ "title": "Conectar via SimpleFIN",+ "description": "O SimpleFIN é um protocolo de leitura de dados bancários. Vá ao SimpleFIN Bridge, escolha o seu banco e copie o token de configuração aqui."+ }+ },"providers": {"pluggy": {"description": "Provedor Open Finance para bancos brasileiros"},"enable_banking": {"description": "Bancos europeus via PSD2 Open Banking"+ },+ "simplefin": {+ "description": "Bancos dos EUA e internacionais via SimpleFIN Bridge"}}},diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 94aeab54..8570a49a 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -39,6 +39,7 @@ import { PageHeader } from '@/components/page-header'import { BankConnectDialog } from '@/components/bank-connect-dialog'import { ConnectorSelectDialog, type Provider } from '@/components/connector-select-dialog'import { OAuthConnectDialog } from '@/components/oauth-connect-dialog'+import { TokenConnectDialog } from '@/components/token-connect-dialog'import { ConnectionSettingsDialog } from '@/components/connection-settings-dialog'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'@@ -628,6 +629,13 @@ export default function AccountsPage() {provider={selectedProvider?.name ?? ''}/>+ {/* Token Connect Dialog — paste-a-token flow (SimpleFIN) */}+ <TokenConnectDialog+ open={!!selectedProvider && selectedProvider.flow_type === 'token'}+ onClose={() => setSelectedProvider(null)}+ provider={selectedProvider?.name ?? ''}+ />+{/* Reconnect Dialog */}<BankConnectDialogopen={!!reconnectConnId}