Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat: add Enable Banking connector for European PSD2 banks (#229)

Tássio Noronhaa6222a3e0f7d
diff --git a/.env.example b/.env.example
index c838abf2..625a3b4b 100644
--- a/.env.example
+++ b/.env.example
@@ -8,6 +8,17 @@ SECRET_KEY=change-me-in-production
PLUGGY_CLIENT_ID=
PLUGGY_CLIENT_SECRET=
+# Bank sync — Enable Banking (https://enablebanking.com) for European banks
+## 1. Sign up at https://enablebanking.com and create a Production application
+## 2. Add http://localhost:${FRONTEND_PORT}/oauth/callback as an allowed redirect URL
+## 3. Save the downloaded PEM file to ./secrets/enable_banking_private.pem
+## 4. Copy your Application ID below
+ENABLE_BANKING_APP_ID=
+# Override only if you put the PEM somewhere other than the default below
+# ENABLE_BANKING_PRIVATE_KEY_FILE=/app/secrets/enable_banking_private.pem
+# Must match exactly one of the Allowed Redirect URLs in your EB application
+ENABLE_BANKING_OAUTH_REDIRECT_URI=http://localhost:${FRONTEND_PORT:-3000}/oauth/callback
+
# Host ports (optional) — change these to avoid conflicts with other services
## Default values are set in docker-compose.yml and docker-compose.prod.yml.
## Example:
diff --git a/.gitignore b/.gitignore
index c54e80f2..01865a63 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.env
+secrets/
.worktrees/
.DS_Store
.playwright-mcp/
diff --git a/README.md b/README.md
index 1c159766..735e89ea 100644
--- a/README.md
+++ b/README.md
@@ -47,7 +47,7 @@ Open [http://localhost:3000](http://localhost:3000) and create an account. That'
- Goals and savings targets with progress tracking
- Asset management with valuation tracking and growth rules
- Reports: Net Worth and Income vs Expenses with category sparklines
-- Bank sync via providers (Pluggy supported, extensible)
+- Bank sync via providers (Pluggy for Brazilian banks, Enable Banking for ~2500 European PSD2 banks, extensible)
- Multi-currency support with automatic FX conversion
- Multi-user support with admin panel and registration controls
- Two-factor authentication (TOTP) with brute-force protection
@@ -55,14 +55,30 @@ Open [http://localhost:3000](http://localhost:3000) and create an account. That'
## Bank Sync (Optional)
-Create a `.env` file with your [Pluggy](https://pluggy.ai) credentials:
+Add credentials for any of the supported providers to `.env`, then restart with `docker compose up`. Configure one or both — each provider auto-registers when its credentials are present.
+
+### Pluggy — Brazilian banks
+
+Sign up at [pluggy.ai](https://pluggy.ai) and add:
```
PLUGGY_CLIENT_ID=your-client-id
PLUGGY_CLIENT_SECRET=your-client-secret
```
-Then restart: `docker compose up`
+### Enable Banking — European banks (PSD2)
+
+Sign up at [enablebanking.com](https://enablebanking.com), create a Production application, and download its PEM private key. Save the PEM to `./secrets/` (gitignored), then add:
+
+```
+ENABLE_BANKING_APP_ID=your-application-id
+ENABLE_BANKING_PRIVATE_KEY_FILE=/app/secrets/your-key.pem
+ENABLE_BANKING_OAUTH_REDIRECT_URI=https://your-host/oauth/callback
+```
+
+The redirect URI must match exactly one of the Allowed Redirect URLs in your EB application. Production EB requires HTTPS — for local development, expose your frontend via a tunnel (ngrok, cloudflared) or use the EB sandbox.
+
+> **Free tier — restricted mode.** Enable Banking's free plan requires you to pre-link the accounts you want to import inside the EB portal *before* connecting from Securo. If you skip that step, the connection returns no accounts and Securo will surface a banner with a link to the portal.
## Exchange Rates (Optional)
diff --git a/backend/app/api/connections.py b/backend/app/api/connections.py
index f27f89a0..508f1c9e 100644
--- a/backend/app/api/connections.py
+++ b/backend/app/api/connections.py
@@ -10,15 +10,18 @@ from app.core.workspace_context import (
current_writable_workspace,
)
from app.providers import all_known_providers
+from app.providers.base import ProviderUserActionRequired, SessionExpiredError
from app.schemas.bank_connection import (
BankConnectionRead,
- OAuthUrlRequest,
- OAuthUrlResponse,
- OAuthCallbackRequest,
+ ConnectionSettingsUpdate,
ConnectTokenRequest,
ConnectTokenResponse,
+ InstitutionListResponse,
+ OAuthCallbackRequest,
+ OAuthUrlRequest,
+ OAuthUrlResponse,
+ ReauthUrlResponse,
ReconnectTokenResponse,
- ConnectionSettingsUpdate,
)
from app.services import connection_service
from app.services.transfer_detection_service import detect_transfer_pairs, unlink_transfer_pair
@@ -64,12 +67,31 @@ async def get_oauth_url(
ctx: WorkspaceContext = Depends(current_writable_workspace),
):
try:
- url = connection_service.get_oauth_url(data.provider, ctx.user_id)
+ url = await connection_service.get_oauth_url(
+ data.provider, ctx.user_id, ctx.workspace.id, flow_params=data.flow_params
+ )
return OAuthUrlResponse(url=url)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
[email protected]("/{provider}/institutions", response_model=InstitutionListResponse)
+async def list_provider_institutions(
+ provider: str,
+ country: str | None = None,
+ ctx: WorkspaceContext = Depends(current_workspace),
+):
+ try:
+ return await connection_service.list_provider_institutions(provider, country)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ except Exception as e:
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Failed to load institutions: {str(e)}",
+ )
+
+
@router.post("/oauth/callback", response_model=BankConnectionRead)
async def oauth_callback(
data: OAuthCallbackRequest,
@@ -78,9 +100,29 @@ async def oauth_callback(
):
try:
connection = await connection_service.handle_oauth_callback(
- session, ctx.workspace.id, ctx.user_id, data.code, data.provider
+ session,
+ ctx.workspace.id,
+ ctx.user_id,
+ data.code,
+ provider_name=data.provider,
+ state=data.state,
)
return connection
+ except ProviderUserActionRequired as e:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "message": str(e),
+ "code": e.code,
+ "help_url": e.help_url,
+ },
+ )
+ except SessionExpiredError as e:
+ raise HTTPException(
+ status_code=status.HTTP_410_GONE, detail=str(e)
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
except Exception as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -88,6 +130,30 @@ async def oauth_callback(
)
+ "/{connection_id}/oauth/reauth-url", response_model=ReauthUrlResponse
+)
+async def get_reauth_url(
+ connection_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(current_writable_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ try:
+ url = await connection_service.get_reauth_url(
+ session, connection_id, ctx.workspace.id, ctx.user_id
+ )
+ return ReauthUrlResponse(url=url)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
+ except NotImplementedError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ except Exception as e:
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail=f"Failed to build reauth URL: {str(e)}",
+ )
+
+
@router.post("/{connection_id}/sync")
async def sync_connection(
connection_id: uuid.UUID,
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 27bf6fce..e911b160 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -20,6 +20,13 @@ class Settings(BaseSettings):
pluggy_client_secret: str = ""
pluggy_oauth_redirect_uri: str = "http://localhost:5173/oauth/callback"
+ # Enable Banking (European PSD2 banks)
+ enable_banking_app_id: str = ""
+ enable_banking_private_key: str = "" # raw PEM; supports \n-escaped envs
+ enable_banking_private_key_file: str = "" # path to PEM file; takes precedence
+ enable_banking_api_url: str = "https://api.enablebanking.com"
+ enable_banking_oauth_redirect_uri: str = "http://localhost:5173/oauth/callback"
+
# Frontend
frontend_url: str = "http://localhost:5173"
diff --git a/backend/app/providers/__init__.py b/backend/app/providers/__init__.py
index 415b40e1..1ea183d4 100644
--- a/backend/app/providers/__init__.py
+++ b/backend/app/providers/__init__.py
@@ -4,6 +4,10 @@ from app.providers.base import (
ConnectTokenData,
ConnectionData,
HoldingData,
+ InstitutionData,
+ InstitutionListData,
+ ProviderUserActionRequired,
+ SessionExpiredError,
TransactionData,
)
@@ -17,6 +21,14 @@ KNOWN_PROVIDERS = [
"display_name": "Pluggy",
"description": "Open finance provider for Brazilian banks",
"flow_type": "widget",
+ "requires_institution_select": False,
+ },
+ {
+ "name": "enable_banking",
+ "display_name": "Enable Banking",
+ "description": "European banks via PSD2 open banking",
+ "flow_type": "oauth",
+ "requires_institution_select": True,
},
]
@@ -60,6 +72,13 @@ def _auto_register_providers() -> None:
from app.providers.pluggy import PluggyProvider
register_provider("pluggy", PluggyProvider)
+ eb_has_key = bool(
+ settings.enable_banking_private_key or settings.enable_banking_private_key_file
+ )
+ if settings.enable_banking_app_id and eb_has_key:
+ from app.providers.enable_banking import EnableBankingProvider
+ register_provider("enable_banking", EnableBankingProvider)
+
_auto_register_providers()
@@ -93,6 +112,10 @@ __all__ = [
"ConnectionData",
"ConnectTokenData",
"HoldingData",
+ "InstitutionData",
+ "InstitutionListData",
+ "ProviderUserActionRequired",
+ "SessionExpiredError",
"register_provider",
"get_provider",
"list_providers",
diff --git a/backend/app/providers/base.py b/backend/app/providers/base.py
index 85effc80..65bc3e93 100644
--- a/backend/app/providers/base.py
+++ b/backend/app/providers/base.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
from typing import Optional
@@ -99,6 +99,45 @@ class HoldingData:
metadata: Optional[dict] = None
+@dataclass
+class InstitutionData:
+ """One ASPSP/bank offered by an OAuth provider."""
+
+ name: str # canonical identifier the provider expects in subsequent calls
+ display_name: str
+ country: str # ISO 3166-1 alpha-2
+ logo: Optional[str] = None
+ bic: Optional[str] = None
+ psu_types: list[str] = field(default_factory=list) # e.g. ["personal", "business"]
+ max_consent_days: Optional[int] = None
+ max_history_days: Optional[int] = None
+
+
+@dataclass
+class InstitutionListData:
+ """List of supported institutions (banks) for a provider, optionally for one country."""
+
+ countries: list[str]
+ institutions: list[InstitutionData]
+
+
+class SessionExpiredError(Exception):
+ """Raised when a provider session/consent has expired and reauth is required."""
+
+
+class ProviderUserActionRequired(Exception):
+ """Raised when a provider needs the user to take an action outside the app.
+
+ Example: Enable Banking restricted mode requires the user to pre-link
+ accounts in the EB portal before sessions return any accounts.
+ """
+
+ def __init__(self, message: str, *, code: str, help_url: Optional[str] = None) -> None:
+ super().__init__(message)
+ self.code = code
+ self.help_url = help_url
+
+
class FxRateProvider(ABC):
"""Abstract interface for FX rate providers."""
@@ -137,17 +176,60 @@ class BankProvider(ABC):
"""Connection flow type: 'oauth' for redirect-based, 'widget' for embedded widget."""
return "oauth"
+ @property
+ def redirect_uri(self) -> str:
+ """Provider-specific OAuth redirect URI.
+
+ Each provider reads its own env var (e.g.
+ ``PLUGGY_OAUTH_REDIRECT_URI``, ``ENABLE_BANKING_OAUTH_REDIRECT_URI``)
+ so different providers can register different URLs in their
+ respective dashboards.
+ """
+ from app.core.config import get_settings
+
+ return get_settings().pluggy_oauth_redirect_uri
+
async def create_connect_token(
self, client_user_id: str, item_id: str | None = None
) -> ConnectTokenData:
"""Create a connect token for widget-based flows. Override in widget providers."""
raise NotImplementedError(f"{self.name} does not support widget connect tokens")
+ async def list_institutions(
+ self, country: Optional[str] = None
+ ) -> "InstitutionListData":
+ """List supported institutions (banks). Empty by default for providers
+ that don't surface a selection step (Pluggy uses its own widget).
+ """
+ return InstitutionListData(countries=[], institutions=[])
+
@abstractmethod
- def get_oauth_url(self, redirect_uri: str, state: str) -> str:
- """Generate OAuth URL for user to authorize."""
+ async def get_oauth_url(
+ self,
+ redirect_uri: str,
+ state: str,
+ flow_params: Optional[dict] = None,
+ ) -> str:
+ """Generate OAuth URL for user to authorize.
+
+ ``flow_params`` carries provider-specific options gathered up-front
+ (e.g. EB needs ``{"country": "DE", "institution_name": "Revolut"}``).
+ """
...
+ async def reauth_url(
+ self,
+ credentials: dict,
+ settings: dict,
+ redirect_uri: str,
+ state: str,
+ ) -> str:
+ """Build a re-authorization URL for an existing connection whose
+ session/consent expired. Default raises — only providers with
+ renewable consent (OAuth-redirect) need to override.
+ """
+ raise NotImplementedError(f"{self.name} does not support reauth_url")
+
@abstractmethod
async def handle_oauth_callback(self, code: str) -> ConnectionData:
"""Exchange OAuth code for access token and fetch initial data."""
diff --git a/backend/app/providers/enable_banking.py b/backend/app/providers/enable_banking.py
new file mode 100644
index 00000000..38035638
--- /dev/null
+++ b/backend/app/providers/enable_banking.py
@@ -0,0 +1,557 @@
+"""Enable Banking (PSD2) provider — European banks via open banking.
+
+Auth model: RS256 JWT signed with the operator's application private key,
+`kid` header set to the application ID. No client secret, no refresh token.
+Sessions are valid for the consent window the user grants at their bank
+(typically 90–180 days); after that, re-authorization is required.
+
+The flow requires the user to pick a country and bank before the
+authorization URL can be generated, so `get_oauth_url` takes
+`flow_params={"country", "institution_name"}`.
+"""
+from __future__ import annotations
+
+import hashlib
+import logging
+import time
+from datetime import date, datetime, timedelta, timezone
+from decimal import Decimal, InvalidOperation
+from pathlib import Path
+from typing import Any, Optional
+
+import httpx
+from jose import jwt
+
+from app.agents.services.crypto import decrypt, encrypt
+from app.core.config import get_settings
+from app.providers.base import (
+ AccountData,
+ BankProvider,
+ ConnectionData,
+ InstitutionData,
+ InstitutionListData,
+ ProviderUserActionRequired,
+ SessionExpiredError,
+ TransactionData,
+)
+
+logger = logging.getLogger(__name__)
+
+JWT_ISSUER = "enablebanking.com"
+JWT_AUDIENCE = "api.enablebanking.com"
+JWT_LIFETIME_SECONDS = 3500 # under EB's 1h cap; refresh well before
+JWT_CACHE_REFRESH_BEFORE = 600 # re-mint with 10 min buffer
+
+DEFAULT_VALID_UNTIL_DAYS = 180
+DEFAULT_PSU_TYPE = "personal"
+DEFAULT_HISTORY_DAYS = 90
+TRANSACTION_PAGE_LIMIT = 50 # safety cap
+
+
+def _map_cash_account_type(eb_type: Optional[str]) -> str:
+ """Map EB cash_account_type (ISO 20022) to Securo internal type."""
+ if not eb_type:
+ return "checking"
+ mapping = {
+ "CACC": "checking", # current
+ "SVGS": "savings",
+ "CARD": "credit_card",
+ "CASH": "checking",
+ "LOAN": "checking", # we don't model loan accounts yet
+ "OTHR": "checking",
+ }
+ return mapping.get(eb_type.upper(), "checking")
+
+
+def _pick_balance(balances: list[dict]) -> Optional[dict]:
+ """Pick the most useful balance from EB's list (prefer closing booked)."""
+ if not balances:
+ return None
+ priority = ["CLBD", "ITAV", "CLAV", "XPCD", "OPBD", "OPAV"]
+ by_type = {b.get("balance_type") or b.get("type"): b for b in balances if isinstance(b, dict)}
+ for key in priority:
+ if key in by_type:
+ return by_type[key]
+ return balances[0] if isinstance(balances[0], dict) else None
+
+
+def _balance_decimal(balance: Optional[dict]) -> Decimal:
+ if not balance:
+ return Decimal("0")
+ amount = balance.get("balance_amount") or balance.get("amount") or {}
+ try:
+ return Decimal(str(amount.get("amount", "0")))
+ except (InvalidOperation, AttributeError):
+ return Decimal("0")
+
+
+def _balance_currency(balance: Optional[dict], fallback: str) -> str:
+ if not balance:
+ return fallback
+ amount = balance.get("balance_amount") or balance.get("amount") or {}
+ return amount.get("currency") or fallback
+
+
+def _parse_iso_date(value: Optional[str]) -> Optional[date]:
+ if not value:
+ return None
+ try:
+ return date.fromisoformat(value[:10])
+ except ValueError:
+ return None
+
+
+def _join_remittance(value: Any) -> str:
+ if isinstance(value, list):
+ return " ".join(str(v) for v in value if v).strip()
+ return (value or "").strip() if isinstance(value, str) else ""
+
+
+def _txn_fingerprint(account_uid: str, raw: dict) -> str:
+ """Stable id for a booked transaction.
+
+ EB's `entry_reference` is unreliable across providers, so we hash the
+ fields most likely to persist across re-fetches of the same booked txn.
+ Pending → booked transitions deliberately produce a different id; the
+ sync layer's pending↔posted twin matcher handles that.
+ """
+ amount = raw.get("transaction_amount") or {}
+ parts = [
+ account_uid,
+ raw.get("booking_date") or "",
+ raw.get("value_date") or "",
+ str(amount.get("amount") or ""),
+ str(amount.get("currency") or ""),
+ raw.get("credit_debit_indicator") or "",
+ _join_remittance(raw.get("remittance_information"))[:80],
+ ((raw.get("creditor_account") or {}).get("iban") or ""),
+ ((raw.get("debtor_account") or {}).get("iban") or ""),
+ ]
+ digest = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
+ return digest[:32]
+
+
+def _extract_payee(raw: dict, indicator: str, source: str) -> Optional[str]:
+ """Pick a payee name from EB transaction payload.
+
+ DBIT (money out): creditor (the recipient).
+ CRDT (money in): debtor (the sender).
+ """
+ if source == "none":
+ return None
+ creditor = (raw.get("creditor") or {}).get("name") or raw.get("creditor_name")
+ debtor = (raw.get("debtor") or {}).get("name") or raw.get("debtor_name")
+ if source == "description":
+ return None # let description carry the info
+ if indicator == "DBIT":
+ return creditor or debtor
+ return debtor or creditor
+
+
+class EnableBankingProvider(BankProvider):
+ """Enable Banking PSD2 connector."""
+
+ # Cache the JWT across requests to amortize the RS256 signing cost.
+ _cached_token: Optional[str] = None
+ _cached_token_exp: float = 0.0
+ _cached_private_key: Optional[str] = None
+
+ @property
+ def name(self) -> str:
+ return "enable_banking"
+
+ @property
+ def flow_type(self) -> str:
+ return "oauth"
+
+ @property
+ def redirect_uri(self) -> str:
+ return get_settings().enable_banking_oauth_redirect_uri
+
+ # ----- credentials -----
+
+ @classmethod
+ def _load_private_key(cls) -> str:
+ if cls._cached_private_key:
+ return cls._cached_private_key
+ settings = get_settings()
+ key_file = (settings.enable_banking_private_key_file or "").strip()
+ if key_file:
+ cls._cached_private_key = Path(key_file).read_text(encoding="utf-8")
+ return cls._cached_private_key
+ raw = settings.enable_banking_private_key or ""
+ if "\\n" in raw and "\n" not in raw:
+ raw = raw.replace("\\n", "\n")
+ cls._cached_private_key = raw
+ return cls._cached_private_key
+
+ @classmethod
+ def _jwt_token(cls) -> str:
+ now = time.time()
+ if cls._cached_token and now < cls._cached_token_exp - JWT_CACHE_REFRESH_BEFORE:
+ return cls._cached_token
+ settings = get_settings()
+ app_id = settings.enable_banking_app_id
+ if not app_id:
+ raise RuntimeError("ENABLE_BANKING_APP_ID is not configured")
+ private_key = cls._load_private_key()
+ if not private_key:
+ raise RuntimeError("Enable Banking private key is not configured")
+ issued_at = int(now)
+ exp = issued_at + JWT_LIFETIME_SECONDS
+ claims = {
+ "iss": JWT_ISSUER,
+ "aud": JWT_AUDIENCE,
+ "iat": issued_at,
+ "exp": exp,
+ }
+ token = jwt.encode(
+ claims,
+ private_key,
+ algorithm="RS256",
+ headers={"kid": app_id, "typ": "JWT"},
+ )
+ cls._cached_token = token
+ cls._cached_token_exp = exp
+ return token
+
+ # ----- HTTP layer -----
+
+ def _client(self) -> httpx.AsyncClient:
+ settings = get_settings()
+ return httpx.AsyncClient(
+ base_url=settings.enable_banking_api_url.rstrip("/"),
+ headers={
+ "Authorization": f"Bearer {self._jwt_token()}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "User-Agent": "Securo/0.1 (+https://usesecuro.com)",
+ },
+ timeout=30.0,
+ )
+
+ async def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Optional[dict] = None,
+ json_body: Optional[dict] = None,
+ ) -> dict:
+ async with self._client() as client:
+ resp = await client.request(method, path, params=params, json=json_body)
+ if resp.status_code in (401, 410):
+ raise SessionExpiredError(
+ f"Enable Banking returned {resp.status_code} for {path}"
+ )
+ if resp.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ f"Enable Banking {method} {path} → {resp.status_code}: {resp.text[:300]}",
+ request=resp.request,
+ response=resp,
+ )
+ return resp.json()
+
+ # ----- institution listing -----
+
+ async def list_institutions(
+ self, country: Optional[str] = None
+ ) -> InstitutionListData:
+ params: dict[str, Any] = {}
+ if country:
+ params["country"] = country.upper()
+ data = await self._request("GET", "/aspsps", params=params or None)
+ raw_list = data.get("aspsps") or []
+ institutions: list[InstitutionData] = []
+ countries: set[str] = set()
+ for item in raw_list:
+ inst_country = (item.get("country") or "").upper()
+ if inst_country:
+ countries.add(inst_country)
+ institutions.append(
+ InstitutionData(
+ name=item.get("name") or "",
+ display_name=item.get("name") or "",
+ country=inst_country,
+ logo=item.get("logo"),
+ bic=item.get("bic"),
+ psu_types=list(item.get("psu_types") or []),
+ max_consent_days=item.get("maximum_consent_validity"),
+ )
+ )
+ institutions.sort(key=lambda i: (i.country, i.display_name.lower()))
+ return InstitutionListData(
+ countries=sorted(countries),
+ institutions=institutions,
+ )
+
+ # ----- OAuth (authorization) -----
+
+ def _build_auth_payload(
+ self,
+ *,
+ country: str,
+ institution_name: str,
+ redirect_uri: str,
+ state: str,
+ psu_type: str,
+ valid_until_days: int,
+ ) -> dict:
+ valid_until_dt = datetime.now(timezone.utc) + timedelta(days=valid_until_days)
+ # EB wants RFC3339 with a trailing 'Z' for UTC.
+ valid_until = valid_until_dt.replace(microsecond=0).isoformat().replace(
+ "+00:00", "Z"
+ )
+ return {
+ "access": {"valid_until": valid_until},
+ "aspsp": {"name": institution_name, "country": country.upper()},
+ "state": state,
+ "redirect_url": redirect_uri,
+ "psu_type": psu_type,
+ }
+
+ async def get_oauth_url(
+ self,
+ redirect_uri: str,
+ state: str,
+ flow_params: Optional[dict] = None,
+ ) -> str:
+ flow_params = flow_params or {}
+ country = (flow_params.get("country") or "").strip().upper()
+ institution_name = (flow_params.get("institution_name") or "").strip()
+ if not country or not institution_name:
+ raise ValueError(
+ "Enable Banking requires flow_params with 'country' and 'institution_name'"
+ )
+ psu_type = (flow_params.get("psu_type") or DEFAULT_PSU_TYPE).strip()
+ valid_until_days = int(
+ flow_params.get("valid_until_days") or DEFAULT_VALID_UNTIL_DAYS
+ )
+ payload = self._build_auth_payload(
+ country=country,
+ institution_name=institution_name,
+ redirect_uri=redirect_uri,
+ state=state,
+ psu_type=psu_type,
+ valid_until_days=valid_until_days,
+ )
+ data = await self._request("POST", "/auth", json_body=payload)
+ url = data.get("url")
+ if not url:
+ raise RuntimeError("Enable Banking /auth did not return a redirect URL")
+ return url
+
+ async def reauth_url(
+ self,
+ credentials: dict,
+ settings: dict,
+ redirect_uri: str,
+ state: str,
+ ) -> str:
+ stored = (settings or {}).get("flow_params") or {}
+ if not stored.get("country") or not stored.get("institution_name"):
+ raise RuntimeError(
+ "Cannot reauth Enable Banking connection without stored flow_params"
+ )
+ return await self.get_oauth_url(redirect_uri, state, flow_params=stored)
+
+ # ----- session exchange -----
+
+ async def handle_oauth_callback(self, code: str) -> ConnectionData:
+ data = await self._request("POST", "/sessions", json_body={"code": code})
+ session_id = data.get("session_id")
+ if not session_id:
+ raise RuntimeError("Enable Banking /sessions response missing session_id")
+
+ accounts_raw = data.get("accounts")
+ if not accounts_raw:
+ raise ProviderUserActionRequired(
+ "Enable Banking returned no accounts. In restricted mode you must "
+ "pre-link accounts in the Enable Banking portal before connecting.",
+ code="no_accounts_linked",
+ help_url="https://enablebanking.com/",
+ )
+
+ aspsp = data.get("aspsp") or {}
+ institution_name = aspsp.get("name") or "Bank"
+ access = data.get("access") or {}
+ valid_until = access.get("valid_until")
+
+ accounts: list[AccountData] = []
+ for raw_acc in accounts_raw:
+ if isinstance(raw_acc, str):
+ continue # restricted clients can return account IDs as strings
+ accounts.append(await self._build_account(raw_acc))
+
+ encrypted_session = encrypt(session_id) or session_id
+ credentials: dict[str, Any] = {
+ "session_id_enc": encrypted_session,
+ "valid_until": valid_until,
+ "aspsp": {
+ "name": institution_name,
+ "country": aspsp.get("country"),
+ },
+ }
+ return ConnectionData(
+ external_id=session_id,
+ institution_name=institution_name,
+ credentials=credentials,
+ accounts=accounts,
+ )
+
+ async def _build_account(self, raw: dict) -> AccountData:
+ uid = raw.get("uid") or raw.get("account_uid") or ""
+ currency = raw.get("currency") or "EUR"
+ # EB doesn't include balances in the session payload; fetch separately.
+ balance = Decimal("0")
+ try:
+ bal_resp = await self._request("GET", f"/accounts/{uid}/balances")
+ picked = _pick_balance(bal_resp.get("balances") or [])
+ balance = _balance_decimal(picked)
+ currency = _balance_currency(picked, currency)
+ except (httpx.HTTPError, SessionExpiredError) as exc:
+ logger.warning(
+ "Failed to fetch balances for account %s: %s", uid, exc
+ )
+ name = (
+ raw.get("display_name")
+ or raw.get("product")
+ or raw.get("name")
+ or "Account"
+ )
+ return AccountData(
+ external_id=uid,
+ name=name,
+ type=_map_cash_account_type(raw.get("cash_account_type")),
+ balance=balance,
+ currency=currency,
+ )
+
+ # ----- account / transaction fetches -----
+
+ def _session_id(self, credentials: dict) -> str:
+ enc = credentials.get("session_id_enc")
+ if enc:
+ decoded = decrypt(enc)
+ if decoded:
+ return decoded
+ # Backward compat: plaintext during dev.
+ return credentials.get("session_id") or ""
+
+ async def get_accounts(self, credentials: dict) -> list[AccountData]:
+ session_id = self._session_id(credentials)
+ if not session_id:
+ raise SessionExpiredError("Enable Banking session_id missing")
+ data = await self._request("GET", f"/sessions/{session_id}")
+ accounts_raw = data.get("accounts") or []
+ result: list[AccountData] = []
+ for raw_acc in accounts_raw:
+ if isinstance(raw_acc, str):
+ continue
+ result.append(await self._build_account(raw_acc))
+ return result
+
+ async def get_transactions(
+ self,
+ credentials: dict,
+ account_external_id: str,
+ since: Optional[date] = None,
+ payee_source: str = "auto",
+ ) -> list[TransactionData]:
+ _ = self._session_id(credentials) # surface expired credentials early
+ date_from = (since or (date.today() - timedelta(days=DEFAULT_HISTORY_DAYS))).isoformat()
+ date_to = date.today().isoformat()
+ transactions: list[TransactionData] = []
+ continuation_key: Optional[str] = None
+ for _ in range(TRANSACTION_PAGE_LIMIT):
+ params: dict[str, Any] = {"date_from": date_from, "date_to": date_to}
+ if continuation_key:
+ params["continuation_key"] = continuation_key
+ page = await self._request(
+ "GET",
+ f"/accounts/{account_external_id}/transactions",
+ params=params,
+ )
+ for raw_txn, status in self._iter_transactions(page):
+ parsed = self._build_transaction(
+ account_external_id, raw_txn, status, payee_source
+ )
+ if parsed:
+ transactions.append(parsed)
+ continuation_key = page.get("continuation_key") or None
+ if not continuation_key:
+ break
+ return transactions
+
+ @staticmethod
+ def _iter_transactions(page: dict):
+ """Yield (raw_txn, status) tuples handling both nested and flat shapes."""
+ body = page.get("transactions")
+ if isinstance(body, dict):
+ for raw in body.get("booked") or []:
+ yield raw, "posted"
+ for raw in body.get("pending") or []:
+ yield raw, "pending"
+ elif isinstance(body, list):
+ for raw in body:
+ raw_status = (raw.get("status") or "").upper()
+ yield raw, "pending" if raw_status in {"PDNG", "PENDING"} else "posted"
+
+ def _build_transaction(
+ self,
+ account_uid: str,
+ raw: dict,
+ status: str,
+ payee_source: str,
+ ) -> Optional[TransactionData]:
+ amount_obj = raw.get("transaction_amount") or {}
+ try:
+ amount = Decimal(str(amount_obj.get("amount", "0")))
+ except InvalidOperation:
+ return None
+ indicator = (raw.get("credit_debit_indicator") or "").upper()
+ txn_type = "debit" if indicator == "DBIT" else "credit"
+ amount = amount.copy_abs()
+ currency = amount_obj.get("currency") or "EUR"
+ booking = _parse_iso_date(raw.get("booking_date"))
+ value = _parse_iso_date(raw.get("value_date"))
+ txn_date = booking or value
+ if not txn_date:
+ return None
+ description = _join_remittance(raw.get("remittance_information")) or (
+ raw.get("additional_information") or ""
+ )
+ description = description.strip()[:500] or "Transaction"
+ external_id = (raw.get("entry_reference") or "").strip() or _txn_fingerprint(
+ account_uid, raw
+ )
+ return TransactionData(
+ external_id=external_id,
+ description=description,
+ amount=amount,
+ date=txn_date,
+ type=txn_type,
+ currency=currency,
+ status=status,
+ payee=_extract_payee(raw, indicator, payee_source),
+ raw_data=raw,
+ )
+
+ # ----- credential lifecycle -----
+
+ async def refresh_credentials(self, credentials: dict) -> dict:
+ valid_until = credentials.get("valid_until")
+ if valid_until:
+ try:
+ # Accept both RFC3339 with 'Z' and offset forms.
+ normalized = valid_until.replace("Z", "+00:00")
+ expires_at = datetime.fromisoformat(normalized)
+ if expires_at.tzinfo is None:
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
+ if expires_at <= datetime.now(timezone.utc):
+ raise SessionExpiredError(
+ "Enable Banking session expired; user must re-authorize"
+ )
+ except ValueError:
+ pass
+ return credentials
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.py
index 00d2ebd0..95cd55ba 100644
--- a/backend/app/providers/pluggy.py
+++ b/backend/app/providers/pluggy.py
@@ -236,7 +236,12 @@ class PluggyProvider(BankProvider):
data = resp.json()
return ConnectTokenData(access_token=data["accessToken"])
- def get_oauth_url(self, redirect_uri: str, state: str) -> str:
+ async def get_oauth_url(
+ self,
+ redirect_uri: str,
+ state: str,
+ flow_params: Optional[dict] = None,
+ ) -> str:
raise NotImplementedError("Pluggy uses widget flow, not OAuth redirect")
async def handle_oauth_callback(self, code: str) -> ConnectionData:
diff --git a/backend/app/schemas/bank_connection.py b/backend/app/schemas/bank_connection.py
index 2d83d37b..0c6ac636 100644
--- a/backend/app/schemas/bank_connection.py
+++ b/backend/app/schemas/bank_connection.py
@@ -25,6 +25,7 @@ class BankConnectionRead(BankConnectionBase):
class OAuthUrlRequest(BaseModel):
provider: str = "pluggy"
+ flow_params: Optional[dict] = None
class OAuthUrlResponse(BaseModel):
@@ -33,7 +34,28 @@ class OAuthUrlResponse(BaseModel):
class OAuthCallbackRequest(BaseModel):
code: str
- provider: str = "pluggy"
+ state: Optional[str] = None
+ provider: Optional[str] = None
+
+
+class ReauthUrlResponse(BaseModel):
+ url: str
+
+
+class InstitutionRead(BaseModel):
+ name: str
+ display_name: str
+ country: str
+ logo: Optional[str] = None
+ bic: Optional[str] = None
+ psu_types: list[str] = []
+ max_consent_days: Optional[int] = None
+ max_history_days: Optional[int] = None
+
+
+class InstitutionListResponse(BaseModel):
+ countries: list[str]
+ institutions: list[InstitutionRead]
class ConnectTokenRequest(BaseModel):
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 609b3e1b..4ec8cc35 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -20,7 +20,12 @@ from app.models.payee import Payee, PayeeMapping
from app.models.transaction import Transaction
from app.models.user import User
from app.providers import get_provider
-from app.providers.base import HoldingData
+from app.providers.base import (
+ HoldingData,
+ ProviderUserActionRequired,
+ SessionExpiredError,
+)
+from app.services import oauth_state
from app.services import admin_service
from app.services.account_service import sync_opening_balance_for_connected_account
from app.services.asset_group_service import ensure_group_for_connection
@@ -352,10 +357,76 @@ async def get_connection(
return result.scalar_one_or_none()
-def get_oauth_url(provider_name: str, user_id: uuid.UUID) -> str:
+async def get_oauth_url(
+ provider_name: str,
+ user_id: uuid.UUID,
+ workspace_id: uuid.UUID,
+ flow_params: Optional[dict] = None,
+ reconnect_connection_id: Optional[uuid.UUID] = None,
+) -> str:
provider = get_provider(provider_name)
- state = str(user_id)
- return provider.get_oauth_url(settings.pluggy_oauth_redirect_uri, state)
+ state = await oauth_state.store_state(
+ {
+ "user_id": str(user_id),
+ "workspace_id": str(workspace_id),
+ "provider": provider_name,
+ "flow_params": flow_params or {},
+ "reconnect_connection_id": (
+ str(reconnect_connection_id) if reconnect_connection_id else None
+ ),
+ }
+ )
+ return await provider.get_oauth_url(provider.redirect_uri, state, flow_params)
+
+
+async def get_reauth_url(
+ session: AsyncSession,
+ connection_id: uuid.UUID,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+) -> str:
+ connection = await get_connection(session, connection_id, workspace_id)
+ if not connection:
+ raise ValueError("Connection not found")
+ provider = get_provider(connection.provider)
+ state = await oauth_state.store_state(
+ {
+ "user_id": str(user_id),
+ "workspace_id": str(workspace_id),
+ "provider": connection.provider,
+ "flow_params": (connection.settings or {}).get("flow_params") or {},
+ "reconnect_connection_id": str(connection.id),
+ }
+ )
+ return await provider.reauth_url(
+ connection.credentials or {},
+ connection.settings or {},
+ provider.redirect_uri,
+ state,
+ )
+
+
+async def list_provider_institutions(
+ provider_name: str, country: Optional[str] = None
+) -> dict:
+ provider = get_provider(provider_name)
+ data = await provider.list_institutions(country)
+ return {
+ "countries": data.countries,
+ "institutions": [
+ {
+ "name": i.name,
+ "display_name": i.display_name,
+ "country": i.country,
+ "logo": i.logo,
+ "bic": i.bic,
+ "psu_types": i.psu_types,
+ "max_consent_days": i.max_consent_days,
+ "max_history_days": i.max_history_days,
+ }
+ for i in data.institutions
+ ],
+ }
async def create_connect_token(
@@ -397,11 +468,44 @@ async def handle_oauth_callback(
workspace_id: uuid.UUID,
user_id: uuid.UUID,
code: str,
- provider_name: str,
+ provider_name: Optional[str] = None,
+ state: Optional[str] = None,
) -> BankConnection:
+ state_payload: dict = {}
+ if state:
+ consumed = await oauth_state.consume_state(state)
+ if not consumed:
+ raise ValueError("OAuth state is invalid or expired")
+ # The state is authoritative — caller-supplied provider_name is a hint.
+ if consumed.get("user_id") != str(user_id):
+ raise ValueError("OAuth state user does not match authenticated user")
+ if consumed.get("workspace_id") != str(workspace_id):
+ raise ValueError("OAuth state workspace does not match active workspace")
+ state_payload = consumed
+ provider_name = consumed.get("provider") or provider_name
+ if not provider_name:
+ raise ValueError("OAuth callback missing provider")
+
provider = get_provider(provider_name)
connection_data = await provider.handle_oauth_callback(code)
+ reconnect_id = state_payload.get("reconnect_connection_id")
+ if reconnect_id:
+ existing = await session.get(BankConnection, uuid.UUID(reconnect_id))
+ if not existing or existing.workspace_id != workspace_id:
+ raise ValueError("Reconnect target connection not found")
+ existing.external_id = connection_data.external_id
+ existing.institution_name = (
+ connection_data.institution_name or existing.institution_name
+ )
+ existing.credentials = connection_data.credentials
+ existing.status = "active"
+ # Re-sync from current data on next sync cycle.
+ existing.last_sync_at = None
+ await session.commit()
+ await session.refresh(existing)
+ return existing
+
connection = BankConnection(
workspace_id=workspace_id,
user_id=user_id,
@@ -409,6 +513,7 @@ async def handle_oauth_callback(
external_id=connection_data.external_id,
institution_name=connection_data.institution_name,
credentials=connection_data.credentials,
+ settings={"flow_params": state_payload.get("flow_params") or {}},
status="active",
)
session.add(connection)
@@ -1236,6 +1341,21 @@ async def sync_connection(
await session.refresh(connection)
return connection, merged_count
+ except SessionExpiredError:
+ # Provider consent expired — distinct from a generic error so the UI
+ # can show a clearer "reauthorize" prompt.
+ await session.rollback()
+ async with session.begin():
+ conn = await session.get(BankConnection, connection_id)
+ if conn:
+ conn.status = "expired"
+ raise
+ except ProviderUserActionRequired:
+ # User must act in the provider's portal (e.g. EB restricted-mode
+ # account linking). Don't mark the connection errored — propagate
+ # so the API layer can surface the specific code to the UI.
+ await session.rollback()
+ raise
except Exception:
# Mark connection as errored so UI shows reconnect banner
await session.rollback()
diff --git a/backend/app/services/oauth_state.py b/backend/app/services/oauth_state.py
new file mode 100644
index 00000000..29466846
--- /dev/null
+++ b/backend/app/services/oauth_state.py
@@ -0,0 +1,48 @@
+"""OAuth state store backed by Redis.
+
+When an OAuth-redirect provider (e.g. Enable Banking) hands the browser
+off to a bank consent page, the browser comes back with `?code=...&state=...`.
+We need to know which workspace/user/provider that flow belonged to and
+what flow params (country, institution) were chosen. Stash that here,
+keyed by an unguessable token, and consume it exactly once on callback.
+"""
+from __future__ import annotations
+
+import json
+import secrets
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from app.core.redis import get_redis
+
+STATE_KEY_PREFIX = "oauth_state:"
+STATE_TTL_SECONDS = 600 # 10 minutes
+
+
+async def store_state(payload: dict[str, Any]) -> str:
+ """Persist OAuth flow context and return an opaque state token.
+
+ The caller embeds the token in the OAuth `state` query param; the
+ provider echoes it back on redirect.
+ """
+ state = secrets.token_urlsafe(32)
+ body = dict(payload)
+ body.setdefault("created_at", datetime.now(timezone.utc).isoformat())
+ redis = await get_redis()
+ await redis.set(f"{STATE_KEY_PREFIX}{state}", json.dumps(body), ex=STATE_TTL_SECONDS)
+ return state
+
+
+async def consume_state(state: str) -> Optional[dict[str, Any]]:
+ """One-shot retrieval — deletes the key in the same round trip."""
+ if not state:
+ return None
+ redis = await get_redis()
+ key = f"{STATE_KEY_PREFIX}{state}"
+ raw = await redis.getdel(key)
+ if raw is None:
+ return None
+ try:
+ return json.loads(raw)
+ except json.JSONDecodeError:
+ return None
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index 34a934ff..e2c266ec 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -58,6 +58,7 @@ omit = [
"app/worker.py",
"app/tasks/*",
"app/providers/pluggy.py",
+ "app/providers/enable_banking.py",
"app/providers/market_price.py",
]
diff --git a/backend/tests/test_connections_api.py b/backend/tests/test_connections_api.py
index 30e94f28..d3d22c40 100644
--- a/backend/tests/test_connections_api.py
+++ b/backend/tests/test_connections_api.py
@@ -16,9 +16,13 @@ async def test_list_providers(client: AsyncClient, auth_headers):
response = await client.get("/api/connections/providers", headers=auth_headers)
assert response.status_code == 200
data = response.json()
- assert len(data["providers"]) == 1
- assert data["providers"][0]["name"] == "pluggy"
- assert data["providers"][0]["configured"] is False
+ by_name = {p["name"]: p for p in data["providers"]}
+ assert "pluggy" in by_name
+ assert by_name["pluggy"]["configured"] is False
+ assert by_name["pluggy"]["flow_type"] == "widget"
+ assert "enable_banking" in by_name
+ assert by_name["enable_banking"]["flow_type"] == "oauth"
+ assert by_name["enable_banking"]["requires_institution_select"] is True
@pytest.mark.asyncio
diff --git a/backend/tests/test_oauth_state.py b/backend/tests/test_oauth_state.py
new file mode 100644
index 00000000..e1dc726b
--- /dev/null
+++ b/backend/tests/test_oauth_state.py
@@ -0,0 +1,65 @@
+"""Tests for the Redis-backed OAuth state store."""
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from app.services import oauth_state
+
+
+class _FakeRedis:
+ """In-process Redis stand-in supporting set/getdel."""
+
+ def __init__(self) -> None:
+ self.store: dict[str, str] = {}
+
+ async def set(self, key: str, value: str, ex: int | None = None) -> None:
+ self.store[key] = value
+
+ async def getdel(self, key: str) -> str | None:
+ return self.store.pop(key, None)
+
+
+def fake_redis():
+ redis = _FakeRedis()
+ with patch.object(oauth_state, "get_redis", AsyncMock(return_value=redis)):
+ yield redis
+
+
+async def test_store_then_consume_round_trips(fake_redis):
+ payload = {
+ "user_id": "u1",
+ "workspace_id": "w1",
+ "provider": "enable_banking",
+ "flow_params": {"country": "DE", "institution_name": "Revolut"},
+ }
+ state = await oauth_state.store_state(payload)
+ assert isinstance(state, str) and len(state) > 20
+
+ consumed = await oauth_state.consume_state(state)
+ assert consumed is not None
+ assert consumed["user_id"] == "u1"
+ assert consumed["flow_params"]["country"] == "DE"
+ assert "created_at" in consumed
+
+
+async def test_consume_is_one_shot(fake_redis):
+ state = await oauth_state.store_state({"user_id": "u"})
+ first = await oauth_state.consume_state(state)
+ second = await oauth_state.consume_state(state)
+ assert first is not None
+ assert second is None
+
+
+async def test_consume_unknown_state_returns_none(fake_redis):
+ assert await oauth_state.consume_state("does-not-exist") is None
+
+
+async def test_consume_empty_state_returns_none(fake_redis):
+ assert await oauth_state.consume_state("") is None
diff --git a/backend/tests/test_providers_enable_banking.py b/backend/tests/test_providers_enable_banking.py
new file mode 100644
index 00000000..9710be78
--- /dev/null
+++ b/backend/tests/test_providers_enable_banking.py
@@ -0,0 +1,396 @@
+"""Unit tests for the Enable Banking provider.
+
+Covers: JWT signing/claims, transaction fingerprint stability, account-type
+mapping, nested vs flat transaction page shapes, restricted-mode handling.
+HTTP is mocked end-to-end via httpx.MockTransport.
+"""
+from __future__ import annotations
+
+from datetime import date, datetime, timedelta, timezone
+from decimal import Decimal
+from unittest.mock import patch
+
+import httpx
+import pytest
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from jose import jwt
+
+from app.providers.base import ProviderUserActionRequired, SessionExpiredError
+from app.providers.enable_banking import (
+ EnableBankingProvider,
+ _map_cash_account_type,
+ _txn_fingerprint,
+)
+
+
+def _rsa_pem() -> tuple[str, str]:
+ """Generate an in-memory RSA keypair and return PEM-encoded (private, public)."""
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ private_pem = key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode("utf-8")
+ public_pem = key.public_key().public_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
+ ).decode("utf-8")
+ return private_pem, public_pem
+
+
+def eb_keys(monkeypatch):
+ """Configure EB env vars with a fresh keypair and reset the provider cache."""
+ private_pem, public_pem = _rsa_pem()
+ monkeypatch.setenv("ENABLE_BANKING_APP_ID", "test-app-id-123")
+ monkeypatch.setenv("ENABLE_BANKING_PRIVATE_KEY", private_pem)
+ # Ensure the inline key wins over any file path the host env may have set.
+ monkeypatch.setenv("ENABLE_BANKING_PRIVATE_KEY_FILE", "")
+ # Force settings re-read.
+ from app.core.config import get_settings
+
+ get_settings.cache_clear()
+ EnableBankingProvider._cached_token = None
+ EnableBankingProvider._cached_token_exp = 0.0
+ EnableBankingProvider._cached_private_key = None
+ yield public_pem
+ get_settings.cache_clear()
+
+
+# ----- JWT signing -----
+
+
+def test_jwt_token_has_expected_claims_and_kid(eb_keys):
+ public_pem = eb_keys
+ token = EnableBankingProvider._jwt_token()
+
+ header = jwt.get_unverified_header(token)
+ assert header["alg"] == "RS256"
+ assert header["kid"] == "test-app-id-123"
+ assert header["typ"] == "JWT"
+
+ claims = jwt.decode(
+ token, public_pem, algorithms=["RS256"], audience="api.enablebanking.com"
+ )
+ assert claims["iss"] == "enablebanking.com"
+ assert claims["aud"] == "api.enablebanking.com"
+ assert isinstance(claims["iat"], int)
+ assert isinstance(claims["exp"], int)
+ # Expiry within the next hour.
+ assert claims["exp"] - claims["iat"] <= 3600
+
+
+def test_jwt_token_cached_across_calls(eb_keys):
+ a = EnableBankingProvider._jwt_token()
+ b = EnableBankingProvider._jwt_token()
+ assert a == b
+
+
+# ----- pure helpers -----
+
+
+def test_cash_account_type_mapping():
+ assert _map_cash_account_type("CACC") == "checking"
+ assert _map_cash_account_type("SVGS") == "savings"
+ assert _map_cash_account_type("CARD") == "credit_card"
+ assert _map_cash_account_type(None) == "checking"
+ assert _map_cash_account_type("UNKNOWN_TYPE") == "checking"
+
+
+def test_txn_fingerprint_stable_for_same_payload():
+ raw = {
+ "transaction_amount": {"amount": "12.34", "currency": "EUR"},
+ "credit_debit_indicator": "DBIT",
+ "booking_date": "2026-05-20",
+ "value_date": "2026-05-20",
+ "remittance_information": ["Coffee shop"],
+ "creditor_account": {"iban": "DE89370400440532013000"},
+ }
+ fp1 = _txn_fingerprint("acc-uid-1", raw)
+ fp2 = _txn_fingerprint("acc-uid-1", dict(raw))
+ assert fp1 == fp2
+ assert len(fp1) == 32
+
+
+def test_txn_fingerprint_differs_on_amount_change():
+ base = {
+ "transaction_amount": {"amount": "12.34", "currency": "EUR"},
+ "credit_debit_indicator": "DBIT",
+ "booking_date": "2026-05-20",
+ "remittance_information": ["X"],
+ }
+ other = dict(base)
+ other["transaction_amount"] = {"amount": "12.35", "currency": "EUR"}
+ assert _txn_fingerprint("acc", base) != _txn_fingerprint("acc", other)
+
+
+# ----- HTTP-driven parsing via httpx.MockTransport -----
+
+
+def _mock_eb_transport(handler):
+ return httpx.MockTransport(handler)
+
+
+def _patch_client(provider: EnableBankingProvider, handler):
+ """Replace _client() so requests hit our MockTransport."""
+ transport = _mock_eb_transport(handler)
+
+ def fake_client():
+ return httpx.AsyncClient(
+ base_url="https://api.enablebanking.com",
+ transport=transport,
+ headers={"Authorization": "Bearer test-jwt"},
+ )
+
+ return patch.object(provider, "_client", side_effect=fake_client)
+
+
+async def test_list_institutions_maps_and_dedupes_countries(eb_keys):
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/aspsps"
+ return httpx.Response(
+ 200,
+ json={
+ "aspsps": [
+ {
+ "name": "Revolut",
+ "country": "DE",
+ "logo": "https://l/revolut.png",
+ "bic": "REVOLT21",
+ "psu_types": ["personal"],
+ "maximum_consent_validity": 180,
+ },
+ {"name": "Sparkasse", "country": "DE"},
+ {"name": "BNP Paribas", "country": "FR"},
+ ]
+ },
+ )
+
+ with _patch_client(provider, handler):
+ data = await provider.list_institutions()
+
+ assert data.countries == ["DE", "FR"]
+ names = [(i.country, i.name) for i in data.institutions]
+ assert ("DE", "Revolut") in names
+ assert ("FR", "BNP Paribas") in names
+ revolut = next(i for i in data.institutions if i.name == "Revolut")
+ assert revolut.max_consent_days == 180
+ assert revolut.psu_types == ["personal"]
+
+
+async def test_get_oauth_url_returns_consent_url(eb_keys):
+ provider = EnableBankingProvider()
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/auth"
+ body = request.read().decode()
+ import json as _json
+
+ captured.update(_json.loads(body))
+ return httpx.Response(
+ 200,
+ json={
+ "url": "https://consent.enablebanking.com/abc",
+ "authorization_id": "auth-1",
+ "psu_id_hash": "hash-x",
+ },
+ )
+
+ with _patch_client(provider, handler):
+ url = await provider.get_oauth_url(
+ "https://app.example.com/oauth/callback",
+ "state-xyz",
+ flow_params={"country": "de", "institution_name": "Revolut"},
+ )
+ assert url == "https://consent.enablebanking.com/abc"
+ assert captured["aspsp"] == {"name": "Revolut", "country": "DE"}
+ assert captured["redirect_url"] == "https://app.example.com/oauth/callback"
+ assert captured["state"] == "state-xyz"
+ assert captured["psu_type"] == "personal"
+ assert "Z" in captured["access"]["valid_until"]
+
+
+async def test_get_oauth_url_rejects_missing_flow_params(eb_keys):
+ provider = EnableBankingProvider()
+ with pytest.raises(ValueError):
+ await provider.get_oauth_url(
+ "https://x/cb", "s", flow_params={"country": "DE"}
+ )
+
+
+async def test_handle_oauth_callback_restricted_mode_raises(eb_keys):
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/sessions"
+ return httpx.Response(
+ 200,
+ json={
+ "session_id": "sess-1",
+ "accounts": None,
+ "aspsp": {"name": "Revolut", "country": "DE"},
+ "access": {"valid_until": "2026-12-01T00:00:00Z"},
+ },
+ )
+
+ with _patch_client(provider, handler):
+ with pytest.raises(ProviderUserActionRequired) as exc:
+ await provider.handle_oauth_callback("code-abc")
+ assert exc.value.code == "no_accounts_linked"
+
+
+async def test_handle_oauth_callback_builds_connection_data(eb_keys):
+ provider = EnableBankingProvider()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path == "/sessions":
+ return httpx.Response(
+ 200,
+ json={
+ "session_id": "sess-2",
+ "accounts": [
+ {
+ "uid": "acc-uid-1",
+ "currency": "EUR",
+ "display_name": "Main",
+ "cash_account_type": "CACC",
+ }
+ ],
+ "aspsp": {"name": "Revolut", "country": "DE"},
+ "access": {"valid_until": "2026-12-01T00:00:00Z"},
+ },
+ )
+ if path == "/accounts/acc-uid-1/balances":
+ return httpx.Response(
+ 200,
+ json={
+ "balances": [
+ {
+ "balance_type": "CLBD",
+ "balance_amount": {"amount": "123.45", "currency": "EUR"},
+ }
+ ]
+ },
+ )
+ return httpx.Response(404)
+
+ with _patch_client(provider, handler):
+ conn = await provider.handle_oauth_callback("code-abc")
+ assert conn.external_id == "sess-2"
+ assert conn.institution_name == "Revolut"
+ assert len(conn.accounts) == 1
+ acc = conn.accounts[0]
+ assert acc.external_id == "acc-uid-1"
+ assert acc.type == "checking"
+ assert acc.balance == Decimal("123.45")
+ assert acc.currency == "EUR"
+ # session_id must NOT appear in credentials in plaintext.
+ assert "session_id_enc" in conn.credentials
+ assert conn.credentials.get("session_id") is None
+
+
+async def test_get_transactions_parses_nested_and_flat_shapes(eb_keys):
+ """Both `transactions:{booked,pending}` and flat list must produce the
+ same internal TransactionData list."""
+ provider = EnableBankingProvider()
+
+ nested_page = {
+ "transactions": {
+ "booked": [
+ {
+ "entry_reference": "ref-1",
+ "transaction_amount": {"amount": "10.00", "currency": "EUR"},
+ "credit_debit_indicator": "DBIT",
+ "booking_date": "2026-05-10",
+ "remittance_information": ["Groceries"],
+ },
+ ],
+ "pending": [
+ {
+ "transaction_amount": {"amount": "5.50", "currency": "EUR"},
+ "credit_debit_indicator": "CRDT",
+ "booking_date": "2026-05-11",
+ "remittance_information": ["Refund"],
+ },
+ ],
+ },
+ "continuation_key": "",
+ }
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path == "/accounts/acc-1/transactions"
+ return httpx.Response(200, json=nested_page)
+
+ credentials = {"session_id_enc": None, "session_id": "sess-x", "valid_until": "2099-01-01T00:00:00Z"}
+ with _patch_client(provider, handler):
+ nested = await provider.get_transactions(credentials, "acc-1", date(2026, 5, 1))
+
+ assert len(nested) == 2
+ debit = next(t for t in nested if t.type == "debit")
+ assert debit.amount == Decimal("10.00")
+ assert debit.status == "posted"
+ assert debit.external_id == "ref-1"
+ credit = next(t for t in nested if t.type == "credit")
+ assert credit.status == "pending"
+
+ flat_page = {
+ "transactions": [
+ {
+ "status": "BOOK",
+ "transaction_amount": {"amount": "10.00", "currency": "EUR"},
+ "credit_debit_indicator": "DBIT",
+ "booking_date": "2026-05-10",
+ "remittance_information": ["Groceries"],
+ },
+ {
+ "status": "PDNG",
+ "transaction_amount": {"amount": "5.50", "currency": "EUR"},
+ "credit_debit_indicator": "CRDT",
+ "booking_date": "2026-05-11",
+ "remittance_information": ["Refund"],
+ },
+ ],
+ "continuation_key": "",
+ }
+
+ def handler2(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=flat_page)
+
+ with _patch_client(provider, handler2):
+ flat = await provider.get_transactions(credentials, "acc-1", date(2026, 5, 1))
+
+ assert len(flat) == 2
+ assert sorted(t.type for t in flat) == sorted(t.type for t in nested)
+ assert {t.status for t in flat} == {"posted", "pending"}
+
+
+async def test_refresh_credentials_expired_raises(eb_keys):
+ provider = EnableBankingProvider()
+ expired = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat().replace(
+ "+00:00", "Z"
+ )
+ with pytest.raises(SessionExpiredError):
+ await provider.refresh_credentials({"valid_until": expired})
+
+
+async def test_refresh_credentials_valid_passes(eb_keys):
+ provider = EnableBankingProvider()
+ future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat().replace(
+ "+00:00", "Z"
+ )
+ creds = {"valid_until": future, "session_id_enc": "enc"}
+ out = await provider.refresh_credentials(creds)
+ assert out is creds
diff --git a/docker-compose.yml b/docker-compose.yml
index 49c954a2..df7e29d5 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -8,6 +8,10 @@ x-backend-env: &backend-env
PLUGGY_CLIENT_ID: ${PLUGGY_CLIENT_ID:-}
PLUGGY_CLIENT_SECRET: ${PLUGGY_CLIENT_SECRET:-}
PLUGGY_OAUTH_REDIRECT_URI: http://localhost:${FRONTEND_PORT:-3000}/oauth/callback
+ ENABLE_BANKING_APP_ID: ${ENABLE_BANKING_APP_ID:-}
+ ENABLE_BANKING_PRIVATE_KEY_FILE: ${ENABLE_BANKING_PRIVATE_KEY_FILE:-/app/secrets/enable_banking_private.pem}
+ ENABLE_BANKING_API_URL: ${ENABLE_BANKING_API_URL:-https://api.enablebanking.com}
+ ENABLE_BANKING_OAUTH_REDIRECT_URI: ${ENABLE_BANKING_OAUTH_REDIRECT_URI:-http://localhost:${FRONTEND_PORT:-3000}/oauth/callback}
REDIS_URL: redis://redis:6379/0
OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}
FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}
@@ -44,6 +48,7 @@ x-backend-base: &backend-base
redis: { condition: service_healthy }
volumes:
- ./backend:/app
+ - ./secrets:/app/secrets:ro
- attachments:/app/data/attachments
- agent_knowledge:/app/data/agent_knowledge
- agent_embedding_models:/app/data/embedding_models
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 2e87f869..d7d6c900 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -33,6 +33,7 @@ const AgentsListPage = lazy(() => import('@/pages/agents-list'))
const AgentDetailPage = lazy(() => import('@/pages/agent-detail'))
const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))
const WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))
+const OAuthCallbackPage = lazy(() => import('@/pages/oauth-callback'))
const queryClient = new QueryClient({
defaultOptions: {
@@ -74,6 +75,8 @@ function App() {
<Route path="/transactions" element={<TransactionsPage />} />
<Route path="/accounts" element={<AccountsPage />} />
<Route path="/accounts/:id" element={<AccountDetailPage />} />
+ <Route path="/oauth/callback" element={<OAuthCallbackPage />} />
+ <Route path="/enable-banking" element={<OAuthCallbackPage />} />
<Route path="/import" element={<ImportPage />} />
<Route path="/rules" element={<RulesPage />} />
<Route path="/categories" element={<CategoriesPage />} />
diff --git a/frontend/src/components/connector-select-dialog.tsx b/frontend/src/components/connector-select-dialog.tsx
index 08a4d4cc..692fc96b 100644
--- a/frontend/src/components/connector-select-dialog.tsx
+++ b/frontend/src/components/connector-select-dialog.tsx
@@ -9,18 +9,19 @@ import {
} from '@/components/ui/dialog'
import { Building2 } from 'lucide-react'
-interface Provider {
+export interface Provider {
name: string
display_name: string
description: string
flow_type: string
configured: boolean
+ requires_institution_select?: boolean
}
interface ConnectorSelectDialogProps {
open: boolean
onClose: () => void
- onSelect: (providerName: string) => void
+ onSelect: (provider: Provider) => void
}
export function ConnectorSelectDialog({ open, onClose, onSelect }: ConnectorSelectDialogProps) {
@@ -62,7 +63,7 @@ export function ConnectorSelectDialog({ open, onClose, onSelect }: ConnectorSele
key={p.name}
disabled={!p.configured}
onClick={() => {
- onSelect(p.name)
+ onSelect(p)
onClose()
}}
className={`w-full flex items-start gap-3 rounded-lg border p-4 text-left transition-colors ${
diff --git a/frontend/src/components/oauth-connect-dialog.tsx b/frontend/src/components/oauth-connect-dialog.tsx
new file mode 100644
index 00000000..aab76934
--- /dev/null
+++ b/frontend/src/components/oauth-connect-dialog.tsx
@@ -0,0 +1,221 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { connections } from '@/lib/api'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Building2, ChevronLeft, Globe } from 'lucide-react'
+import { toast } from 'sonner'
+
+type Institution = {
+ name: string
+ display_name: string
+ country: string
+ logo?: string | null
+}
+
+interface OAuthConnectDialogProps {
+ open: boolean
+ onClose: () => void
+ provider: string
+}
+
+const LAST_COUNTRY_KEY = 'securo:lastOAuthCountry'
+
+const REGION_NAMES: Intl.DisplayNames | null = (() => {
+ try {
+ return new Intl.DisplayNames(navigator.language || 'en', { type: 'region' })
+ } catch {
+ return null
+ }
+})()
+
+function countryLabel(code: string): string {
+ if (!REGION_NAMES) return code
+ return REGION_NAMES.of(code) || code
+}
+
+export function OAuthConnectDialog({ open, onClose, provider }: OAuthConnectDialogProps) {
+ const { t } = useTranslation()
+ const [step, setStep] = useState<'country' | 'bank'>('country')
+ const [country, setCountry] = useState<string | null>(null)
+ const [countries, setCountries] = useState<string[]>([])
+ const [institutions, setInstitutions] = useState<Institution[]>([])
+ const [loading, setLoading] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [redirecting, setRedirecting] = useState(false)
+
+ // Reset when dialog opens.
+ useEffect(() => {
+ if (!open) return
+ setStep('country')
+ setCountry(null)
+ setInstitutions([])
+ setError(null)
+ setRedirecting(false)
+ setLoading(true)
+ connections
+ .listInstitutions(provider)
+ .then((data) => {
+ setCountries(data.countries)
+ const stored = localStorage.getItem(LAST_COUNTRY_KEY)
+ if (stored && data.countries.includes(stored)) {
+ setCountry(stored)
+ setStep('bank')
+ }
+ })
+ .catch(() => setError(t('accounts.loadingInstitutionsError')))
+ .finally(() => setLoading(false))
+ }, [open, provider, t])
+
+ // Load banks when a country is picked.
+ useEffect(() => {
+ if (!open || !country || step !== 'bank') return
+ setLoading(true)
+ setError(null)
+ connections
+ .listInstitutions(provider, country)
+ .then((data) => setInstitutions(data.institutions))
+ .catch(() => setError(t('accounts.loadingInstitutionsError')))
+ .finally(() => setLoading(false))
+ }, [open, provider, country, step, t])
+
+ const sortedCountries = useMemo(
+ () =>
+ [...countries].sort((a, b) =>
+ countryLabel(a).localeCompare(countryLabel(b)),
+ ),
+ [countries],
+ )
+
+ const handleCountrySelect = (code: string) => {
+ setCountry(code)
+ localStorage.setItem(LAST_COUNTRY_KEY, code)
+ setStep('bank')
+ }
+
+ const handleBankSelect = async (institution: Institution) => {
+ if (!country) return
+ setRedirecting(true)
+ try {
+ const url = await connections.getOAuthUrl(provider, {
+ country,
+ institution_name: institution.name,
+ })
+ window.location.assign(url)
+ } catch (e) {
+ setRedirecting(false)
+ const message = e instanceof Error ? e.message : String(e)
+ toast.error(message || t('accounts.connectError'))
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && !redirecting && onClose()}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ {step === 'bank' && (
+ <button
+ onClick={() => setStep('country')}
+ className="text-muted-foreground hover:text-foreground"
+ aria-label={t('accounts.back')}
+ >
+ <ChevronLeft size={18} />
+ </button>
+ )}
+ {step === 'country' ? t('accounts.selectCountry') : t('accounts.selectBank')}
+ </DialogTitle>
+ <p className="text-sm text-muted-foreground">
+ {step === 'country'
+ ? t('accounts.selectCountryDesc')
+ : t('accounts.selectBankDesc')}
+ </p>
+ </DialogHeader>
+
+ {redirecting ? (
+ <div className="py-12 flex flex-col items-center gap-3">
+ <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
+ <p className="text-sm text-muted-foreground">{t('accounts.redirecting')}</p>
+ </div>
+ ) : loading ? (
+ <div className="flex justify-center py-8">
+ <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
+ </div>
+ ) : error ? (
+ <div className="py-8 text-center text-sm text-destructive">{error}</div>
+ ) : step === 'country' ? (
+ <div className="space-y-1 pt-2 max-h-[60vh] overflow-y-auto">
+ {sortedCountries.length === 0 ? (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ {t('accounts.noInstitutionsFound')}
+ </p>
+ ) : (
+ sortedCountries.map((code) => (
+ <button
+ key={code}
+ onClick={() => handleCountrySelect(code)}
+ className="w-full flex items-center gap-3 rounded-lg border border-border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50"
+ >
+ <div className="w-8 h-8 rounded-md bg-muted flex items-center justify-center shrink-0">
+ <Globe size={14} className="text-muted-foreground" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-foreground">{countryLabel(code)}</p>
+ <p className="text-xs text-muted-foreground">{code}</p>
+ </div>
+ </button>
+ ))
+ )}
+ </div>
+ ) : (
+ <div className="space-y-1 pt-2 max-h-[60vh] overflow-y-auto">
+ {institutions.length === 0 ? (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ {t('accounts.noInstitutionsFound')}
+ </p>
+ ) : (
+ institutions.map((inst) => (
+ <button
+ key={`${inst.country}-${inst.name}`}
+ onClick={() => handleBankSelect(inst)}
+ className="w-full flex items-center gap-3 rounded-lg border border-border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50"
+ >
+ <div className="w-8 h-8 rounded-md bg-muted overflow-hidden flex items-center justify-center shrink-0">
+ {inst.logo ? (
+ <img
+ src={inst.logo}
+ alt=""
+ className="w-full h-full object-contain"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = 'none'
+ }}
+ />
+ ) : (
+ <Building2 size={14} className="text-muted-foreground" />
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-foreground truncate">
+ {inst.display_name}
+ </p>
+ </div>
+ </button>
+ ))
+ )}
+ <div className="pt-2">
+ <Button variant="ghost" size="sm" onClick={() => setStep('country')}>
+ <ChevronLeft size={14} className="mr-1" />
+ {t('accounts.back')}
+ </Button>
+ </div>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index dc6050a8..cccfa2b6 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -230,7 +230,7 @@ export const connections = {
const { data } = await api.get('/connections')
return data
},
- getProviders: async (): Promise<{ name: string; display_name: string; description: string; flow_type: string; configured: boolean }[]> => {
+ getProviders: async (): Promise<{ name: string; display_name: string; description: string; flow_type: string; configured: boolean; requires_institution_select?: boolean }[]> => {
const { data } = await api.get('/connections/providers')
return data.providers
},
@@ -238,14 +238,39 @@ export const connections = {
const { data } = await api.post('/connections/connect-token', { provider })
return data.access_token
},
- getOAuthUrl: async (provider: string): Promise<string> => {
- const { data } = await api.post('/connections/oauth/url', { provider })
+ getOAuthUrl: async (provider: string, flow_params?: Record<string, unknown>): Promise<string> => {
+ const { data } = await api.post('/connections/oauth/url', { provider, flow_params })
return data.url
},
- handleCallback: async (code: string, provider: string): Promise<BankConnection> => {
- const { data } = await api.post('/connections/oauth/callback', { code, provider })
+ listInstitutions: async (
+ provider: string,
+ country?: string,
+ ): Promise<{
+ countries: string[]
+ institutions: {
+ name: string
+ display_name: string
+ country: string
+ logo?: string | null
+ bic?: string | null
+ psu_types: string[]
+ max_consent_days?: number | null
+ max_history_days?: number | null
+ }[]
+ }> => {
+ const { data } = await api.get(`/connections/${provider}/institutions`, {
+ params: country ? { country } : undefined,
+ })
+ return data
+ },
+ handleCallback: async (code: string, provider: string, state?: string): Promise<BankConnection> => {
+ const { data } = await api.post('/connections/oauth/callback', { code, provider, state })
return data
},
+ getReauthUrl: async (connectionId: string): Promise<string> => {
+ const { data } = await api.post(`/connections/${connectionId}/oauth/reauth-url`)
+ return data.url
+ },
sync: async (id: string): Promise<BankConnection> => {
const { data } = await api.post(`/connections/${id}/sync`)
return data
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index c269bfce..b38d6ed6 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -486,9 +486,33 @@
"selectConnectorDesc": "Choose a bank connection provider",
"connectorNotConfigured": "This connector requires configuration. Set up the required credentials to enable it.",
"noConnectorsAvailable": "No bank connectors available",
+ "selectCountry": "Select country",
+ "selectCountryDesc": "Choose the country your bank is in",
+ "selectBank": "Select bank",
+ "selectBankDesc": "Choose your bank from the list of supported institutions",
+ "noInstitutionsFound": "No banks available for this country",
+ "loadingInstitutions": "Loading banks…",
+ "loadingInstitutionsError": "Failed to load banks",
+ "connectionExpired": "Connection expired — reconnect to fix",
+ "back": "Back",
+ "redirecting": "Redirecting to your bank…",
+ "oauthCallback": {
+ "title": "Connecting your bank",
+ "linking": "Importing your accounts, balances and transactions. This can take a minute.",
+ "dontClose": "Don't close this tab — we'll redirect you when it's ready.",
+ "linkAccountsFirstTitle": "Accounts not linked yet",
+ "linkAccountsFirstDesc": "Your Enable Banking account is in restricted mode, so accounts have to be pre-linked in the Enable Banking portal before they can be imported here.",
+ "openPortal": "Open Enable Banking portal",
+ "retry": "I've linked my accounts, try again",
+ "missingState": "OAuth state is missing or invalid. Please start the connection again.",
+ "providerError": "The bank reported an error: {{message}}"
+ },
"providers": {
"pluggy": {
"description": "Open finance provider for Brazilian banks"
+ },
+ "enable_banking": {
+ "description": "European banks via PSD2 open banking"
}
}
},
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 2838a548..06c15dc5 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -486,9 +486,33 @@
"selectConnectorDesc": "Escolha um provedor de conexão bancária",
"connectorNotConfigured": "Este conector requer configuração. Configure as credenciais necessárias para habilitá-lo.",
"noConnectorsAvailable": "Nenhum conector bancário disponível",
+ "selectCountry": "Selecione o país",
+ "selectCountryDesc": "Escolha o país do seu banco",
+ "selectBank": "Selecione o banco",
+ "selectBankDesc": "Escolha seu banco na lista de instituições suportadas",
+ "noInstitutionsFound": "Nenhum banco disponível para este país",
+ "loadingInstitutions": "Carregando bancos…",
+ "loadingInstitutionsError": "Falha ao carregar bancos",
+ "connectionExpired": "Conexão expirada — reconecte para corrigir",
+ "back": "Voltar",
+ "redirecting": "Redirecionando para o seu banco…",
+ "oauthCallback": {
+ "title": "Conectando seu banco",
+ "linking": "Importando suas contas, saldos e transações. Isto pode levar um minuto.",
+ "dontClose": "Não feche esta aba — vamos te redirecionar quando estiver pronto.",
+ "linkAccountsFirstTitle": "Contas ainda não vinculadas",
+ "linkAccountsFirstDesc": "Sua conta Enable Banking está em modo restrito, então as contas precisam ser pré-vinculadas no portal Enable Banking antes de poderem ser importadas aqui.",
+ "openPortal": "Abrir portal Enable Banking",
+ "retry": "Já vinculei minhas contas, tentar novamente",
+ "missingState": "O estado do OAuth está ausente ou inválido. Inicie a conexão novamente.",
+ "providerError": "O banco reportou um erro: {{message}}"
+ },
"providers": {
"pluggy": {
"description": "Provedor Open Finance para bancos brasileiros"
+ },
+ "enable_banking": {
+ "description": "Bancos europeus via PSD2 Open Banking"
}
}
},
diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsx
index c60e37df..94aeab54 100644
--- a/frontend/src/pages/accounts.tsx
+++ b/frontend/src/pages/accounts.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { getAccountName } from '@/lib/account-utils'
import { getConnectionName } from '@/lib/connection-utils'
import { Link } from 'react-router-dom'
@@ -37,7 +37,8 @@ import {
} from 'lucide-react'
import { PageHeader } from '@/components/page-header'
import { BankConnectDialog } from '@/components/bank-connect-dialog'
-import { ConnectorSelectDialog } from '@/components/connector-select-dialog'
+import { ConnectorSelectDialog, type Provider } from '@/components/connector-select-dialog'
+import { OAuthConnectDialog } from '@/components/oauth-connect-dialog'
import { ConnectionSettingsDialog } from '@/components/connection-settings-dialog'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
@@ -79,7 +80,7 @@ export default function AccountsPage() {
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
const [deletingId, setDeletingId] = useState<string | null>(null)
const [connectorSelectOpen, setConnectorSelectOpen] = useState(false)
- const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
+ const [selectedProvider, setSelectedProvider] = useState<Provider | null>(null)
const [settingsConnection, setSettingsConnection] = useState<BankConnection | null>(null)
const [disconnectingConnection, setDisconnectingConnection] = useState<BankConnection | null>(null)
const [closingAccountId, setClosingAccountId] = useState<string | null>(null)
@@ -96,6 +97,35 @@ export default function AccountsPage() {
queryFn: connections.list,
})
+ const { data: providersList } = useQuery({
+ queryKey: ['connections', 'providers'],
+ queryFn: connections.getProviders,
+ staleTime: 1000 * 60 * 10,
+ })
+
+ const providersByName = useMemo(() => {
+ const map = new Map<string, Provider>()
+ for (const p of providersList ?? []) map.set(p.name, p as Provider)
+ return map
+ }, [providersList])
+
+ const handleReconnectClick = async (conn: BankConnection) => {
+ const providerInfo = providersByName.get(conn.provider)
+ if (providerInfo?.flow_type === 'oauth') {
+ try {
+ const url = await connections.getReauthUrl(conn.id)
+ window.location.assign(url)
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e)
+ toast.error(message || t('accounts.connectError'))
+ }
+ return
+ }
+ // Widget flow (Pluggy): re-open the widget with the existing item_id.
+ setReconnectConnId(conn.id)
+ setReconnectItemId(conn.external_id)
+ }
+
const { data: closedAccountsList } = useQuery({
queryKey: ['accounts', 'closed'],
queryFn: () => accounts.list(true),
@@ -362,17 +392,16 @@ export default function AccountsPage() {
{conn.status !== 'active' && (
<div className="mx-5 mt-3 flex items-center justify-between rounded-lg border border-amber-200 bg-amber-50 px-4 py-2.5">
<span className="text-sm text-amber-800">
- {t('accounts.connectionError')}
+ {conn.status === 'expired'
+ ? t('accounts.connectionExpired')
+ : t('accounts.connectionError')}
</span>
{canWrite && (
<Button
variant="outline"
size="sm"
className="border-amber-300 text-amber-700 hover:bg-amber-100 gap-1.5 h-8"
- onClick={() => {
- setReconnectConnId(conn.id)
- setReconnectItemId(conn.external_id)
- }}
+ onClick={() => handleReconnectClick(conn)}
>
<RefreshCw size={12} />
{t('accounts.reconnect')}
@@ -585,11 +614,18 @@ export default function AccountsPage() {
onSelect={(provider) => setSelectedProvider(provider)}
/>
- {/* Bank Connect Dialog */}
+ {/* Bank Connect Dialog — widget-based (Pluggy) */}
<BankConnectDialog
- open={!!selectedProvider}
+ open={!!selectedProvider && selectedProvider.flow_type === 'widget'}
+ onClose={() => setSelectedProvider(null)}
+ provider={selectedProvider?.name}
+ />
+
+ {/* OAuth Connect Dialog — institution-pickers (Enable Banking) */}
+ <OAuthConnectDialog
+ open={!!selectedProvider && selectedProvider.flow_type === 'oauth'}
onClose={() => setSelectedProvider(null)}
- provider={selectedProvider ?? undefined}
+ provider={selectedProvider?.name ?? ''}
/>
{/* Reconnect Dialog */}
diff --git a/frontend/src/pages/oauth-callback.tsx b/frontend/src/pages/oauth-callback.tsx
new file mode 100644
index 00000000..aafa6e98
--- /dev/null
+++ b/frontend/src/pages/oauth-callback.tsx
@@ -0,0 +1,140 @@
+import { useEffect, useState } from 'react'
+import { useNavigate, useSearchParams } from 'react-router-dom'
+import { useTranslation } from 'react-i18next'
+import { useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import axios from 'axios'
+import { connections } from '@/lib/api'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+import { Button } from '@/components/ui/button'
+import { Building2, ExternalLink } from 'lucide-react'
+
+type RestrictedDetail = {
+ message?: string
+ code?: string
+ help_url?: string | null
+}
+
+export default function OAuthCallbackPage() {
+ const { t } = useTranslation()
+ const [params] = useSearchParams()
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
+ const code = params.get('code')
+ const state = params.get('state')
+ const errorParam = params.get('error')
+ const errorDescription = params.get('error_description')
+ const [restricted, setRestricted] = useState<RestrictedDetail | null>(null)
+ const [retrying, setRetrying] = useState(false)
+
+ useEffect(() => {
+ // Provider reported an error during the consent step.
+ if (errorParam) {
+ toast.error(
+ t('accounts.oauthCallback.providerError', {
+ message: errorDescription || errorParam,
+ }),
+ )
+ navigate('/accounts', { replace: true })
+ return
+ }
+ if (!code || !state) {
+ toast.error(t('accounts.oauthCallback.missingState'))
+ navigate('/accounts', { replace: true })
+ return
+ }
+ // The state token is single-use server-side, so React StrictMode's
+ // double-mount in dev (or any accidental remount) would fire a second
+ // POST that gets rejected. Guard via sessionStorage so only the first
+ // mount actually submits — and don't cancel on unmount; we want the
+ // side-effect to finish even if the user navigates away mid-sync.
+ const submitKey = `oauth-submitted:${code}:${state}`
+ if (sessionStorage.getItem(submitKey)) return
+ sessionStorage.setItem(submitKey, '1')
+
+ ;(async () => {
+ try {
+ await connections.handleCallback(code, '', state)
+ await queryClient.refetchQueries({ queryKey: ['connections'] })
+ invalidateFinancialQueries(queryClient)
+ toast.success(t('accounts.connected'))
+ navigate('/accounts', { replace: true })
+ } catch (err) {
+ if (axios.isAxiosError(err) && err.response?.status === 409) {
+ const detail = err.response.data?.detail as RestrictedDetail | string | undefined
+ if (typeof detail === 'object' && detail?.code === 'no_accounts_linked') {
+ // Let the user retry: clear the guard so a fresh consent flow works.
+ sessionStorage.removeItem(submitKey)
+ setRestricted(detail)
+ return
+ }
+ }
+ const message =
+ axios.isAxiosError(err) && err.response?.data?.detail
+ ? String(err.response.data.detail)
+ : t('accounts.connectError')
+ sessionStorage.removeItem(submitKey)
+ toast.error(message)
+ navigate('/accounts', { replace: true })
+ }
+ })()
+ }, [code, state, errorParam, errorDescription, navigate, queryClient, t, retrying])
+
+ if (restricted) {
+ return (
+ <div className="mx-auto max-w-md py-16 px-4">
+ <div className="rounded-xl border border-amber-300 bg-amber-50 dark:border-amber-700/40 dark:bg-amber-900/20 p-6 space-y-4">
+ <div className="flex items-start gap-3">
+ <div className="rounded-lg bg-amber-100 dark:bg-amber-800/30 p-2 shrink-0">
+ <Building2 size={18} className="text-amber-700 dark:text-amber-300" />
+ </div>
+ <div className="space-y-1">
+ <h2 className="text-base font-semibold">
+ {t('accounts.oauthCallback.linkAccountsFirstTitle')}
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ {t('accounts.oauthCallback.linkAccountsFirstDesc')}
+ </p>
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ {restricted.help_url && (
+ <Button asChild variant="outline">
+ <a href={restricted.help_url} target="_blank" rel="noreferrer">
+ {t('accounts.oauthCallback.openPortal')}
+ <ExternalLink size={14} className="ml-2" />
+ </a>
+ </Button>
+ )}
+ <Button
+ onClick={() => {
+ setRestricted(null)
+ setRetrying((v) => !v)
+ }}
+ >
+ {t('accounts.oauthCallback.retry')}
+ </Button>
+ <Button variant="ghost" onClick={() => navigate('/accounts', { replace: true })}>
+ {t('common.cancel')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col items-center justify-center min-h-[60vh] gap-5 px-4 text-center">
+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
+ <div className="space-y-1.5 max-w-md">
+ <p className="text-base font-medium">{t('accounts.oauthCallback.title')}</p>
+ <p className="text-sm text-muted-foreground">
+ {t('accounts.oauthCallback.linking')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('accounts.oauthCallback.dontClose')}
+ </p>
+ </div>
+ </div>
+ )
+}