use std::marker::PhantomData;
use std::time::Duration;
use jiff::{
Timestamp,
civil::{Date, DateTime},
};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
use crate::banks::{BankConfig, BookingIdSource, InitMode};
use crate::error::{FinTSError, Result};
use crate::formats::mt940::{parse_mt940, parse_mt942};
use crate::protocol::{
self, Account, Allowance, BankParams, InitResult, Open, Response, Segment, UpdAccount,
};
use crate::return_code::{Category, ClientWarning, Kind, Notice, NoticeDialog, ReturnCode};
use crate::segments::Order;
use crate::segments::read::{extract_camt_data, extract_mt940_data, parse_hiwdu, parse_hiwpd};
use crate::session::SessionState;
use crate::transport::SharedTransport;
use crate::types::*;
#[derive(Clone)]
pub struct BankClient {
config: BankConfig,
product_id: ProductId,
transport: Option<SharedTransport>,
quirks: Option<std::sync::Arc<dyn Fn() -> crate::quirks::QuirkChain + Send + Sync>>,
now: Option<DateTime>,
}
impl BankClient {
pub fn new(config: BankConfig, product_id: ProductId) -> Self {
Self {
config,
product_id,
transport: None,
quirks: None,
now: None,
}
}
pub fn with_now(mut self, now: DateTime) -> Self {
self.now = Some(now);
self
}
pub fn now(&self) -> DateTime {
self.now
.unwrap_or_else(|| jiff::ZonedDateTime::now().datetime())
}
pub fn today(&self) -> Date {
self.now().date()
}
pub fn with_transport(mut self, transport: SharedTransport) -> Self {
self.transport = Some(transport);
self
}
pub fn with_quirks(
mut self,
quirks: impl Fn() -> crate::quirks::QuirkChain + Send + Sync + 'static,
) -> Self {
self.quirks = Some(std::sync::Arc::new(quirks));
self
}
pub fn config(&self) -> &BankConfig {
&self.config
}
pub(crate) fn effective_user_id(&self, user_id: &UserId) -> UserId {
let Some(rule) = &self.config.profile.user_id else {
return user_id.clone();
};
match rule.apply(user_id.as_str()) {
std::borrow::Cow::Borrowed(_) => user_id.clone(),
std::borrow::Cow::Owned(full) => {
debug!(
"[FinTS] User ID completed by the {} profile: {} -> {}",
self.config.profile.id,
"*".repeat(user_id.as_str().chars().count()),
"*".repeat(full.chars().count()),
);
UserId::new(full)
}
}
}
fn new_dialog(&self, creds: &Credentials) -> Result<protocol::Dialog<protocol::New>> {
let c = &self.config;
let dialog = protocol::Dialog::new(
c.url.as_str(),
&c.blz,
&self.effective_user_id(&creds.user_id),
&creds.pin,
&self.product_id,
)?
.with_tan_overrides(c.profile.tan_overrides.clone());
let dialog = match &self.quirks {
Some(q) => dialog.with_quirks(q()),
None => dialog,
}
.with_now(self.now);
Ok(match &self.transport {
Some(t) => dialog.with_transport(t.clone()),
None => dialog,
})
}
}
impl std::fmt::Debug for BankClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BankClient")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct Credentials {
pub user_id: UserId,
pub pin: Pin,
}
impl Credentials {
pub fn new(user_id: UserId, pin: Pin) -> Self {
Self { user_id, pin }
}
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Credentials(****)")
}
}
#[must_use]
#[derive(Debug)]
pub enum Step<T> {
Done(Completed<T>),
NeedTan(TanChallenge, Resume<T>),
NeedVopConfirmation(VopConfirmation, Resume<T>),
VopPending(VopWait, Resume<T>),
}
#[derive(Debug, Clone)]
pub struct Completed<T> {
pub value: T,
pub notices: Vec<Notice>,
}
#[derive(Debug)]
pub struct Resume<T> {
ticket: Ticket,
_value: PhantomData<fn() -> T>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum Ticket {
Task(TaskReference),
Local(u64),
}
impl Ticket {
fn local() -> Self {
Self::Local(rand::random())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum Wait {
Tan(TanChallenge),
VopConfirmation(VopConfirmation),
VopPoll(VopWait),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TanChallenge {
pub challenge: ChallengeText,
pub challenge_markup: bool,
pub kind: TanKind,
pub valid_until: Option<DateTime>,
pub not_before: Option<Timestamp>,
pub payee_check: Option<VopResult>,
pub rejected: Option<Box<TanRejected>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TanRejected {
pub code: ReturnCode,
pub attempts_left: Option<u32>,
pub count: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TanKind {
Typed { media: Option<TanMedia> },
Decoupled {
first_wait: Option<Duration>,
next_wait: Option<Duration>,
max_polls: Option<u32>,
polls_done: u32,
auto_polling_allowed: Option<bool>,
},
}
impl TanChallenge {
fn from_bank(
challenge: &protocol::TanChallenge,
params: &BankParams,
arrived: Timestamp,
) -> Self {
let mut not_before = None;
let kind = if challenge.decoupled {
let p = params.decoupled_params();
not_before = not_before_after(arrived, p.wait_before_first_poll);
TanKind::Decoupled {
first_wait: p.wait_before_first_poll,
next_wait: p.wait_before_next_poll,
max_polls: p.max_polls,
polls_done: 0,
auto_polling_allowed: p.auto_polling_allowed,
}
} else {
TanKind::Typed {
media: challenge
.challenge_hhduc
.as_ref()
.and_then(HhdUcData::decode),
}
};
Self {
challenge: challenge.challenge.clone(),
challenge_markup: challenge.challenge_markup || params.challenge_structured(),
kind,
valid_until: challenge.valid_until,
not_before,
payee_check: None,
rejected: None,
}
}
}
pub(crate) fn extend_notices(notices: &mut Vec<Notice>, new: Vec<Notice>) {
for notice in new {
if !notices.contains(¬ice) {
notices.push(notice);
}
}
}
fn not_before_after(arrived: Timestamp, wait: Option<Duration>) -> Option<Timestamp> {
let wait = jiff::SignedDuration::try_from(wait?).ok()?;
arrived.checked_add(wait).ok()
}
#[derive(Debug, Clone)]
pub struct Opened {
pub accounts: Vec<AccountInfo>,
pub tan_methods: Vec<TanMethod>,
pub allowed_security_functions: Vec<SecurityFunction>,
pub selected_tan_method: Option<TanMethod>,
}
pub trait JobValue: sealed::Sealed + Sized {}
impl JobValue for Opened {}
impl JobValue for Option<AccountBalance> {}
impl JobValue for Statement {}
impl JobValue for Vec<SecurityHolding> {}
impl JobValue for Vec<DepotTransaction> {}
impl JobValue for TransferReceipt {}
impl JobValue for InstantStatus {}
mod sealed {
use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Job {
Open,
Balance,
Transactions,
Holdings,
DepotTransactions,
Transfer,
InstantStatus,
}
pub enum Value {
Opened(Opened),
Balance(Option<AccountBalance>),
Statement(Statement),
Holdings(Vec<SecurityHolding>),
DepotTransactions(Vec<DepotTransaction>),
Transfer(TransferReceipt),
InstantStatus(InstantStatus),
}
pub trait Sealed: Sized {
const JOB: Job;
fn from_value(value: Value) -> Option<Self>;
}
impl Sealed for Opened {
const JOB: Job = Job::Open;
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Opened(v) => Some(v),
_ => None,
}
}
}
impl Sealed for Option<AccountBalance> {
const JOB: Job = Job::Balance;
fn from_value(value: Value) -> Option<Self> {
match value {
Value::Balance(v) => Some(v),
_ => None,
}
}
}
}
macro_rules! sealed_value {
($($ty:ty => $job:ident, $variant:ident;)*) => {$(
impl Sealed for $ty {
const JOB: Job = Job::$job;
fn from_value(value: Value) -> Option<Self> {
match value {
Value::$variant(v) => Some(v),
_ => None,
}
}
}
)*};
}
sealed_value! {
Statement => Transactions, Statement;
Vec<SecurityHolding> => Holdings, Holdings;
Vec<DepotTransaction> => DepotTransactions, DepotTransactions;
TransferReceipt => Transfer, Transfer;
InstantStatus => InstantStatus, InstantStatus;
}
use sealed::{Job, Sealed, Value};
mod accounts;
pub use accounts::AccountInfo;
mod capabilities;
pub use capabilities::{
AccountCapabilities, Capabilities, JobCapability, JobKind, Support, VopSupport,
};
mod paused;
pub use paused::{AnyResume, PAUSED_DIALOG_FORMAT, PausedDialog, PausedFormat, ResumeKind};
mod instant_status;
pub use instant_status::{InstantStatus, SepaOrderStatus, StatusSource, instant_status};
mod transfer;
pub use transfer::{
CheckedTransfer, Instant, InvalidReason, InvalidTransfer, PayeeOutcome, PayeeResult, SentAs,
Transfer, TransferField, TransferReceipt, TransferStatus, VopConfirmation, VopResult, VopWait,
transfer,
};
use transfer::{PaymentIds, PaymentJob};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Range {
pub from: Date,
pub to: Date,
}
impl Range {
pub fn new(from: Date, to: Date) -> Self {
Self { from, to }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Format {
#[default]
Auto,
Camt,
Mt940,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatementFormat {
Camt,
Mt940,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Pending {
Reported(Vec<Transaction>),
NotSent,
Unreadable { kind: Category, message: String },
}
impl Pending {
pub fn reported(&self) -> Option<&[Transaction]> {
match self {
Self::Reported(t) => Some(t),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Statement {
pub booked: Vec<Transaction>,
pub pending: Pending,
pub pending_created_at: Option<BankTime>,
pub format: StatementFormat,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum JobInput {
Open,
Balance { account: Account },
Transactions {
account: Account,
range: Range,
format: StatementFormat,
touchdown: Option<TouchdownPoint>,
booked: Vec<Vec<u8>>,
pending: Vec<Vec<u8>>,
pending_sent: bool,
find_payment: Option<String>,
},
Holdings {
account: Account,
currency: Option<Currency>,
touchdown: Option<TouchdownPoint>,
found: Vec<SecurityHolding>,
},
DepotTransactions {
account: Account,
range: Option<Range>,
touchdown: Option<TouchdownPoint>,
found: Vec<DepotTransaction>,
},
Transfer(Box<PaymentJob>),
InstantStatus {
account: Account,
descriptors: Vec<String>,
order_id: String,
min_wait: Option<u32>,
},
}
fn after_order<T>(ids: Option<&PaymentIds>, outcome: Result<T>) -> Result<T> {
match ids {
Some(ids) => outcome.map_err(|e| ids.after_order(e)),
None => outcome,
}
}
impl JobInput {
fn payment_ids(&self) -> Option<PaymentIds> {
match self {
Self::Transfer(p) => Some(p.ids()),
_ => None,
}
}
fn in_flight(&self) -> InFlight {
match self.payment_ids() {
Some(ids) => InFlight::Payment(ids),
None => InFlight::Message,
}
}
fn tan_extra(&self) -> Vec<Segment> {
match self {
Self::Transfer(p) => p.tan_extra(),
_ => Vec::new(),
}
}
fn job(&self) -> Job {
match self {
Self::Open => Job::Open,
Self::Balance { .. } => Job::Balance,
Self::Transactions {
find_payment: Some(_),
..
} => Job::InstantStatus,
Self::Transactions { .. } => Job::Transactions,
Self::Holdings { .. } => Job::Holdings,
Self::DepotTransactions { .. } => Job::DepotTransactions,
Self::Transfer(_) => Job::Transfer,
Self::InstantStatus { .. } => Job::InstantStatus,
}
}
fn order(&self) -> Option<(Segment, &'static str, &'static str)> {
Some(match self {
Self::Open | Self::Transfer(_) => return None,
Self::Balance { account } => (
Segment::Balance {
account: account.clone(),
},
"HKSAL",
"HISAL",
),
Self::Transactions {
account,
range,
format,
touchdown,
..
} => match format {
StatementFormat::Mt940 => (
Segment::Transactions {
account: account.clone(),
start_date: range.from,
end_date: range.to,
touchdown: touchdown.clone(),
},
"HKKAZ",
"HIKAZ",
),
StatementFormat::Camt => (
Segment::CamtTransactions {
account: account.clone(),
start_date: range.from,
end_date: range.to,
touchdown: touchdown.clone(),
},
"HKCAZ",
"HICAZ",
),
},
Self::Holdings {
account,
currency,
touchdown,
..
} => (
Segment::Holdings {
account: account.clone(),
currency: currency.clone(),
touchdown: touchdown.clone(),
},
"HKWPD",
"HIWPD",
),
Self::DepotTransactions {
account,
range,
touchdown,
..
} => (
Segment::DepotTransactions {
account: account.clone(),
start_date: range.map(|r| r.from),
end_date: range.map(|r| r.to),
touchdown: touchdown.clone(),
},
"HKWDU",
"HIWDU",
),
Self::InstantStatus {
account,
descriptors,
order_id,
..
} => (
Segment::InstantStatus {
account: account.clone(),
descriptors: descriptors.clone(),
order_id: order_id.clone(),
},
"HKIPS",
"HIIPS",
),
})
}
fn absorb(
&mut self,
response: &Response,
requested_camt: &str,
notices: &mut Vec<Notice>,
) -> bool {
let next = response.touchdown();
let (current, more) = match self {
Self::Open | Self::Balance { .. } | Self::Transfer(_) | Self::InstantStatus { .. } => {
return false;
}
Self::Transactions {
format,
touchdown,
booked,
pending,
pending_sent,
..
} => {
match format {
StatementFormat::Mt940 => {
let page = extract_mt940_data(&response.segments);
booked.push(page.booked);
pending.push(page.pending);
*pending_sent |= page.pending_sent;
}
StatementFormat::Camt => {
let page = extract_camt_data(&response.segments);
for (descriptor, document) in page.descriptors.iter().zip(&page.booked) {
crate::camt::note_version_mismatch(
requested_camt,
descriptor,
document,
);
}
booked.extend(page.booked);
pending.extend(page.pending);
*pending_sent |= page.pending_sent;
}
}
(touchdown, next)
}
Self::Holdings {
touchdown, found, ..
} => {
found.extend(parse_hiwpd(&response.segments));
(touchdown, next)
}
Self::DepotTransactions {
touchdown, found, ..
} => {
found.extend(parse_hiwdu(&response.segments));
(touchdown, next)
}
};
match more {
Some(point) if current.as_ref() == Some(&point) => {
warn!("[FinTS] The bank repeated touchdown point {point}; stopping");
notices.extend(
response
.all_codes()
.filter(|c| matches!(c.kind(), Kind::Touchdown(_)))
.map(|c| Notice::new(NoticeDialog::Job, c.clone())),
);
false
}
Some(point) => {
info!("[FinTS] Touchdown {point}: more data");
*current = Some(point);
true
}
None => false,
}
}
fn finish(self, response: &Response, booking_id: BookingIdSource) -> Result<Value> {
Ok(match self {
Self::Open | Self::Transfer(_) => {
return Err(FinTSError::Internal("not a read order".into()));
}
Self::Balance { .. } => Value::Balance(
response
.find_segment("HISAL")
.and_then(crate::segments::read::balance),
),
Self::Transactions {
format,
booked,
pending,
pending_sent,
find_payment,
..
} => {
let statement =
parse_statement(format, &booked, &pending, pending_sent, booking_id)?;
match find_payment {
Some(id) => {
Value::InstantStatus(instant_status::from_statement(&statement, &id))
}
None => Value::Statement(statement),
}
}
Self::Holdings { found, .. } => Value::Holdings(found),
Self::DepotTransactions { found, .. } => Value::DepotTransactions(found),
Self::InstantStatus { min_wait, .. } => {
Value::InstantStatus(instant_status::read(response, min_wait)?)
}
})
}
}
fn parse_statement(
format: StatementFormat,
booked: &[Vec<u8>],
pending: &[Vec<u8>],
pending_sent: bool,
booking_id: BookingIdSource,
) -> Result<Statement> {
let (booked, pending) =
match format {
StatementFormat::Mt940 => (
parse_mt940(&booked.concat(), TransactionStatus::Booked),
parse_mt942(&pending.concat()).map(|p| (p.transactions, p.created)),
),
StatementFormat::Camt => (
booked
.iter()
.try_fold(Vec::new(), |mut all, doc| {
all.extend(crate::camt::parse_camt052(doc, booking_id)?);
Ok(all)
})
.map(|mut all: Vec<Transaction>| {
crate::camt::drop_shared_booking_ids(&mut all);
all
}),
pending
.iter()
.try_fold(Vec::new(), |mut all, doc| {
let none = BookingIdSource::None;
all.extend(crate::camt::parse_camt052(doc, none)?.into_iter().map(
|mut t| {
t.status = TransactionStatus::Pending;
t
},
));
Ok(all)
})
.map(|all| (all, None)),
),
};
let (pending, pending_created_at) = match pending {
_ if !pending_sent => (Pending::NotSent, None),
Ok((pending, created)) => (Pending::Reported(pending), created),
Err(e) => (
Pending::Unreadable {
kind: e.kind(),
message: e.to_string(),
},
None,
),
};
Ok(Statement {
booked: booked?,
pending,
pending_created_at,
format,
})
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingJob {
ticket: Ticket,
wait: Wait,
job: JobInput,
notices: Vec<Notice>,
}
impl PendingJob {
pub fn challenge(&self) -> Option<&TanChallenge> {
match &self.wait {
Wait::Tan(c) => Some(c),
_ => None,
}
}
pub fn vop(&self) -> Option<&VopConfirmation> {
match &self.wait {
Wait::VopConfirmation(c) => Some(c),
_ => None,
}
}
pub fn vop_wait(&self) -> Option<&VopWait> {
match &self.wait {
Wait::VopPoll(w) => Some(w),
_ => None,
}
}
fn task_reference(&self) -> Result<TaskReference> {
match &self.ticket {
Ticket::Task(t) => Ok(t.clone()),
Ticket::Local(_) => Err(FinTSError::Internal(
"TAN wait without task reference".into(),
)),
}
}
}
#[derive(Debug, Clone)]
pub enum Phase {
Open,
Paused(Box<PendingJob>),
Ended,
}
enum Outcome {
Done(Value, Vec<Notice>),
Paused(Wait, Ticket),
}
impl Outcome {
fn into_step<T: Sealed>(self) -> Result<Step<T>> {
match self {
Self::Done(value, notices) => T::from_value(value)
.map(|value| Step::Done(Completed { value, notices }))
.ok_or_else(|| FinTSError::Internal("job finished with another value".into())),
Self::Paused(wait, ticket) => {
let resume = Resume {
ticket,
_value: PhantomData,
};
Ok(match wait {
Wait::Tan(c) => Step::NeedTan(c, resume),
Wait::VopConfirmation(c) => Step::NeedVopConfirmation(c, resume),
Wait::VopPoll(w) => Step::VopPending(w, resume),
})
}
}
}
}
pub struct Dialog {
inner: protocol::Dialog<Open>,
bic: Bic,
booking_id: BookingIdSource,
phase: Phase,
last_message_at: Timestamp,
in_flight: Option<InFlight>,
}
#[derive(Debug, Clone)]
enum InFlight {
Message,
Payment(PaymentIds),
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Cancelled {
NothingSent,
OrderSubmitted {
end_to_end_id: String,
message_id: String,
},
}
impl std::fmt::Debug for Dialog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let phase = match &self.phase {
Phase::Open => "Open",
Phase::Paused(_) => "Paused",
Phase::Ended => "Ended",
};
f.debug_struct("Dialog")
.field("blz", self.inner.blz())
.field("phase", &phase)
.field("last_message_at", &self.last_message_at)
.finish_non_exhaustive()
}
}
pub async fn open(
client: &BankClient,
creds: &Credentials,
state: &SessionState,
) -> Result<(Dialog, Step<Opened>)> {
let state = state_for(client, creds, state);
match open_once(client, creds, state).await {
Err(e)
if e.kind() == Category::SystemId
&& state.is_some_and(|s| s.system_id.is_assigned()) =>
{
warn!("[FinTS] Bank rejected cached system ID ({e}); re-synchronizing");
open_once(client, creds, None).await
}
other => other,
}
}
async fn open_once(
client: &BankClient,
creds: &Credentials,
state: Option<&SessionState>,
) -> Result<(Dialog, Step<Opened>)> {
if let InitMode::Direct { security_function } = &client.config().profile.init {
return open_direct(client, creds, state, security_function).await;
}
let mut notices = Vec::new();
let (mut params, system_id) = match state.filter(|s| s.can_skip_sync()) {
Some(s) => {
info!(
"[FinTS] Using cached BPD v{} / UPD v{} and system ID: no sync dialog",
s.bpd_version, s.upd_version
);
(s.to_params(), s.system_id.clone())
}
None => fetch_params(client, creds, state, &mut notices).await?,
};
if let Some(s) = state {
params.preferred_security_function = s
.tan_method
.clone()
.or(params.preferred_security_function.take());
params.selected_tan_medium = s.tan_medium.clone().or(params.selected_tan_medium.take());
params.select_security_function();
}
let init = client
.new_dialog(creds)?
.with_system_id(&system_id)
.with_params(¶ms)
.init()
.await?;
let (inner, challenge) = match init {
InitResult::Opened(open) => (open, None),
InitResult::TanRequired(pending, challenge) => (pending.transition(), Some(challenge)),
};
let mut dialog = Dialog {
inner,
bic: client.config().bic.clone(),
booking_id: client.config().profile.booking_id,
phase: Phase::Open,
last_message_at: Timestamp::now(),
in_flight: None,
};
notices.extend(dialog.inner.take_notices());
let outcome = match challenge {
Some(challenge) => dialog.pause(JobInput::Open, &challenge, notices),
None => Outcome::Done(Value::Opened(dialog.opened()), notices),
};
let step = outcome.into_step()?;
Ok((dialog, step))
}
async fn open_direct(
client: &BankClient,
creds: &Credentials,
state: Option<&SessionState>,
security_function: &str,
) -> Result<(Dialog, Step<Opened>)> {
let system_id = state
.map(|s| &s.system_id)
.filter(|s| s.is_assigned())
.cloned()
.unwrap_or_else(|| SystemId::new(format!("{:016X}", rand::random::<u64>())));
let (inner, _) = client
.new_dialog(creds)?
.with_system_id(&system_id)
.with_security_function(SecurityFunction::new(security_function))
.init_no_tan()
.await?;
let mut dialog = Dialog {
inner,
bic: client.config().bic.clone(),
booking_id: client.config().profile.booking_id,
phase: Phase::Open,
last_message_at: Timestamp::now(),
in_flight: None,
};
let notices = dialog.inner.take_notices();
let step = Outcome::Done(Value::Opened(dialog.opened()), notices).into_step()?;
Ok((dialog, step))
}
fn state_for<'a>(
client: &BankClient,
creds: &Credentials,
state: &'a SessionState,
) -> Option<&'a SessionState> {
let matches = state.blz == client.config().blz
&& client.effective_user_id(&state.user_id) == client.effective_user_id(&creds.user_id);
if !matches {
warn!("[FinTS] Ignoring session state: it belongs to another bank or user");
}
matches.then_some(state)
}
pub async fn synchronise(
client: &BankClient,
creds: &Credentials,
state: &SessionState,
) -> Result<Completed<SessionState>> {
let config = client.config();
let user_id = client.effective_user_id(&creds.user_id);
let state = state_for(client, creds, state);
if let InitMode::Direct { security_function } = &config.profile.init {
let mut state = state
.cloned()
.unwrap_or_else(|| SessionState::new(&config.blz, &user_id));
state.tan_method = Some(SecurityFunction::new(security_function));
return Ok(Completed {
value: state,
notices: Vec::new(),
});
}
let mut notices = Vec::new();
let (mut params, system_id) = fetch_params(client, creds, state, &mut notices).await?;
for n in ¬ices {
info!("[FinTS] Synchronisation: {n}");
}
if let Some(s) = state {
params.preferred_security_function = s.tan_method.clone();
params.selected_tan_medium = s.tan_medium.clone();
params
.tan_required_learned
.extend(s.tan_required_learned.iter().cloned());
params.select_security_function();
}
Ok(Completed {
value: SessionState::capture(&config.blz, &user_id, &system_id, ¶ms),
notices,
})
}
async fn fetch_params(
client: &BankClient,
creds: &Credentials,
state: Option<&SessionState>,
notices: &mut Vec<Notice>,
) -> Result<(BankParams, SystemId)> {
let stored = state.map(|s| &s.system_id).filter(|s| s.is_assigned());
if let Some(sid) = stored {
match client
.new_dialog(creds)?
.with_system_id(sid)
.probe_parameters()
.await
{
Ok(found) => {
info!("[FinTS] Reusing the stored system ID; no sync dialog");
return Ok(found);
}
Err(e) if matches!(e.kind(), Category::Credentials(_) | Category::SystemId) => {
return Err(e);
}
Err(e) => warn!(
"[FinTS] Parameter probe with the stored system ID failed ({e}); synchronizing"
),
}
}
let mut sync = client.new_dialog(creds)?;
if let Some(sid) = stored {
sync = sync.with_system_id(sid);
}
let (mut synced, _) = sync.sync().await?;
notices.extend(synced.take_notices());
let (params, system_id) = synced.end().await?;
let system_id = if system_id.is_assigned() {
system_id
} else {
stored.cloned().unwrap_or_else(SystemId::unassigned)
};
Ok((params, system_id))
}
pub async fn balance(
dialog: &mut Dialog,
account: &Account,
) -> Result<Step<Option<AccountBalance>>> {
dialog
.start(JobInput::Balance {
account: account.clone(),
})
.await?
.into_step()
}
pub async fn transactions(
dialog: &mut Dialog,
account: &Account,
range: Range,
format: Format,
) -> Result<Step<Statement>> {
let today = dialog.inner.now().date();
transactions_on(dialog, account, range, format, today).await
}
async fn transactions_on(
dialog: &mut Dialog,
account: &Account,
range: Range,
format: Format,
today: Date,
) -> Result<Step<Statement>> {
let format = choose_format(dialog.bank_params(), account, format)?;
let order = match format {
StatementFormat::Mt940 => Order::Transactions,
StatementFormat::Camt => Order::Camt,
};
let days = dialog.bank_params().days_stored(order);
let (range, clamped) = clamp_range(range, today, days);
let notices = clamped
.map(|requested| {
let warning = ClientWarning::RangeClamped {
requested,
used: range.from,
};
warn!("[FinTS] {warning}");
Notice::client(NoticeDialog::Job, warning)
})
.into_iter()
.collect();
dialog
.start_with(
JobInput::Transactions {
account: account.clone(),
range,
format,
touchdown: None,
booked: Vec::new(),
pending: Vec::new(),
pending_sent: false,
find_payment: None,
},
notices,
)
.await?
.into_step()
}
fn clamp_range(range: Range, today: Date, days_stored: Option<u32>) -> (Range, Option<Date>) {
let Some(oldest) = days_stored
.and_then(|d| today.checked_sub(jiff::Span::new().days(i64::from(d))).ok())
.filter(|oldest| range.from < *oldest)
else {
return (range, None);
};
(Range::new(oldest, range.to.max(oldest)), Some(range.from))
}
fn choose_format(
params: &BankParams,
account: &Account,
wanted: Format,
) -> Result<StatementFormat> {
choose_statement_format(params, wanted, || upd_allowance(params, account, "HKCAZ"))
}
fn choose_statement_format(
params: &BankParams,
wanted: Format,
camt_allowance: impl FnOnce() -> Allowance,
) -> Result<StatementFormat> {
match wanted {
Format::Camt => Ok(StatementFormat::Camt),
Format::Mt940 => Ok(StatementFormat::Mt940),
Format::Auto => match params.order_version(Order::Camt) {
Ok(_) if camt_allowance() == Allowance::No => {
info!("[FinTS] The UPD does not list HKCAZ for the account; using MT940");
Ok(StatementFormat::Mt940)
}
Ok(_) => Ok(StatementFormat::Camt),
Err(FinTSError::VersionMismatch(why)) => {
info!("[FinTS] camt not available ({why}); using MT940");
Ok(StatementFormat::Mt940)
}
Err(e) => Err(e),
},
}
}
fn find_upd_account<'a>(params: &'a BankParams, account: &Account) -> Option<&'a UpdAccount> {
params.upd()?.find(account)
}
fn upd_allowance(params: &BankParams, account: &Account, code: &str) -> Allowance {
match (params.upd(), find_upd_account(params, account)) {
(Some(upd), Some(a)) => upd.allows(a, code),
_ => Allowance::Unknown,
}
}
pub async fn holdings(
dialog: &mut Dialog,
account: &Account,
currency: Option<Currency>,
) -> Result<Step<Vec<SecurityHolding>>> {
dialog
.start(JobInput::Holdings {
account: account.clone(),
currency,
touchdown: None,
found: Vec::new(),
})
.await?
.into_step()
}
pub async fn depot_transactions(
dialog: &mut Dialog,
account: &Account,
range: Option<Range>,
) -> Result<Step<Vec<DepotTransaction>>> {
dialog
.start(JobInput::DepotTransactions {
account: account.clone(),
range,
touchdown: None,
found: Vec::new(),
})
.await?
.into_step()
}
impl Dialog {
pub fn phase(&self) -> &Phase {
&self.phase
}
pub fn pending(&self) -> Option<&PendingJob> {
match &self.phase {
Phase::Paused(p) => Some(p.as_ref()),
_ => None,
}
}
pub fn last_message_at(&self) -> Timestamp {
self.last_message_at
}
pub fn capabilities(&self, accounts: &[Account]) -> Capabilities {
Capabilities::build(self.bank_params(), self.inner.tan_overrides(), accounts)
}
#[cfg(feature = "tooling")]
pub fn bank_params(&self) -> &BankParams {
self.inner.bank_params()
}
#[cfg(not(feature = "tooling"))]
pub(crate) fn bank_params(&self) -> &BankParams {
self.inner.bank_params()
}
pub async fn submit_tan<T: JobValue>(
&mut self,
resume: Resume<T>,
tan: &str,
) -> Result<Step<T>> {
let pending = self.pending_for(&resume)?;
match &pending.wait {
Wait::Tan(c) if matches!(c.kind, TanKind::Decoupled { .. }) => {
return Err(FinTSError::Dialog(
"decoupled challenge: confirm in the app and poll".into(),
));
}
Wait::Tan(_) => {}
_ => {
return Err(FinTSError::Dialog(
"the job waits for its payee check, not for a TAN".into(),
));
}
}
let mut pending = self.take_pending();
let ids = pending.job.payment_ids();
let outcome = async {
let task_reference = pending.task_reference()?;
let extra = pending.job.tan_extra();
self.in_flight = Some(pending.job.in_flight());
let response = self.inner.send_tan(&extra, &task_reference, tan).await;
let response = self.settle(&pending.job, response)?;
if let JobInput::Transfer(p) = &mut pending.job {
p.tan_extra_sent();
}
if !matches!(self.phase, Phase::Ended)
&& let Some((code, attempts_left)) = response.tan_rejection()
&& let Wait::Tan(challenge) = &mut pending.wait
{
let count = challenge.rejected.as_ref().map_or(0, |r| r.count) + 1;
warn!(
"[FinTS] TAN rejected ({} {}); the bank keeps the order for another TAN",
code.code, code.text
);
challenge.rejected = Some(Box::new(TanRejected {
code,
attempts_left,
count,
}));
extend_notices(&mut pending.notices, self.inner.take_notices());
let outcome = Outcome::Paused(pending.wait.clone(), pending.ticket.clone());
self.phase = Phase::Paused(Box::new(pending));
return Ok(outcome);
}
self.confirmed(pending, response).await
}
.await;
after_order(ids.as_ref(), outcome)?.into_step()
}
pub async fn poll<T: JobValue>(&mut self, resume: Resume<T>) -> Result<Step<T>> {
let pending = self.pending_for(&resume)?;
let (max_polls, polls_done) = match &pending.wait {
Wait::VopPoll(_) => {
let pending = self.take_pending();
return self.vop_poll(pending).await?.into_step();
}
Wait::VopConfirmation(_) => {
return Err(FinTSError::Dialog(
"payee check result: confirm_vop or cancel".into(),
));
}
Wait::Tan(TanChallenge {
kind:
TanKind::Decoupled {
max_polls,
polls_done,
..
},
..
}) => (*max_polls, *polls_done),
Wait::Tan(_) => {
return Err(FinTSError::Dialog(
"typed TAN challenge: submit the TAN".into(),
));
}
};
let mut pending = self.take_pending();
let ids = pending.job.payment_ids();
if let Some(max) = max_polls.filter(|max| polls_done >= *max) {
self.job_failed(&pending.job);
return Err(match ids {
Some(ids) => {
warn!("[FinTS] Transfer approval not confirmed within {max} status requests");
ids.unknown()
}
None => FinTSError::DecoupledMaxPolls(max),
});
}
let outcome = async {
let task_reference = pending.task_reference()?;
let extra = pending.job.tan_extra();
self.in_flight = Some(pending.job.in_flight());
let response = self.inner.send_tan_status(&extra, &task_reference).await;
let response = self.settle(&pending.job, response)?;
if let JobInput::Transfer(p) = &mut pending.job {
p.tan_extra_sent();
}
for c in response.all_codes() {
info!("[FinTS] Poll: {} - {}", c.code, c.text);
}
if response.is_decoupled_pending() {
extend_notices(&mut pending.notices, self.inner.take_notices());
if let Wait::Tan(challenge) = &mut pending.wait
&& let TanKind::Decoupled {
polls_done,
next_wait,
..
} = &mut challenge.kind
{
*polls_done += 1;
let next_wait = *next_wait;
challenge.not_before = not_before_after(Timestamp::now(), next_wait);
}
let outcome = Outcome::Paused(pending.wait.clone(), pending.ticket.clone());
self.phase = Phase::Paused(Box::new(pending));
return Ok(outcome);
}
self.confirmed(pending, response).await
}
.await;
after_order(ids.as_ref(), outcome)?.into_step()
}
pub fn cancel<T: JobValue>(&mut self, resume: Resume<T>) -> Result<Cancelled> {
self.pending_for(&resume)?;
let pending = self.take_pending();
if pending.job.job() == Job::Open {
self.phase = Phase::Ended;
}
Ok(match &pending.job {
JobInput::Transfer(p) => p.cancelled(&pending.wait),
_ => Cancelled::NothingSent,
})
}
pub async fn end(mut self) -> Result<SessionState> {
self.check_in_flight()?;
self.inner.end_quietly().await;
Ok(self.capture_state())
}
pub fn session_state(&self) -> SessionState {
self.capture_state()
}
fn capture_state(&self) -> SessionState {
SessionState::capture(
self.inner.blz(),
self.inner.user_id(),
self.inner.system_id(),
self.inner.bank_params(),
)
}
fn opened(&self) -> Opened {
let p = self.inner.bank_params();
Opened {
accounts: p
.upd()
.map(|u| AccountInfo::from_upd(u, &self.bic))
.unwrap_or_default(),
tan_methods: p.tan_methods.clone(),
allowed_security_functions: p.allowed_security_functions.clone(),
selected_tan_method: p.selected_tan_method().cloned(),
}
}
fn check_in_flight(&mut self) -> Result<()> {
let Some(in_flight) = self.in_flight.take() else {
return Ok(());
};
warn!("[FinTS] A request was dropped mid-flight; the dialog has ended");
self.end_locally();
match in_flight {
InFlight::Message => Ok(()),
InFlight::Payment(ids) => Err(ids.unknown()),
}
}
fn end_locally(&mut self) {
self.phase = Phase::Ended;
self.inner.forget_dialog();
}
fn ready(&mut self) -> Result<()> {
self.check_in_flight()?;
match self.phase {
Phase::Open => Ok(()),
Phase::Paused(_) => Err(FinTSError::DialogPaused),
Phase::Ended => Err(FinTSError::DialogEnded),
}
}
fn pending_for<T: Sealed>(&mut self, resume: &Resume<T>) -> Result<&PendingJob> {
self.check_in_flight()?;
match &self.phase {
Phase::Paused(p) if p.ticket == resume.ticket && p.job.job() == T::JOB => Ok(p),
Phase::Ended => Err(FinTSError::DialogEnded),
_ => Err(FinTSError::WrongResume),
}
}
fn take_pending(&mut self) -> PendingJob {
match std::mem::replace(&mut self.phase, Phase::Open) {
Phase::Paused(p) => *p,
other => {
self.phase = other;
unreachable!("take_pending after pending_for")
}
}
}
fn job_failed(&mut self, job: &JobInput) {
if job.job() == Job::Open {
self.phase = Phase::Ended;
}
}
fn settle(&mut self, job: &JobInput, sent: Result<Response>) -> Result<Response> {
self.settle_message(job.job() == Job::Open, sent)
}
fn settle_message(&mut self, login: bool, sent: Result<Response>) -> Result<Response> {
self.in_flight = None;
match sent {
Ok(response) => {
self.last_message_at = Timestamp::now();
if response
.all_codes()
.any(|c| c.kind() == Kind::DialogAborted)
{
self.end_locally();
}
Ok(response)
}
Err(e) => {
if matches!(
e,
FinTSError::Transport { .. }
| FinTSError::Timeout
| FinTSError::Http { .. }
| FinTSError::Parse(_)
| FinTSError::InvalidResponse(_)
| FinTSError::Io(_)
) {
self.end_locally();
} else if login {
self.phase = Phase::Ended;
}
Err(e)
}
}
}
fn pause(
&mut self,
job: JobInput,
challenge: &protocol::TanChallenge,
notices: Vec<Notice>,
) -> Outcome {
let tan = TanChallenge::from_bank(challenge, self.inner.bank_params(), Timestamp::now());
let ticket = Ticket::Task(challenge.task_reference.clone());
self.pause_on(job, Wait::Tan(tan), ticket, notices)
}
fn pause_on(
&mut self,
job: JobInput,
wait: Wait,
ticket: Ticket,
notices: Vec<Notice>,
) -> Outcome {
let outcome = Outcome::Paused(wait.clone(), ticket.clone());
self.phase = Phase::Paused(Box::new(PendingJob {
ticket,
wait,
job,
notices,
}));
outcome
}
async fn start(&mut self, job: JobInput) -> Result<Outcome> {
self.start_with(job, Vec::new()).await
}
async fn start_with(&mut self, job: JobInput, notices: Vec<Notice>) -> Result<Outcome> {
self.ready()?;
self.inner.take_notices();
self.send_order(job, notices).await
}
async fn send_order(&mut self, mut job: JobInput, mut notices: Vec<Notice>) -> Result<Outcome> {
loop {
let Some((segment, code, _)) = job.order() else {
return Err(FinTSError::Internal("the login is not an order".into()));
};
self.in_flight = Some(InFlight::Message);
let response = self.inner.send_order(segment, code).await;
let response = self.settle(&job, response)?;
notices.extend(self.inner.take_notices());
if let Some(challenge) = response.order_tan_challenge()? {
return Ok(self.pause(job, &challenge, notices));
}
response.check_errors()?;
if !job.absorb(
&response,
&self.inner.bank_params().camt052_format(),
&mut notices,
) {
return Ok(Outcome::Done(
job.finish(&response, self.booking_id)?,
notices,
));
}
}
}
async fn confirmed(&mut self, mut pending: PendingJob, response: Response) -> Result<Outcome> {
extend_notices(&mut pending.notices, self.inner.take_notices());
if let Err(e) = response.check_errors() {
self.job_failed(&pending.job);
return Err(e);
}
if let JobInput::Transfer(p) = &pending.job {
let receipt = p.receipt(&response, self.inner.bank_params(), self.inner.now().date());
return Ok(Outcome::Done(Value::Transfer(receipt), pending.notices));
}
self.inner.ingest(&response);
let PendingJob {
mut job,
mut notices,
..
} = pending;
match job.order() {
None => Ok(Outcome::Done(Value::Opened(self.opened()), notices)),
Some((_, _, data))
if response.find_segment(data).is_some()
|| response.has_no_entries()
|| (matches!(job, JobInput::InstantStatus { .. })
&& response.has(Kind::InstantStatusQuery)) =>
{
if job.absorb(
&response,
&self.inner.bank_params().camt052_format(),
&mut notices,
) {
self.send_order(job, notices).await
} else {
Ok(Outcome::Done(
job.finish(&response, self.booking_id)?,
notices,
))
}
}
Some((_, code, data)) => {
info!("[FinTS] {code}: confirmation carried no {data}; sending the order again");
self.send_order(job, notices).await
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use jiff::civil::date;
#[test]
fn range_is_clamped_to_the_storage_period() {
let today = date(2026, 11, 18);
let r = |from, to| Range::new(from, to);
let (clamped, asked) = clamp_range(r(date(2026, 1, 1), today), today, Some(60));
assert_eq!(clamped, r(date(2026, 9, 19), today));
assert_eq!(asked, Some(date(2026, 1, 1)));
for (from, days) in [
(date(2026, 10, 1), Some(60)),
(date(2026, 9, 19), Some(60)),
(date(2000, 1, 1), None),
] {
assert_eq!(
clamp_range(r(from, today), today, days),
(r(from, today), None)
);
}
let (clamped, _) = clamp_range(r(date(2020, 1, 1), date(2020, 2, 1)), today, Some(60));
assert_eq!(clamped, r(date(2026, 9, 19), date(2026, 9, 19)));
}
#[test]
fn only_3955_makes_a_challenge_decoupled() {
use crate::types::{TanMethod, TanProcess};
let mut params = BankParams::new();
params.tan_methods = vec![TanMethod {
security_function: SecurityFunction::new("901"),
tan_process: TanProcess::TwoStep,
name: "App".into(),
needs_tan_medium: false,
decoupled_max_polls: -1,
wait_before_first_poll: 0,
wait_before_next_poll: 0,
is_decoupled: true,
hktan_version: 7,
zka_name: None,
decoupled_auto_polling: None,
challenge_structured: false,
}];
params.selected_security_function = SecurityFunction::new("901");
let bank = |decoupled| protocol::TanChallenge {
challenge: ChallengeText::new("TAN eingeben"),
challenge_hhduc: None,
task_reference: TaskReference::new("TASK-1"),
decoupled,
challenge_markup: false,
valid_until: None,
};
let now = Timestamp::now();
let typed = TanChallenge::from_bank(&bank(false), ¶ms, now);
assert!(matches!(typed.kind, TanKind::Typed { .. }), "{typed:?}");
let app = TanChallenge::from_bank(&bank(true), ¶ms, now);
assert!(matches!(app.kind, TanKind::Decoupled { .. }), "{app:?}");
}
fn camt_entry(reference: &str) -> Vec<u8> {
format!(
"<Document><BkToCstmrAcctRpt><Rpt><Ntry><Amt Ccy=\"EUR\">1.00</Amt>\
<CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>\
<BookgDt><Dt>2026-03-02</Dt></BookgDt>\
<AcctSvcrRef>{reference}</AcctSvcrRef></Ntry></Rpt></BkToCstmrAcctRpt></Document>"
)
.into_bytes()
}
fn ids(txs: &[Transaction]) -> Vec<Option<&str>> {
txs.iter().map(|t| t.booking_id.as_deref()).collect()
}
#[test]
fn statement_booking_ids_follow_the_rule_on_booked_camt_only() {
let rule = BookingIdSource::CamtEntryAcctSvcrRef;
let booked = [camt_entry("TESTREF-1"), camt_entry("TESTREF-2")];
let pending = [camt_entry("TESTREF-3")];
let s = parse_statement(StatementFormat::Camt, &booked, &pending, true, rule).unwrap();
assert_eq!(ids(&s.booked), [Some("TESTREF-1"), Some("TESTREF-2")]);
let Pending::Reported(p) = &s.pending else {
panic!("{:?}", s.pending)
};
assert_eq!(ids(p), [None]);
let generic = BookingIdSource::None;
let s = parse_statement(StatementFormat::Camt, &booked, &[], false, generic).unwrap();
assert_eq!(ids(&s.booked), [None, None]);
let repeated = [camt_entry("TESTREF-1"), camt_entry("TESTREF-1")];
let s = parse_statement(StatementFormat::Camt, &repeated, &[], false, rule).unwrap();
assert_eq!(ids(&s.booked), [None, None]);
}
#[test]
fn mt940_bookings_never_get_a_booking_id() {
let mt940 = b":20:STARTUMS\r\n:25:12030000/0000000201\r\n:28C:1\r\n\
:60F:C260301EUR100,00\r\n\
:61:2603020302D1,00NTRFNONREF//TESTBANKREF1\r\n:86:177?20SVWZ+Test\r\n\
:62F:C260302EUR99,00\r\n-"
.to_vec();
let rule = BookingIdSource::CamtEntryAcctSvcrRef;
let s = parse_statement(StatementFormat::Mt940, &[mt940], &[], false, rule).unwrap();
assert_eq!(s.booked.len(), 1);
assert_eq!(s.booked[0].bank_reference.as_deref(), Some("TESTBANKREF1"));
assert_eq!(s.booked[0].booking_id, None);
}
#[test]
fn pending_job_round_trips_through_json() {
let pending = PendingJob {
ticket: Ticket::Task(TaskReference::new("TASK0001")),
wait: Wait::Tan(TanChallenge {
challenge: ChallengeText::new("Bitte in der App freigeben"),
challenge_markup: false,
kind: TanKind::Decoupled {
first_wait: Some(Duration::from_secs(5)),
next_wait: Some(Duration::from_secs(2)),
max_polls: Some(10),
polls_done: 3,
auto_polling_allowed: Some(false),
},
valid_until: None,
not_before: Some(Timestamp::constant(1_740_830_405, 0)),
payee_check: None,
rejected: None,
}),
job: JobInput::Balance {
account: Account::new("DE02120300000000202051", "BYLADEM1001").unwrap(),
},
notices: Vec::new(),
};
let json = serde_json::to_string(&pending).unwrap();
let back: PendingJob = serde_json::from_str(&json).unwrap();
assert_eq!(back.challenge(), pending.challenge());
assert_eq!(back.ticket, pending.ticket);
assert_eq!(back.job.job(), Job::Balance);
assert_eq!(serde_json::to_string(&back).unwrap(), json);
}
}