Skip to main content

fints_client/
protocol.rs

1//! FinTS 3.0 Protocol State Machine (spec-aligned).
2//!
3//! Implements the dialog lifecycle as defined in FinTS 3.0 Formals (2017-10-06)
4//! and PIN/TAN Security (2020-07-10).
5//!
6//! ## Dialog types (spec Chapter C)
7//!
8//! - **Synchronization dialog**: HKIDN + HKVVB + HKSYN → get system_id → HKEND.
9//!   Marked by presence of HKSYN. Business segments are forbidden (banks return 9110).
10//! - **Normal dialog**: HKIDN + HKVVB [+ HKTAN:4] → [TAN confirmation] → business ops → HKEND.
11//!
12//! ## State machine (spec Chapter C, Section 6)
13//!
14//! Internal: the typestate `Dialog<S>` (`New`, `Synced`, `Open`,
15//! `TanPending`) keeps the dialog's authentication state in the type system.
16//! [`crate::jobs::Dialog`] wraps it for callers and adds the pause/resume
17//! phases, so the library never waits for a TAN or an app confirmation.
18//!
19//! ```text
20//!   Dialog<New>
21//!       ├── sync()           → (Dialog<Synced>, Response)      [sync dialog]
22//!       ├── init()           → InitResult                      [normal dialog]
23//!       │     ├── Opened(Dialog<Open>)                            0010/0020
24//!       │     └── TanRequired(Dialog<TanPending>, TanChallenge)   0030/3955
25//!       └── init_no_tan()    → (Dialog<Open>, Response)        [PIN-only login]
26//!
27//!   Dialog<Synced>
28//!       └── end()            → (BankParams, SystemId)
29//!
30//!   Dialog<Open>
31//!       └── send_order()     → Response                        [one order]
32//! ```
33
34use std::collections::BTreeSet;
35use std::marker::PhantomData;
36use tracing::{debug, info, warn};
37
38use jiff::civil::Date;
39
40use crate::error::{BankError, FinTSError, Result};
41use crate::message;
42use crate::parser::RawSegment;
43pub use crate::segments::Order;
44use crate::segments::read::{extract_allowed_security_functions, find_touchdown};
45
46use crate::quirks::QuirkChain;
47use crate::return_code::{
48    Category, Class, ClientWarning, Kind, Notice, NoticeDialog, ReturnCode, Scope,
49    looks_like_utf8_as_latin1,
50};
51use crate::transport::SharedTransport;
52use crate::types::*;
53
54mod params;
55mod tan;
56pub use params::{
57    AccountLimit, Allowance, AllowedJob, BalanceParams, Bpd, CamtParams, FormatLists,
58    HoldingsParams, InstantParams, InstantStatusParams, InstantSupport, JobDetail, JobParams,
59    JobVersion, LimitKind, ParamsError, PinTanParams, SepaParams, StatementParams, TanParams,
60    TanVersion, UnparsedParam, Upd, UpdAccount, UpdUsage, VersionMismatch, VopDelivery, VopParams,
61};
62use params::{bpd_after, upd_after};
63pub use tan::{
64    Retry, TanDecision, TanOverride, TanOverrides, TanReason, on_sca_required, order_tan,
65};
66
67// ═══════════════════════════════════════════════════════════════════════════════
68// Typestate markers (per spec dialog states)
69// ═══════════════════════════════════════════════════════════════════════════════
70
71/// Dialog not yet started. Can transition to `Synced` or `Open`/`TanPending`.
72#[derive(Debug)]
73pub(crate) struct New;
74/// Synchronization dialog: system_id obtained, BPD/UPD cached. No business ops allowed.
75#[derive(Debug)]
76pub(crate) struct Synced;
77/// Dialog is open and authenticated. Business segments can be sent.
78#[derive(Debug)]
79pub(crate) struct Open;
80/// A TAN challenge is pending (either from init or from a business segment).
81#[derive(Debug)]
82pub(crate) struct TanPending;
83
84// ═══════════════════════════════════════════════════════════════════════════════
85// Typed business segments — replaces raw Vec<DEG> at all internal boundaries
86// ═══════════════════════════════════════════════════════════════════════════════
87
88/// A typed FinTS business segment. Every field is validated at construction.
89/// This is the ONLY way to construct segments within the crate — raw DEG
90/// builders are never called directly from protocol or job code.
91#[derive(Debug, Clone)]
92pub(crate) enum Segment {
93    /// HKIDN: Identifikation (dialog init)
94    Identify {
95        blz: Blz,
96        user_id: UserId,
97        system_id: SystemId,
98    },
99    /// HKVVB: Verarbeitungsvorbereitung
100    ProcessPrep {
101        bpd_version: u16,
102        upd_version: u16,
103        product_id: ProductId,
104    },
105    /// HKSYN: Synchronisierung (get system_id)
106    Sync,
107    /// HKSAL: Saldenabfrage (balance request)
108    Balance { account: Account },
109    /// HKKAZ: Kontoumsätze (transaction request)
110    Transactions {
111        account: Account,
112        start_date: Date,
113        end_date: Date,
114        touchdown: Option<TouchdownPoint>,
115    },
116    /// HKCAZ: Kontoumsätze im camt-Format (CAMT.052 transaction request)
117    CamtTransactions {
118        account: Account,
119        start_date: Date,
120        end_date: Date,
121        touchdown: Option<TouchdownPoint>,
122    },
123    /// HKWPD: Wertpapierdepotaufstellung (securities holdings request)
124    Holdings {
125        account: Account,
126        currency: Option<Currency>,
127        touchdown: Option<TouchdownPoint>,
128    },
129    /// HKWDU: Depotumsätze (depot transactions request)
130    DepotTransactions {
131        account: Account,
132        start_date: Option<Date>,
133        end_date: Option<Date>,
134        touchdown: Option<TouchdownPoint>,
135    },
136    /// HKTAN process 4: initiate TAN for a referenced segment
137    TanProcess4 {
138        reference_seg: SegmentRef,
139        tan_medium: Option<TanMediumName>,
140    },
141    /// HKTAN process S: poll decoupled TAN status
142    TanPollDecoupled {
143        task_reference: TaskReference,
144        tan_medium: Option<TanMediumName>,
145    },
146    /// HKTAN process 2: submit TAN response
147    TanProcess2 {
148        task_reference: TaskReference,
149        tan_medium: Option<TanMediumName>,
150    },
151    /// HKEND: dialog end
152    End { dialog_id: DialogId },
153    /// HKCCS: SEPA credit transfer, the pain.001 bytes as built.
154    CreditTransfer {
155        account: Account,
156        descriptor: String,
157        pain: Vec<u8>,
158    },
159    /// HKIPZ: SEPA instant credit transfer at `version` (chosen before
160    /// the pain message was built); `convert` is v2's conversion flag.
161    InstantTransfer {
162        account: Account,
163        version: u16,
164        descriptor: String,
165        pain: Vec<u8>,
166        convert: Option<bool>,
167    },
168    /// HKIPS: status of an instant payment; `descriptors` are the pain
169    /// messages the client reads in the answer.
170    InstantStatus {
171        account: Account,
172        descriptors: Vec<String>,
173        order_id: String,
174    },
175    /// HKVPP: payee check; a poll carries the polling ID and touchdown.
176    VopCheck {
177        descriptors: Vec<String>,
178        polling_id: Option<Vec<u8>>,
179        touchdown: Option<String>,
180    },
181    /// HKVPA: release after the payee check.
182    VopExecute { vop_id: Vec<u8> },
183}
184
185impl Segment {
186    /// Encode with the given segment number, choosing segment versions from
187    /// the bank's BPD.
188    pub(crate) fn encode(&self, params: &BankParams, number: u16) -> Result<RawSegment> {
189        use crate::segments::{encode, request};
190        fn td(t: &Option<TouchdownPoint>) -> Option<&str> {
191            t.as_ref().map(TouchdownPoint::as_str)
192        }
193        let national = params.national_account_allowed();
194        let with_flag = |a: &Account| a.clone().with_kti_national(national);
195        match self {
196            Segment::Identify {
197                blz,
198                user_id,
199                system_id,
200            } => encode(
201                &request::hkidn(blz.as_str(), user_id.as_str(), system_id.as_str())?,
202                number,
203            ),
204            Segment::ProcessPrep {
205                bpd_version,
206                upd_version,
207                product_id,
208            } => encode(
209                &request::hkvvb(*bpd_version, *upd_version, product_id.as_str())?,
210                number,
211            ),
212            Segment::Sync => encode(&request::hksyn(), number),
213            Segment::End { dialog_id } => encode(&request::hkend(dialog_id.as_str())?, number),
214            Segment::TanProcess4 {
215                reference_seg,
216                tan_medium,
217            } => request::hktan(
218                params.hktan_version()?,
219                request::TanRequest::Start {
220                    segment: reference_seg.as_str(),
221                },
222                tan_medium.as_ref().map(|t| t.as_str()),
223                number,
224            ),
225            Segment::TanPollDecoupled {
226                task_reference,
227                tan_medium,
228            } => request::hktan(
229                params.hktan_version()?,
230                request::TanRequest::DecoupledStatus {
231                    task_reference: task_reference.as_str(),
232                },
233                tan_medium.as_ref().map(|t| t.as_str()),
234                number,
235            ),
236            Segment::TanProcess2 {
237                task_reference,
238                tan_medium,
239            } => request::hktan(
240                params.hktan_version()?,
241                request::TanRequest::Submit {
242                    task_reference: task_reference.as_str(),
243                },
244                tan_medium.as_ref().map(|t| t.as_str()),
245                number,
246            ),
247            Segment::CreditTransfer {
248                account,
249                descriptor,
250                pain,
251            } => {
252                let version = params.order_version(Order::Transfer)?;
253                request::hkccs(number, version, &with_flag(account), descriptor, pain)
254            }
255            Segment::InstantTransfer {
256                account,
257                version,
258                descriptor,
259                pain,
260                convert,
261            } => request::hkipz(
262                number,
263                *version,
264                &with_flag(account),
265                descriptor,
266                pain,
267                *convert,
268            ),
269            Segment::InstantStatus {
270                account,
271                descriptors,
272                order_id,
273            } => {
274                let version = params.order_version(Order::InstantStatus)?;
275                request::hkips(number, version, &with_flag(account), descriptors, order_id)
276            }
277            Segment::VopCheck {
278                descriptors,
279                polling_id,
280                touchdown,
281            } => {
282                let version = params.order_version(Order::VopCheck)?;
283                request::hkvpp(
284                    number,
285                    version,
286                    descriptors,
287                    polling_id.as_deref(),
288                    touchdown.as_deref(),
289                )
290            }
291            Segment::VopExecute { vop_id } => {
292                let version = params.order_version(Order::VopExecute)?;
293                request::hkvpa(number, version, vop_id)
294            }
295            Segment::Balance { account } => {
296                let version = params.order_version(Order::Balance)?;
297                request::hksal(number, version, &with_flag(account), None)
298            }
299            Segment::Transactions {
300                account,
301                start_date,
302                end_date,
303                touchdown,
304            } => {
305                let version = params.order_version(Order::Transactions)?;
306                request::hkkaz(
307                    number,
308                    version,
309                    &with_flag(account),
310                    *start_date,
311                    *end_date,
312                    td(touchdown),
313                )
314            }
315            Segment::CamtTransactions {
316                account,
317                start_date,
318                end_date,
319                touchdown,
320            } => {
321                let version = params.order_version(Order::Camt)?;
322                request::hkcaz(
323                    number,
324                    version,
325                    &with_flag(account),
326                    &params.camt052_format(),
327                    *start_date,
328                    *end_date,
329                    td(touchdown),
330                )
331            }
332            Segment::Holdings {
333                account,
334                currency,
335                touchdown,
336            } => {
337                let version = params.order_version(Order::Holdings)?;
338                request::hkwpd(
339                    number,
340                    version,
341                    account,
342                    currency.as_ref().map(|c| c.as_str()),
343                    td(touchdown),
344                )
345            }
346            Segment::DepotTransactions {
347                account,
348                start_date,
349                end_date,
350                touchdown,
351            } => {
352                let version = params.order_version(Order::DepotTransactions)?;
353                request::hkwdu(
354                    number,
355                    version,
356                    account,
357                    *start_date,
358                    *end_date,
359                    td(touchdown),
360                )
361            }
362        }
363    }
364}
365
366// ═══════════════════════════════════════════════════════════════════════════════
367// Result of dialog init — response-driven transition
368// ═══════════════════════════════════════════════════════════════════════════════
369
370/// Result of `Dialog::init()`. Per the spec, the bank either accepts the dialog
371/// (0010/0020) or requires SCA (0030/3955).
372pub(crate) enum InitResult {
373    /// Dialog opened, no TAN needed. Ready for business segments.
374    Opened(Dialog<Open>),
375    /// Bank requires TAN on init (SCA). Must confirm before business ops.
376    TanRequired(Dialog<TanPending>, TanChallenge),
377}
378
379// ═══════════════════════════════════════════════════════════════════════════════
380// Parsed bank response
381// ═══════════════════════════════════════════════════════════════════════════════
382
383/// Parsed response from the bank after sending a message.
384#[derive(Debug)]
385pub struct Response {
386    /// All segments from the response (including inner HNVSD segments).
387    pub segments: Vec<RawSegment>,
388    /// Return codes for the whole message (HIRMG), in wire order.
389    pub global_codes: Vec<ReturnCode>,
390    /// Return codes for segments of the sent message (HIRMS), in wire order.
391    pub segment_codes: Vec<ReturnCode>,
392}
393
394impl Response {
395    pub fn find_segments(&self, seg_type: &str) -> Vec<&RawSegment> {
396        self.segments
397            .iter()
398            .filter(|s| s.segment_type() == seg_type)
399            .collect()
400    }
401
402    pub fn find_segment(&self, seg_type: &str) -> Option<&RawSegment> {
403        self.segments.iter().find(|s| s.segment_type() == seg_type)
404    }
405
406    pub fn all_codes(&self) -> impl Iterator<Item = &ReturnCode> {
407        self.global_codes.iter().chain(self.segment_codes.iter())
408    }
409
410    /// The answer to a typed TAN rejects the TAN and leaves the order for
411    /// another one (docs/return-codes-design.md section 1): the class 9
412    /// codes are 9941 and, at most, the 9050 summary and a 9360 that still
413    /// leaves attempts. Gives the first 9941 and 9360's P1. `None` when
414    /// the bank ended the dialog (9800), deleted the order (9210), locked
415    /// the access (9931, 9360 without attempts), the TAN timed out or was
416    /// used (9951, 9943), or the codes are unreadable.
417    pub(crate) fn tan_rejection(&self) -> Option<(ReturnCode, Option<u32>)> {
418        if !matches!(self.check_errors(), Err(FinTSError::Bank(_))) {
419            return None;
420        }
421        let mut rejected = None;
422        let mut attempts_left = None;
423        for c in self.all_codes().filter(|c| c.is_error()) {
424            match c.kind() {
425                Kind::TanInvalid => {
426                    rejected.get_or_insert_with(|| c.clone());
427                }
428                Kind::PartialErrors => {}
429                Kind::LockAfterAttempts {
430                    attempts_left: Some(n),
431                } if n > 0 => attempts_left = Some(n),
432                _ => return None,
433            }
434        }
435        rejected.map(|c| (c, attempts_left))
436    }
437
438    /// True if any code has this kind.
439    pub(crate) fn has(&self, kind: Kind) -> bool {
440        self.all_codes().any(|c| c.kind() == kind)
441    }
442
443    /// Fills [`Scope::Segment`]'s `order` of every HIRMS code from the
444    /// sent message `request` (its segment numbers). Codes referring to a
445    /// number not in the request keep `None`.
446    fn name_orders(&mut self, request: &[RawSegment]) {
447        for code in &mut self.segment_codes {
448            if let Scope::Segment { number, order } = &mut code.scope {
449                *order = request
450                    .iter()
451                    .find(|s| s.segment_number() == *number)
452                    .map(|s| SegmentType::new(s.segment_type()));
453            }
454        }
455    }
456
457    /// All segments read with the codec's declarative definitions. A
458    /// segment without a definition, or one its definition rejects, comes
459    /// back as `ParsedSegment::Raw` with the error that says why
460    /// (docs/architecture.md 2.1, "parse what you can, keep the rest").
461    pub fn decode_segments(&self) -> Vec<crate::codec::ParsedSegment> {
462        crate::codec::parse_segments(self.segments.iter().cloned())
463    }
464
465    /// The codec errors of all segments that stayed raw for a reason other
466    /// than a missing definition.
467    pub fn segment_errors(&self) -> Vec<crate::codec::CodecError> {
468        self.decode_segments()
469            .into_iter()
470            .filter_map(|p| match p {
471                crate::codec::ParsedSegment::Raw { error, .. }
472                    if error.kind != crate::codec::ErrorKind::UnknownSegment =>
473                {
474                    Some(error)
475                }
476                _ => None,
477            })
478            .collect()
479    }
480
481    /// 0030 = order received, TAN required.
482    pub fn needs_tan(&self) -> bool {
483        self.has(Kind::TanRequired) || self.has(Kind::DecoupledInitiated)
484    }
485
486    /// 3955 = decoupled TAN (pushTAN initiated).
487    pub fn is_decoupled(&self) -> bool {
488        self.has(Kind::DecoupledInitiated)
489    }
490
491    /// A status request got no confirmation yet: 3956, or 3957 ("wait for
492    /// the push message") without 0020 in the same answer.
493    pub fn is_decoupled_pending(&self) -> bool {
494        self.has(Kind::DecoupledPending)
495            || (self.has(Kind::DecoupledAwaitPush) && !self.has(Kind::OrderExecuted))
496    }
497
498    /// 3010 = not available; after a data request banks send it for "no
499    /// entries".
500    pub fn has_no_entries(&self) -> bool {
501        self.has(Kind::NotAvailable)
502    }
503
504    /// 3076 = no strong authentication required (SCA exemption).
505    pub fn has_sca_exemption(&self) -> bool {
506        self.has(Kind::ScaExemption)
507    }
508
509    /// 3040 = more data available (touchdown/pagination).
510    /// Returns the touchdown point if found.
511    pub fn touchdown(&self) -> Option<TouchdownPoint> {
512        find_touchdown(&self.segment_codes).or_else(|| find_touchdown(&self.global_codes))
513    }
514
515    /// Extract HITAN challenge from response. No HITAN is `Ok(None)`; a
516    /// HITAN its definition rejects is [`FinTSError::SegmentUnreadable`].
517    pub(crate) fn get_tan_challenge(&self) -> Result<Option<TanChallenge>> {
518        let Some(raw) = self.find_segment("HITAN") else {
519            return Ok(None);
520        };
521        let Some(hitan) =
522            crate::segments::read::tan_challenge(raw).map_err(FinTSError::SegmentUnreadable)?
523        else {
524            return Ok(None);
525        };
526        if hitan.task_reference.is_empty() && hitan.challenge.is_empty() {
527            return Ok(None);
528        }
529        Ok(Some(TanChallenge {
530            challenge: ChallengeText::new(hitan.challenge),
531            challenge_hhduc: hitan.challenge_hhduc.map(HhdUcData),
532            task_reference: TaskReference::new(hitan.task_reference),
533            decoupled: self.is_decoupled(),
534            challenge_markup: false,
535            valid_until: hitan.valid_until,
536        }))
537    }
538
539    /// The TAN challenge of a business order the bank wants confirmed
540    /// (0030/3955 with HITAN), unless it granted an exemption (3076).
541    pub(crate) fn order_tan_challenge(&self) -> Result<Option<TanChallenge>> {
542        if self.needs_tan() && !self.has_sca_exemption() {
543            self.get_tan_challenge()
544        } else {
545            Ok(None)
546        }
547    }
548
549    /// Check for fatal errors. Returns `Ok(())` if no errors.
550    ///
551    /// The reported error is [`Response::select_error`]'s; a credentials
552    /// or system ID error wins even over unreadable HIRMG/HIRMS, which
553    /// otherwise give `InvalidResponse`.
554    pub fn check_errors(&self) -> Result<()> {
555        let selected = self.select_error();
556        // Credentials and system ID decide what the caller must do, even
557        // next to response codes the codec cannot read.
558        if let Some(e) = selected
559            .as_ref()
560            .filter(|e| matches!(e.category(), Category::Credentials(_) | Category::SystemId))
561        {
562            return Err(FinTSError::Bank(e.clone()));
563        }
564        // HIRMG/HIRMS the codec rejects: the bank's verdict is unknown, so
565        // do not treat the response as a success.
566        if let Some(error) = self
567            .segments
568            .iter()
569            .filter(|s| matches!(s.segment_type(), "HIRMG" | "HIRMS"))
570            .find_map(|s| crate::segments::read::response_codes(s).err())
571        {
572            return Err(FinTSError::InvalidResponse(format!(
573                "response codes unreadable: {error}"
574            )));
575        }
576        match selected {
577            Some(e) => Err(FinTSError::Bank(e)),
578            None => Ok(()),
579        }
580    }
581
582    /// The error to report when the response has class 9 codes
583    /// (docs/return-codes-design.md section 3), with all codes of the
584    /// response. Specific causes rank above the signature error 9340,
585    /// which ranks above the generic codes:
586    /// 1. a credentials code that names the cause (9942, 9910, 9930,
587    ///    9931), then a system ID code (9391), wherever they appear;
588    /// 2. else the first specific segment-scope error;
589    /// 3. else the first specific message-scope error (e.g. 9210 "BLZ does
590    ///    not match the user" next to 9340);
591    /// 4. else 9340 (signature not accepted), wherever it appears;
592    /// 5. else the first error, segment scope first.
593    ///
594    /// Specific means neither generic (9010, 9050, 9800: summaries or
595    /// consequences, not the reason) nor 9340.
596    pub fn select_error(&self) -> Option<BankError> {
597        fn errors(codes: &[ReturnCode]) -> impl Iterator<Item = &ReturnCode> {
598            codes.iter().filter(|c| c.is_error())
599        }
600        let all = || self.all_codes().filter(|c| c.is_error());
601        let specific = |c: &&ReturnCode| {
602            !matches!(
603                c.kind(),
604                Kind::GeneralError
605                    | Kind::PartialErrors
606                    | Kind::DialogAborted
607                    | Kind::SignatureInvalid
608            )
609        };
610        let named_credentials = |c: &&ReturnCode| {
611            matches!(c.category(), Some(Category::Credentials(_)))
612                && c.kind() != Kind::SignatureInvalid
613        };
614        let selected = all()
615            .find(named_credentials)
616            .or_else(|| all().find(|c| c.category() == Some(Category::SystemId)))
617            .or_else(|| errors(&self.segment_codes).find(specific))
618            .or_else(|| errors(&self.global_codes).find(specific))
619            .or_else(|| all().find(|c| c.kind() == Kind::SignatureInvalid))
620            .or_else(|| {
621                errors(&self.segment_codes)
622                    .chain(errors(&self.global_codes))
623                    .next()
624            })?;
625        Some(BankError::new(
626            selected.clone(),
627            self.all_codes().cloned().collect(),
628        ))
629    }
630
631    /// The codes of this response the caller should see: not class 0 or 9
632    /// and not consumed by the protocol (0030, 3040, 3076, 3920, 3955,
633    /// 3956, 3091, 3945, 3045; 3090, 3093, 3094 on HKVPP/HKVPA): the
634    /// transfer job acts on the VoP and instant codes itself.
635    pub fn notices(&self, dialog: NoticeDialog) -> Vec<Notice> {
636        self.all_codes()
637            .filter(|c| matches!(c.class(), Class::Note | Class::Warning | Class::Undefined))
638            .filter(|c| !Notice::is_consumed(c))
639            .cloned()
640            .map(|c| Notice::new(dialog, c))
641            .chain(self.client_warning(dialog))
642            .collect()
643    }
644
645    /// Heuristic check, once per response, of the free text of HIRMG and
646    /// HIRMS (code texts and parameters): UTF-8 sequences in an ISO 8859-1
647    /// answer. Statement bodies are not checked. The text stays as decoded.
648    fn client_warning(&self, dialog: NoticeDialog) -> Option<Notice> {
649        let garbled = self.all_codes().any(|c| {
650            looks_like_utf8_as_latin1(&c.text)
651                || c.parameters.iter().any(|p| looks_like_utf8_as_latin1(p))
652        });
653        garbled.then(|| Notice::client(dialog, ClientWarning::Utf8TextInLatin1))
654    }
655
656    /// Log the warnings no job turns into a notice of its own.
657    pub(crate) fn log_informational_codes(&self) {
658        for code in self.all_codes() {
659            match code.kind() {
660                Kind::VopNotRequired | Kind::VopApprovalNotPossible => {
661                    debug!(
662                        "[FinTS] {} (Verification of Payee): {}",
663                        code.code, code.text
664                    );
665                }
666                Kind::Other if code.class() == Class::Warning => {
667                    debug!("[FinTS] Warning {}: {}", code.code, code.text);
668                }
669                _ => {}
670            }
671        }
672    }
673
674    /// Extract allowed TAN security functions from code 3920.
675    pub fn allowed_security_functions(&self) -> Vec<SecurityFunction> {
676        extract_allowed_security_functions(&self.segment_codes)
677            .into_iter()
678            .chain(extract_allowed_security_functions(&self.global_codes))
679            .collect()
680    }
681}
682
683// ═══════════════════════════════════════════════════════════════════════════════
684// TAN challenge
685// ═══════════════════════════════════════════════════════════════════════════════
686
687#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
688pub(crate) struct TanChallenge {
689    pub challenge: ChallengeText,
690    pub challenge_hhduc: Option<HhdUcData>,
691    pub task_reference: TaskReference,
692    pub decoupled: bool,
693    /// HITANS "Challenge strukturiert" of the TAN method in use: the
694    /// challenge text may carry markup. The response alone does not know
695    /// the method; [`BankParams::challenge_structured`] sets it.
696    pub challenge_markup: bool,
697    /// HITAN "Gültigkeitsdatum und -uhrzeit für Challenge" (bank local
698    /// time), when the bank sends one.
699    pub valid_until: Option<jiff::civil::DateTime>,
700}
701
702// ═══════════════════════════════════════════════════════════════════════════════
703// Bank parameters
704// ═══════════════════════════════════════════════════════════════════════════════
705
706/// The bank's parameter data as one dialog knows it.
707///
708/// The sources are `bpd_segments` (the bank parameters: HIBPA, HIKOM, the
709/// TAN segments HITANS and HIPINS, and every `HI…S` order parameter
710/// segment) and `upd_segments` (the user parameters: HIUPA and its HIUPD),
711/// both byte for byte as received. All other fields are read from them. An
712/// answer with a new HIBPA or HIUPA starts a new set; segments are never
713/// merged across answers.
714#[derive(Debug, Clone)]
715pub struct BankParams {
716    pub bpd_version: u16,
717    pub upd_version: u16,
718    pub bpd_segments: Vec<RawSegment>,
719    pub upd_segments: Vec<RawSegment>,
720    /// The TAN methods of `bpd`, kept as a list for the selection logic.
721    pub tan_methods: Vec<TanMethod>,
722    pub selected_security_function: SecurityFunction,
723    pub selected_tan_medium: Option<TanMediumName>,
724    pub allowed_security_functions: Vec<SecurityFunction>,
725    pub preferred_security_function: Option<SecurityFunction>,
726    /// Set when the bank reported code 3072 (changed access data): the new
727    /// user ID to use from the next dialog on.
728    pub changed_user_id: Option<UserId>,
729    /// Order codes the bank turned out to want HKTAN for although HIPINS did
730    /// not say so. Empty until the 9075 retry learns them.
731    pub tan_required_learned: BTreeSet<SegmentType>,
732    bpd: Option<Bpd>,
733    upd: Option<Upd>,
734}
735
736impl BankParams {
737    pub fn new() -> Self {
738        Self {
739            bpd_version: 0,
740            upd_version: 0,
741            bpd_segments: Vec::new(),
742            upd_segments: Vec::new(),
743            tan_methods: Vec::new(),
744            selected_security_function: SecurityFunction::pin_only(),
745            selected_tan_medium: None,
746            allowed_security_functions: Vec::new(),
747            preferred_security_function: None,
748            changed_user_id: None,
749            tan_required_learned: BTreeSet::new(),
750            bpd: None,
751            upd: None,
752        }
753    }
754
755    /// The typed BPD, built from `bpd_segments`; `None` until a readable
756    /// HIBPA has arrived.
757    pub fn bpd(&self) -> Option<&Bpd> {
758        self.bpd.as_ref()
759    }
760
761    /// The typed UPD, built from `upd_segments`. A dialog-only UPD
762    /// (version 0) is held for the dialog but not stored by
763    /// [`SessionState`](crate::SessionState).
764    pub fn upd(&self) -> Option<&Upd> {
765        self.upd.as_ref()
766    }
767
768    /// Ingest BPD/UPD/HISYN/3920/3072 from a response.
769    pub fn ingest_response(&mut self, response: &Response, system_id: &mut SystemId) {
770        let segs = &response.segments;
771
772        if let Some(bpd) = bpd_after(&self.bpd_segments, segs) {
773            self.set_bpd(bpd);
774        }
775        if let Some(upd) = upd_after(segs) {
776            self.set_upd(upd);
777        }
778
779        if let Some(sid) = segs
780            .iter()
781            .find(|s| s.segment_type() == "HISYN")
782            .and_then(crate::segments::read::system_id)
783            && !sid.is_empty()
784        {
785            info!("[FinTS] System ID assigned");
786            *system_id = SystemId::new(sid);
787        }
788
789        let allowed = response.allowed_security_functions();
790        if !allowed.is_empty() {
791            self.allowed_security_functions = allowed;
792        }
793
794        // 3072: access data changed. The new user/customer ID is passed on to the
795        // caller; we also drop the UPD so the next dialog reloads it.
796        for code in response.all_codes() {
797            if let Kind::UserDataChanged { user_id, .. } = code.kind() {
798                warn!(
799                    "[FinTS] 3072 changed access data (new user ID {})",
800                    if user_id.is_some() {
801                        "given"
802                    } else {
803                        "not given"
804                    }
805                );
806                if let Some(uid) = user_id {
807                    self.changed_user_id = Some(UserId::new(uid));
808                }
809                if !segs.iter().any(|s| s.segment_type() == "HIUPA") {
810                    self.invalidate_upd();
811                }
812            }
813        }
814    }
815
816    /// Replace the BPD and rebuild the typed model, the version and the TAN
817    /// methods from it. A HIBPA the codec cannot read leaves no model and
818    /// version 0, so the next dialog fetches the BPD again.
819    pub(crate) fn set_bpd(&mut self, segments: Vec<RawSegment>) {
820        match Bpd::from_segments(&segments) {
821            Ok(bpd) => {
822                self.bpd_version = bpd.version;
823                // Only methods in a HITANS version we can build are offered.
824                self.tan_methods = bpd
825                    .tan_methods()
826                    .filter(|m| crate::segments::request::HKTAN_VERSIONS.contains(&m.hktan_version))
827                    .cloned()
828                    .collect();
829                self.bpd = Some(bpd);
830            }
831            Err(e) => {
832                if !segments.is_empty() {
833                    warn!("[FinTS] BPD not usable: {e}");
834                }
835                if matches!(e, ParamsError::Unreadable(..)) {
836                    self.bpd_version = 0;
837                }
838                self.tan_methods.clear();
839                self.bpd = None;
840            }
841        }
842        info!(
843            "[FinTS] BPD v{}: {} segments, {} TAN methods",
844            self.bpd_version,
845            segments.len(),
846            self.tan_methods.len(),
847        );
848        self.bpd_segments = segments;
849    }
850
851    /// Replace the UPD and rebuild the typed model, the version and the
852    /// accounts from it.
853    pub(crate) fn set_upd(&mut self, segments: Vec<RawSegment>) {
854        match Upd::from_segments(&segments) {
855            Ok(upd) => {
856                self.upd_version = upd.version;
857                self.upd = Some(upd);
858            }
859            Err(e) => {
860                if !segments.is_empty() {
861                    warn!("[FinTS] UPD not usable: {e}");
862                }
863                if matches!(e, ParamsError::Unreadable(..)) {
864                    self.upd_version = 0;
865                }
866                self.upd = None;
867            }
868        }
869        info!(
870            "[FinTS] UPD v{}: {} accounts",
871            self.upd_version,
872            self.upd.as_ref().map_or(0, |u| u.accounts().len())
873        );
874        self.upd_segments = segments;
875    }
876
877    /// Drop the user parameters; HKVVB then announces UPD version 0 and the
878    /// bank sends them anew.
879    pub fn invalidate_upd(&mut self) {
880        self.upd = None;
881        self.upd_segments = Vec::new();
882        self.upd_version = 0;
883    }
884
885    /// The TAN methods of every HITANS version the bank sent, including
886    /// versions the client cannot build (`tan_methods` holds only the
887    /// buildable ones once a BPD is set). Empty when no HITANS is known.
888    fn hitans_methods(&self) -> Vec<&TanMethod> {
889        match &self.bpd {
890            Some(bpd) => bpd.tan_methods().collect(),
891            None => self.tan_methods.iter().collect(),
892        }
893    }
894
895    /// HKTAN version to send: the highest version in
896    /// `HKTAN_VERSIONS` among the
897    /// HITANS versions that list the selected security function (Formals
898    /// "Segmentversion": the HITANS version of a method is its HKTAN version).
899    /// There is no fallback to another method's version; when none is
900    /// buildable the result is [`FinTSError::VersionMismatch`] naming the
901    /// HITANS versions that list the method and the ones we implement.
902    ///
903    /// No HITANS known (first dialog, before any BPD): 7, the highest we
904    /// implement. Evidence: the committed Consorsbank trace (live 2026-11-16)
905    /// sends `HKTAN:5:7+4+HKIDN` at dialog init and the bank accepts it.
906    pub fn hktan_version(&self) -> Result<u16> {
907        let implemented = crate::segments::request::HKTAN_VERSIONS;
908        let methods = self.hitans_methods();
909        if methods.is_empty() {
910            return Ok(implemented.iter().copied().max().unwrap_or(7));
911        }
912        let mut offered: Vec<u16> = methods
913            .iter()
914            .filter(|m| m.security_function == self.selected_security_function)
915            .map(|m| m.hktan_version)
916            .collect();
917        offered.sort_unstable();
918        offered.dedup();
919        offered
920            .iter()
921            .rev()
922            .copied()
923            .find(|v| implemented.contains(v))
924            .ok_or_else(|| {
925                FinTSError::VersionMismatch(VersionMismatch {
926                    code: SegmentType::new("HKTAN"),
927                    offered,
928                    implemented: implemented.to_vec(),
929                    formats: None,
930                })
931            })
932    }
933
934    /// The HKTAN version for the dialog-initialisation message, or `None`
935    /// when it carries no HKTAN. The init message allows HKTAN 6 and 7 only
936    /// (PIN/TAN spec B.4, "Dialoginitialisierung": "ein Segment HKTAN ab
937    /// Segmentversion #6"), so a selected method that appears only in HITANS
938    /// below 6 gets no HKTAN at init; its orders still use its own version.
939    /// A pin-only selection (999) with HITANS known has no method to signal
940    /// and also gets none.
941    pub fn init_hktan_version(&self) -> Result<Option<u16>> {
942        if self.selected_security_function == SecurityFunction::pin_only()
943            && !self.hitans_methods().is_empty()
944        {
945            return Ok(None);
946        }
947        let version = self.hktan_version()?;
948        Ok((version >= 6).then_some(version))
949    }
950
951    /// Whether the bank allows national account details next to the IBAN
952    /// (HISPAS, parameter "Nationale Kontoverbindung erlaubt"). `false`
953    /// when the BPD has no HISPAS.
954    pub fn national_account_allowed(&self) -> bool {
955        self.bpd
956            .as_ref()
957            .and_then(Bpd::sepa)
958            .is_some_and(|s| s.national_account_allowed)
959    }
960
961    /// The version of `order` to send: the highest version the bank offers
962    /// in its BPD that this client implements ([`Order::implemented`],
963    /// Formals C.10). Pure on the parameters, so it also answers "can this
964    /// bank do X" without a dialog.
965    ///
966    /// - No BPD known → [`FinTSError::NoBpd`]: orders run only after
967    ///   synchronisation, and no version is guessed.
968    /// - The bank offers no version we implement, or not the order at all →
969    ///   [`FinTSError::VersionMismatch`] naming both sides, instead of sending
970    ///   something the bank will reject.
971    pub fn order_version(&self, order: Order) -> Result<u16> {
972        let code = order.code();
973        let Some(bpd) = &self.bpd else {
974            return Err(FinTSError::NoBpd {
975                code: SegmentType::new(code),
976            });
977        };
978        let chosen = bpd.highest_common(code, order.implemented());
979        debug!(
980            "[FinTS] Version negotiation {}: we implement {:?} → {:?}",
981            code,
982            order.implemented(),
983            chosen
984        );
985        chosen.map_err(FinTSError::VersionMismatch)
986    }
987
988    /// The bank's storage period in days ("Speicherzeitraum" of HIKAZS or
989    /// HICAZS, Messages C.2.1.1.1 / C.2.3.1.1.1) for the version we would
990    /// send of `order` (`Order::Transactions` or `Order::Camt`). `None`
991    /// without a BPD, for another order, or when the bank sends 0.
992    pub fn days_stored(&self, order: Order) -> Option<u32> {
993        let version = self.order_version(order).ok()?;
994        let job = self.bpd.as_ref()?.job(order.code())?;
995        match &job.versions.get(&version)?.detail {
996            JobDetail::Statement(p) => Some(p.days_stored),
997            JobDetail::Camt(p) => Some(p.days_stored),
998            _ => None,
999        }
1000        .filter(|d| *d > 0)
1001    }
1002
1003    /// The camt.052 format to request in HKCAZ: the highest `camt.052.001.NN`
1004    /// the bank lists in HICAZS, compared by the number NN. Among equal
1005    /// versions the descriptor without `.xsd` wins. The bank's own string
1006    /// is sent. camt.052.001.02 when it lists none.
1007    /// All camt.052 versions parse with [`crate::camt::parse_camt052`].
1008    pub fn camt052_format(&self) -> String {
1009        self.bpd
1010            .iter()
1011            .flat_map(|b| b.camt_formats())
1012            .filter_map(|f| Some((crate::camt::camt052_version(f.as_bytes())?, f)))
1013            .max_by(|(va, a), (vb, b)| {
1014                va.cmp(vb)
1015                    .then_with(|| b.ends_with(".xsd").cmp(&a.ends_with(".xsd")))
1016            })
1017            .map(|(_, f)| f)
1018            .cloned()
1019            .unwrap_or_else(|| crate::segments::request::CAMT052_DEFAULT.to_string())
1020    }
1021
1022    /// Select the best security function from 3920 allowed list.
1023    pub fn select_security_function(&mut self) {
1024        let allowed = &self.allowed_security_functions;
1025        if allowed.is_empty() {
1026            // No 3920 list (yet): honor a cached preference the BPD knows about.
1027            if let Some(pref) = &self.preferred_security_function
1028                && self
1029                    .tan_methods
1030                    .iter()
1031                    .any(|m| &m.security_function == pref)
1032            {
1033                self.selected_security_function = pref.clone();
1034            }
1035            return;
1036        }
1037
1038        // A method that no buildable HITANS version lists is not offered:
1039        // a stored preference for it is ignored like an unknown method, and
1040        // the automatic choice skips it. Without HITANS everything is open.
1041        let pin_only = SecurityFunction::pin_only();
1042        let methods = &self.tan_methods;
1043        let available = |sf: &SecurityFunction| {
1044            methods.is_empty()
1045                || *sf == pin_only
1046                || methods.iter().any(|m| &m.security_function == sf)
1047        };
1048        if let Some(ref pref) = self.preferred_security_function
1049            && allowed.contains(pref)
1050            && available(pref)
1051        {
1052            self.selected_security_function = pref.clone();
1053            return;
1054        }
1055
1056        let chosen = allowed
1057            .iter()
1058            .filter(|sf| *sf != &pin_only && available(sf))
1059            .max_by_key(|sf| {
1060                methods
1061                    .iter()
1062                    .find(|m| &m.security_function == *sf)
1063                    .map(|m| if m.is_decoupled { 2i32 } else { 1 })
1064                    .unwrap_or(0)
1065            });
1066
1067        if let Some(sf) = chosen {
1068            info!("[FinTS] Selected security function: {}", sf);
1069            self.selected_security_function = sf.clone();
1070        }
1071    }
1072
1073    pub fn is_decoupled(&self) -> bool {
1074        self.tan_methods
1075            .iter()
1076            .find(|m| m.security_function == self.selected_security_function)
1077            .map(|m| m.is_decoupled)
1078            .unwrap_or(false)
1079    }
1080
1081    /// HITANS "Challenge strukturiert" of the TAN method in use.
1082    pub fn challenge_structured(&self) -> bool {
1083        self.tan_methods
1084            .iter()
1085            .find(|m| m.security_function == self.selected_security_function)
1086            .map(|m| m.challenge_structured)
1087            .unwrap_or(false)
1088    }
1089
1090    /// Whether the chosen method wants a TAN medium named in HKTAN. Asks
1091    /// the first HITANS entry of the method, as the order lists them.
1092    pub fn needs_tan_medium(&self) -> bool {
1093        let chosen = &self.selected_security_function;
1094        let first = self
1095            .tan_methods
1096            .iter()
1097            .find(|m| m.security_function == *chosen);
1098        first.is_some_and(|m| m.needs_tan_medium)
1099    }
1100
1101    /// The chosen method's HITANS entry. When several HITANS versions list
1102    /// it, the entry of the highest version, which is the HKTAN we send.
1103    pub fn selected_tan_method(&self) -> Option<&TanMethod> {
1104        let chosen = &self.selected_security_function;
1105        let mut best: Option<&TanMethod> = None;
1106        for method in self
1107            .tan_methods
1108            .iter()
1109            .filter(|m| m.security_function == *chosen)
1110        {
1111            if best.is_none_or(|b| method.hktan_version >= b.hktan_version) {
1112                best = Some(method);
1113            }
1114        }
1115        best
1116    }
1117
1118    /// How often and how long to ask for the status of a decoupled
1119    /// approval, from the chosen method's HITANS 7 entry.
1120    pub fn decoupled_params(&self) -> DecoupledParams {
1121        let Some(method) = self.selected_tan_method() else {
1122            return DecoupledParams::default();
1123        };
1124        // HITANS gives seconds; 0 and the -1 we store for "not sent" both
1125        // mean no requirement.
1126        let wait = |seconds: i32| {
1127            (seconds > 0).then(|| std::time::Duration::from_secs(seconds.unsigned_abs().into()))
1128        };
1129        // A maximum of 0 means no limit, the same as no maximum.
1130        let max_polls =
1131            (method.decoupled_max_polls > 0).then(|| method.decoupled_max_polls.unsigned_abs());
1132        DecoupledParams {
1133            wait_before_first_poll: wait(method.wait_before_first_poll),
1134            wait_before_next_poll: wait(method.wait_before_next_poll),
1135            max_polls,
1136            auto_polling_allowed: method.decoupled_auto_polling,
1137        }
1138    }
1139}
1140
1141impl Default for BankParams {
1142    fn default() -> Self {
1143        Self::new()
1144    }
1145}
1146
1147// ═══════════════════════════════════════════════════════════════════════════════
1148// Decoupled TAN polling
1149// ═══════════════════════════════════════════════════════════════════════════════
1150
1151/// The bank's rules for status requests (HKTAN process S) while a
1152/// decoupled approval is pending, from HITANS 7. `None` everywhere the
1153/// bank set no rule.
1154#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1155pub struct DecoupledParams {
1156    /// Wait at least this long before the first status request.
1157    pub wait_before_first_poll: Option<std::time::Duration>,
1158    /// Wait at least this long between two status requests.
1159    pub wait_before_next_poll: Option<std::time::Duration>,
1160    /// Send no more status requests than this.
1161    pub max_polls: Option<u32>,
1162    /// Whether the client may ask without the user confirming first.
1163    pub auto_polling_allowed: Option<bool>,
1164}
1165
1166// ═══════════════════════════════════════════════════════════════════════════════
1167// Dialog<S> — the typestate dialog
1168// ═══════════════════════════════════════════════════════════════════════════════
1169
1170pub(crate) struct Dialog<S: std::fmt::Debug> {
1171    transport: SharedTransport,
1172    url: String,
1173    quirks: QuirkChain,
1174    blz: Blz,
1175    user_id: UserId,
1176    pin: Pin,
1177    system_id: SystemId,
1178    product_id: ProductId,
1179    dialog_id: DialogId,
1180    message_number: u16,
1181    pub params: BankParams,
1182    /// The bank profile's HKTAN overrides, beating HIPINS.
1183    tan_overrides: TanOverrides,
1184    /// Notices of the messages since the last [`Dialog::take_notices`].
1185    notices: Vec<Notice>,
1186    /// The dialog the notices are tagged with.
1187    notice_dialog: NoticeDialog,
1188    /// Pinned local time ([`crate::BankClient::with_now`]), else the wall clock.
1189    now: Option<jiff::civil::DateTime>,
1190    _state: PhantomData<S>,
1191}
1192
1193impl<S: std::fmt::Debug> std::fmt::Debug for Dialog<S> {
1194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1195        f.debug_struct("Dialog")
1196            .field("blz", &self.blz)
1197            .field("user_id", &self.user_id)
1198            .field("system_id", &self.system_id)
1199            .field("dialog_id", &self.dialog_id)
1200            .field("message_number", &self.message_number)
1201            .field("state", &std::any::type_name::<S>())
1202            .finish()
1203    }
1204}
1205
1206// Note: Pin intentionally Debug-redacted (shows "Pin(****)")
1207
1208// ── Shared internals (all states) ───────────────────────────────────────────
1209
1210impl<S: std::fmt::Debug> Dialog<S> {
1211    pub fn system_id(&self) -> &SystemId {
1212        &self.system_id
1213    }
1214    /// The notices of every message exchanged since the last call (or the
1215    /// dialog's start), including touchdown pages and TAN resubmits.
1216    pub fn take_notices(&mut self) -> Vec<Notice> {
1217        std::mem::take(&mut self.notices)
1218    }
1219    pub fn bank_params(&self) -> &BankParams {
1220        &self.params
1221    }
1222    pub(crate) fn tan_overrides(&self) -> &TanOverrides {
1223        &self.tan_overrides
1224    }
1225
1226    /// The dialog's local time: pinned, else the wall clock.
1227    pub(crate) fn now(&self) -> jiff::civil::DateTime {
1228        self.now
1229            .unwrap_or_else(|| jiff::ZonedDateTime::now().datetime())
1230    }
1231
1232    /// Build the standard HKIDN segment for this dialog.
1233    fn identify_segment(&self) -> Segment {
1234        Segment::Identify {
1235            blz: self.blz.clone(),
1236            user_id: self.user_id.clone(),
1237            system_id: self.system_id.clone(),
1238        }
1239    }
1240
1241    /// Build the standard HKVVB segment for this dialog.
1242    fn process_prep_segment(&self) -> Segment {
1243        Segment::ProcessPrep {
1244            bpd_version: self.params.bpd_version,
1245            upd_version: self.params.upd_version,
1246            product_id: self.product_id.clone(),
1247        }
1248    }
1249
1250    /// The next message of this dialog around `segments`, signed with the
1251    /// PIN and, when given, the TAN (HNSHA).
1252    fn message(&self, segments: &[Segment], tan: Option<&str>) -> Result<Vec<u8>> {
1253        let signer = message::SecurityContext {
1254            dialog_id: self.dialog_id.as_str(),
1255            message_number: self.message_number,
1256            blz: self.blz.as_str(),
1257            user_id: self.user_id.as_str(),
1258            system_id: self.system_id.as_str(),
1259            pin: self.pin.as_str(),
1260            tan,
1261            security_function: self.params.selected_security_function.as_str(),
1262        };
1263        message::build_from_segments(&signer, segments, &self.params, self.now())
1264    }
1265
1266    /// Sends `segments` signed with the PIN only.
1267    async fn send_segments(&mut self, segments: &[Segment]) -> Result<Response> {
1268        self.send(segments, None).await
1269    }
1270
1271    /// Sends `segments` with `tan` in the signature closing segment.
1272    async fn send_segments_with_tan(
1273        &mut self,
1274        segments: &[Segment],
1275        tan: &str,
1276    ) -> Result<Response> {
1277        self.send(segments, Some(tan)).await
1278    }
1279
1280    async fn send(&mut self, segments: &[Segment], tan: Option<&str>) -> Result<Response> {
1281        let request = self.message(segments, tan)?;
1282        if tan.is_none() {
1283            // Masked by segment (PIN, TAN, IDs, accounts); cut by characters,
1284            // since a byte index can fall inside an umlaut.
1285            let masked: String = crate::mask::mask_for_log(&request)
1286                .chars()
1287                .take(500)
1288                .collect();
1289            info!("[FinTS] Outgoing ({} bytes): {masked}", request.len());
1290        }
1291        let answer = self.exchange(&request).await?;
1292        let response = parse_answer(&answer, self.message_number - 1, &request)?;
1293        response.log_informational_codes();
1294        self.notices.extend(response.notices(self.notice_dialog));
1295        Ok(response)
1296    }
1297
1298    async fn send_end(&mut self) -> Result<()> {
1299        if !self.dialog_id.is_assigned() {
1300            return Ok(());
1301        }
1302        debug!("Ending dialog {}", self.dialog_id);
1303        let end = [Segment::End {
1304            dialog_id: self.dialog_id.clone(),
1305        }];
1306        let msg_bytes = self.message(&end, None)?;
1307        let _ = self.exchange(&msg_bytes).await;
1308        self.dialog_id = DialogId::unassigned();
1309        Ok(())
1310    }
1311
1312    /// One request and its answer, both through the quirk chain. The next
1313    /// message of the dialog gets the next number.
1314    async fn exchange(&mut self, request: &[u8]) -> Result<Vec<u8>> {
1315        let number = self.message_number;
1316        self.message_number = number + 1;
1317        let Self {
1318            transport,
1319            url,
1320            quirks,
1321            dialog_id,
1322            ..
1323        } = &*self;
1324        let ctx = crate::quirks::QuirkContext {
1325            hbci_version: "300",
1326            dialog_id: dialog_id.as_str(),
1327            message_number: number,
1328        };
1329        crate::transport::exchange(transport.as_ref(), url, quirks, &ctx, request).await
1330    }
1331
1332    /// Sends a dialog initialisation (or another message that may carry
1333    /// BPD and UPD) and takes over what the answer hands out: the dialog
1334    /// ID from its header, and parameters, system ID and allowed methods.
1335    async fn send_and_adopt(&mut self, segments: &[Segment]) -> Result<Response> {
1336        let response = self.send_segments(segments).await?;
1337        let header = response.find_segment("HNHBK");
1338        let assigned = header
1339            .and_then(crate::segments::read::message_header)
1340            .map(|(id, _)| DialogId::new(id))
1341            .filter(DialogId::is_assigned);
1342        if let Some(id) = assigned {
1343            self.dialog_id = id;
1344        }
1345        self.params.ingest_response(&response, &mut self.system_id);
1346        Ok(response)
1347    }
1348
1349    pub(crate) fn blz(&self) -> &Blz {
1350        &self.blz
1351    }
1352
1353    pub(crate) fn user_id(&self) -> &UserId {
1354        &self.user_id
1355    }
1356
1357    pub(crate) fn url(&self) -> &str {
1358        &self.url
1359    }
1360
1361    pub(crate) fn dialog_id(&self) -> &DialogId {
1362        &self.dialog_id
1363    }
1364
1365    /// The number the next message will carry.
1366    pub(crate) fn message_number(&self) -> u16 {
1367        self.message_number
1368    }
1369
1370    /// Take BPD, UPD, system ID, 3920 and 3072 from a response.
1371    pub(crate) fn ingest(&mut self, response: &Response) {
1372        self.params.ingest_response(response, &mut self.system_id);
1373    }
1374
1375    /// HKTAN process 2 for `task_reference`, after the `extra` segments
1376    /// (HKVPA for a payment, else none), with `tan` in HNSHA (PIN/TAN
1377    /// B.4.2). Works for the login and for any order. Returns the bank's
1378    /// answer unchecked.
1379    pub(crate) async fn send_tan(
1380        &mut self,
1381        extra: &[Segment],
1382        task_reference: &TaskReference,
1383        tan: &str,
1384    ) -> Result<Response> {
1385        let mut segments = extra.to_vec();
1386        segments.push(Segment::TanProcess2 {
1387            task_reference: task_reference.clone(),
1388            tan_medium: self.params.selected_tan_medium.clone(),
1389        });
1390        self.send_segments_with_tan(&segments, tan).await
1391    }
1392
1393    /// One decoupled status request for `task_reference` (HKTAN process S,
1394    /// or 2 before HKTAN 7), after the `extra` segments (HKVPA on a
1395    /// payment's first poll, else none). Returns the bank's answer
1396    /// unchecked.
1397    pub(crate) async fn send_tan_status(
1398        &mut self,
1399        extra: &[Segment],
1400        task_reference: &TaskReference,
1401    ) -> Result<Response> {
1402        let mut segments = extra.to_vec();
1403        segments.push(Segment::TanPollDecoupled {
1404            task_reference: task_reference.clone(),
1405            tan_medium: self.params.selected_tan_medium.clone(),
1406        });
1407        self.send_segments(&segments).await
1408    }
1409
1410    /// HKEND, best effort; nothing when the dialog has no ID (never
1411    /// opened, or forgotten).
1412    pub(crate) async fn end_quietly(&mut self) {
1413        self.send_end().await.ok();
1414    }
1415
1416    /// Forget the dialog ID: the bank ended the dialog, or its message
1417    /// number is unknown, so no HKEND is sent for it.
1418    pub(crate) fn forget_dialog(&mut self) {
1419        self.dialog_id = DialogId::unassigned();
1420    }
1421
1422    pub(crate) fn transition<T: std::fmt::Debug>(self) -> Dialog<T> {
1423        Dialog {
1424            transport: self.transport,
1425            url: self.url,
1426            quirks: self.quirks,
1427            blz: self.blz,
1428            user_id: self.user_id,
1429            pin: self.pin,
1430            system_id: self.system_id,
1431            product_id: self.product_id,
1432            dialog_id: self.dialog_id,
1433            message_number: self.message_number,
1434            params: self.params,
1435            tan_overrides: self.tan_overrides,
1436            notices: self.notices,
1437            notice_dialog: self.notice_dialog,
1438            now: self.now,
1439            _state: PhantomData,
1440        }
1441    }
1442}
1443
1444// ── Dialog<New> ─────────────────────────────────────────────────────────────
1445
1446impl Dialog<New> {
1447    pub fn new(
1448        url: &str,
1449        blz: &Blz,
1450        user_id: &UserId,
1451        pin: &Pin,
1452        product_id: &ProductId,
1453    ) -> Result<Self> {
1454        Ok(Self {
1455            transport: crate::transport::default_transport()?,
1456            url: url.to_string(),
1457            quirks: QuirkChain::default(),
1458            blz: blz.clone(),
1459            user_id: user_id.clone(),
1460            pin: pin.clone(),
1461            system_id: SystemId::unassigned(),
1462            product_id: product_id.clone(),
1463            dialog_id: DialogId::unassigned(),
1464            message_number: 1,
1465            params: BankParams::new(),
1466            tan_overrides: TanOverrides::default(),
1467            notices: Vec::new(),
1468            notice_dialog: NoticeDialog::Job,
1469            now: None,
1470            _state: PhantomData,
1471        })
1472    }
1473
1474    /// Pin the local time of this dialog's signatures and orders.
1475    pub fn with_now(mut self, now: Option<jiff::civil::DateTime>) -> Self {
1476        self.now = now;
1477        self
1478    }
1479
1480    pub fn with_system_id(mut self, system_id: &SystemId) -> Self {
1481        self.system_id = system_id.clone();
1482        self
1483    }
1484
1485    pub fn with_params(mut self, params: &BankParams) -> Self {
1486        self.params = params.clone();
1487        self
1488    }
1489
1490    pub fn with_security_function(mut self, function: SecurityFunction) -> Self {
1491        self.params.selected_security_function = function;
1492        self
1493    }
1494
1495    /// Use a custom quirk chain instead of the default one
1496    /// (e.g. `QuirkChain::default().with(MyBankFix)`, or `QuirkChain::none()`).
1497    /// Continue a dialog the bank opened earlier (a thawed paused dialog):
1498    /// its ID, and the number its next message carries.
1499    pub(crate) fn resume(mut self, dialog_id: DialogId, message_number: u16) -> Dialog<Open> {
1500        self.dialog_id = dialog_id;
1501        self.message_number = message_number;
1502        self.transition()
1503    }
1504
1505    pub(crate) fn with_quirks(mut self, quirks: crate::quirks::QuirkChain) -> Self {
1506        self.quirks = quirks;
1507        self
1508    }
1509
1510    /// Send through `transport` instead of the default (`HttpTransport` with feature `http`)
1511    /// (custom timeout, recording, in-process banks).
1512    pub fn with_transport(mut self, transport: SharedTransport) -> Self {
1513        self.transport = transport;
1514        self
1515    }
1516
1517    /// The bank profile's per-order HKTAN overrides (beat HIPINS).
1518    pub fn with_tan_overrides(mut self, overrides: TanOverrides) -> Self {
1519        self.tan_overrides = overrides;
1520        self
1521    }
1522
1523    /// Synchronization dialog (spec: Initialisierung mit Synchronisierung).
1524    ///
1525    /// Sends HKIDN + HKVVB + HKSYN (mode=0 for new system_id).
1526    /// The bank responds with BPD, UPD, HITANS, HIPINS, and HISYN(system_id).
1527    /// This dialog is ONLY for synchronization — no business segments allowed.
1528    pub async fn sync(mut self) -> Result<(Dialog<Synced>, Response)> {
1529        info!("[FinTS] Sync dialog: BLZ={}", self.blz);
1530        self.notice_dialog = NoticeDialog::Sync;
1531
1532        let segments = [
1533            self.identify_segment(),
1534            self.process_prep_segment(),
1535            Segment::Sync,
1536        ];
1537
1538        let response = self.send_and_adopt(&segments).await?;
1539        self.params.select_security_function();
1540
1541        // Check for fatal errors (sync dialog should not require TAN)
1542        if !response.needs_tan() {
1543            response.check_errors()?;
1544        }
1545
1546        // Log all BPD parameter segments for diagnostics
1547        let bpd_summary: Vec<String> = self
1548            .params
1549            .bpd_segments
1550            .iter()
1551            .map(|s| format!("{}:v{}", s.segment_type(), s.segment_version()))
1552            .collect();
1553        info!(
1554            "[FinTS] Sync complete: BPD v{}, {} TAN methods",
1555            self.params.bpd_version,
1556            self.params.tan_methods.len()
1557        );
1558        info!(
1559            "[FinTS] BPD segments ({}): {}",
1560            bpd_summary.len(),
1561            bpd_summary.join(", ")
1562        );
1563        if let Some(bpd) = self.params.bpd() {
1564            for u in bpd.unparsed() {
1565                warn!("[FinTS] BPD segment not fully read: {u:?}");
1566            }
1567        }
1568
1569        Ok((self.transition(), response))
1570    }
1571
1572    /// Normal dialog initialization (spec: Dialoginitialisierung).
1573    ///
1574    /// Sends HKIDN + HKVVB + HKTAN(process=4, ref=HKIDN).
1575    /// Response-driven: returns `InitResult::Opened` or `InitResult::TanRequired`
1576    /// based on the bank's response codes.
1577    pub async fn init(mut self) -> Result<InitResult> {
1578        let medium = self.params.selected_tan_medium.clone();
1579        info!(
1580            "[FinTS] Init dialog: BLZ={} security_fn={}",
1581            self.blz, self.params.selected_security_function
1582        );
1583
1584        let mut segments = vec![self.identify_segment(), self.process_prep_segment()];
1585        if self.params.init_hktan_version()?.is_some() {
1586            segments.push(Segment::TanProcess4 {
1587                reference_seg: SegmentRef::new("HKIDN"),
1588                tan_medium: medium,
1589            });
1590        } else {
1591            info!("[FinTS] Init dialog: no HKTAN (selected method below HKTAN 6, or PIN only)");
1592        }
1593
1594        let response = self.send_and_adopt(&segments).await?;
1595
1596        let allowed = response.allowed_security_functions();
1597        if !allowed.is_empty() {
1598            self.params.allowed_security_functions = allowed;
1599            self.params.select_security_function();
1600        }
1601
1602        for c in response.all_codes() {
1603            info!("[FinTS] Init: {} - {}", c.code, c.text);
1604        }
1605
1606        // Response-driven transition per spec:
1607        if response.needs_tan()
1608            && let Some(challenge) = response.get_tan_challenge()?
1609        {
1610            // 0030/3955: TAN required on init → TanPending
1611            // Decoupled only on the bank's word (3955, PIN/TAN TAN-Prozess
1612            // 4): a decoupled method may still ask for a typed TAN (0030).
1613            let challenge = TanChallenge {
1614                challenge_markup: self.params.challenge_structured(),
1615                ..challenge
1616            };
1617            info!(
1618                "[FinTS] Init requires TAN: decoupled={}",
1619                challenge.decoupled
1620            );
1621            return Ok(InitResult::TanRequired(self.transition(), challenge));
1622        }
1623
1624        // 0010/0020 or 3076: dialog opened, no TAN needed → Open
1625        response.check_errors()?;
1626        info!("[FinTS] Init opened without TAN");
1627        Ok(InitResult::Opened(self.transition()))
1628    }
1629
1630    /// Learn the bank's parameters without a synchronization dialog, for a
1631    /// client that has a system ID but no BPD (e.g. migrated from another
1632    /// store). HKSYN would assign a new system ID, so the bank would see a
1633    /// new device and might withhold an SCA exemption (3076).
1634    ///
1635    /// Sends HKIDN + HKVVB with the stored system ID, signed PIN-only (999)
1636    /// and without HKTAN (HKTAN with 999 is an invalid combination). Whether
1637    /// the bank opens a dialog or aborts it, it answers with its BPD, the UPD
1638    /// and the allowed security functions (3920); the dialog is ended right
1639    /// away. Wrong PIN, locked access and a rejected system ID are errors.
1640    /// Returns the parameters with the best security function selected.
1641    pub async fn probe_parameters(mut self) -> Result<(BankParams, SystemId)> {
1642        info!(
1643            "[FinTS] Parameter probe: BLZ={} with stored system ID",
1644            self.blz
1645        );
1646        self.params.selected_security_function = SecurityFunction::pin_only();
1647        let segments = [self.identify_segment(), self.process_prep_segment()];
1648        let response = self.send_and_adopt(&segments).await?;
1649        for c in response.all_codes() {
1650            info!("[FinTS] Probe: {} - {}", c.code, c.text);
1651        }
1652        let fatal = response.all_codes().find(|c| {
1653            matches!(
1654                c.kind(),
1655                Kind::PinWrong
1656                    | Kind::SignatureInvalid
1657                    | Kind::AccountLocked
1658                    | Kind::SystemIdInvalid
1659            )
1660        });
1661        if fatal.is_some() {
1662            response.check_errors()?;
1663        }
1664        self.send_end().await.ok();
1665        self.params.select_security_function();
1666        if self.params.bpd().is_none() {
1667            return Err(FinTSError::Dialog(
1668                "parameter probe: the bank sent no BPD".into(),
1669            ));
1670        }
1671        Ok((self.params, self.system_id))
1672    }
1673
1674    /// Initialize WITHOUT HKTAN — PIN-only. Used when bank doesn't require SCA.
1675    pub async fn init_no_tan(mut self) -> Result<(Dialog<Open>, Response)> {
1676        info!("[FinTS] Init (no HKTAN)");
1677        let segments = [self.identify_segment(), self.process_prep_segment()];
1678
1679        let response = self.send_and_adopt(&segments).await?;
1680        response.check_errors()?;
1681        Ok((self.transition(), response))
1682    }
1683}
1684
1685// ── Dialog<Synced> ──────────────────────────────────────────────────────────
1686
1687impl Dialog<Synced> {
1688    /// End the sync dialog. Returns bank params and system_id for use in normal dialogs.
1689    pub async fn end(mut self) -> Result<(BankParams, SystemId)> {
1690        self.send_end().await.ok();
1691        Ok((self.params, self.system_id))
1692    }
1693}
1694
1695// ═══════════════════════════════════════════════════════════════════════════════
1696// Account — the account an order is for
1697// ═══════════════════════════════════════════════════════════════════════════════
1698
1699/// The account an order is for, as KTI (international: IBAN and BIC) and,
1700/// where known, KTV (national: number, subaccount, bank code).
1701///
1702/// The constructors refuse an account the bank could not address: no IBAN
1703/// or no BIC for [`Account::new`], no number or no valid bank code for
1704/// [`Account::national`]. Orders on `Dialog<Open>` take `&Account`, so
1705/// they never see an empty identifier.
1706///
1707/// ```
1708/// use fints_client::protocol::Account;
1709///
1710/// let account = Account::new("DE14 1234 5678 0000 0047 11", "TESTDEFFXXX").unwrap();
1711/// assert_eq!(account.iban(), "DE14123456780000004711");
1712/// assert_eq!(account.account_number(), Some("4711"));
1713///
1714/// assert!(Account::new("DE14123456780000004711", " ").is_err());
1715/// ```
1716#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1717pub struct Account {
1718    iban: Iban,
1719    bic: Bic,
1720    /// KTV account number, for the segment versions that address accounts
1721    /// nationally.
1722    number: Option<String>,
1723    /// KTV "Unterkontomerkmal".
1724    subaccount: Option<String>,
1725    /// KTV bank code.
1726    blz: Option<Blz>,
1727    /// Send number, subaccount and bank code in KTI too (`IBAN:BIC:number::280:BLZ`).
1728    /// Set from the BPD (HISPAS) when the bank allows national account details.
1729    kti_national: bool,
1730}
1731
1732/// `None` for a missing or blank subaccount.
1733fn subaccount_value(subaccount: Option<&str>) -> Option<String> {
1734    subaccount.filter(|s| !s.is_empty()).map(String::from)
1735}
1736
1737impl Account {
1738    /// An account by IBAN and BIC; fails when either is blank.
1739    ///
1740    /// Blanks are removed from the IBAN and letters upper-cased. A German
1741    /// IBAN contains the bank code (positions 5 to 12) and the account
1742    /// number (13 to 22), which become the KTV that HKSAL 5 and 6, HKKAZ 5
1743    /// and 6 and HKWPD need.
1744    pub fn new(iban: &str, bic: &str) -> Result<Self> {
1745        let iban: String = iban
1746            .split_whitespace()
1747            .flat_map(str::chars)
1748            .map(|c| c.to_ascii_uppercase())
1749            .collect();
1750        let bic = bic.trim();
1751        if iban.is_empty() {
1752            return Err(FinTSError::Dialog("the account has no IBAN".into()));
1753        }
1754        if bic.is_empty() {
1755            return Err(FinTSError::Dialog(
1756                "the account has no BIC; set it in the account settings".into(),
1757            ));
1758        }
1759        let national = german_iban_parts(&iban);
1760        Ok(Self {
1761            number: national.as_ref().map(|(_, number)| number.clone()),
1762            blz: national.map(|(blz, _)| Blz::new(blz)),
1763            iban: Iban::new(iban),
1764            bic: Bic::new(bic),
1765            subaccount: None,
1766            kti_national: false,
1767        })
1768    }
1769
1770    /// An account by its KTV alone, the way the UPD lists most depots.
1771    /// HKWPD addresses such an account; orders whose segment version needs
1772    /// an IBAN fail for it. National account details exist only in Germany
1773    /// (country code 280), so the bank code must have 8 digits.
1774    pub fn national(number: &str, subaccount: Option<&str>, blz: &Blz, bic: &str) -> Result<Self> {
1775        let number = number.trim();
1776        let code = blz.as_str();
1777        if number.is_empty() || code.is_empty() {
1778            return Err(FinTSError::Dialog(
1779                "a national account needs an account number and a bank code".into(),
1780            ));
1781        }
1782        if code.len() != 8 || !code.chars().all(|c| c.is_ascii_digit()) {
1783            return Err(FinTSError::Dialog(format!(
1784                "bank code {code:?} is not 8 digits"
1785            )));
1786        }
1787        let account = Self {
1788            iban: Iban::new(""),
1789            bic: Bic::new(bic.trim()),
1790            number: None,
1791            subaccount: None,
1792            blz: None,
1793            kti_national: false,
1794        };
1795        Ok(account.with_national(number, subaccount, blz))
1796    }
1797
1798    /// The same account with this subaccount, for an account the UPD
1799    /// lists by IBAN and subaccount.
1800    pub(crate) fn with_subaccount(self, subaccount: Option<&str>) -> Self {
1801        Self {
1802            subaccount: subaccount_value(subaccount),
1803            ..self
1804        }
1805    }
1806
1807    /// The same account with this KTV, which replaces anything taken from
1808    /// the IBAN; used with the details the UPD gives.
1809    pub fn with_national(self, number: &str, subaccount: Option<&str>, blz: &Blz) -> Self {
1810        Self {
1811            number: Some(number.to_owned()),
1812            subaccount: subaccount_value(subaccount),
1813            blz: Some(blz.clone()),
1814            ..self
1815        }
1816    }
1817
1818    /// Whether KTI carries the national parts too (see [`Account::kti_national`] field).
1819    pub(crate) fn with_kti_national(self, kti_national: bool) -> Self {
1820        Self {
1821            kti_national,
1822            ..self
1823        }
1824    }
1825
1826    pub(crate) fn kti_national(&self) -> bool {
1827        self.kti_national
1828    }
1829
1830    /// The IBAN without blanks; empty for an account known nationally only.
1831    pub fn iban(&self) -> &str {
1832        self.iban.as_str()
1833    }
1834
1835    pub fn bic(&self) -> &str {
1836        self.bic.as_str()
1837    }
1838
1839    /// The KTV account number, if known.
1840    pub fn account_number(&self) -> Option<&str> {
1841        self.number.as_deref()
1842    }
1843
1844    /// The KTV subaccount, if any.
1845    pub fn subaccount(&self) -> Option<&str> {
1846        self.subaccount.as_deref()
1847    }
1848
1849    /// The KTV bank code, if known.
1850    pub fn blz(&self) -> Option<&str> {
1851        self.blz.as_ref().map(Blz::as_str)
1852    }
1853}
1854
1855/// Bank code and account number of a German IBAN (`DE`, two check digits,
1856/// eight digits bank code, ten digits account number). The account number
1857/// loses its leading zeros, keeping a single `0` for an all-zero number.
1858fn german_iban_parts(iban: &str) -> Option<(String, String)> {
1859    let digits = iban.strip_prefix("DE")?;
1860    if digits.len() != 20 || !digits.bytes().all(|b| b.is_ascii_digit()) {
1861        return None;
1862    }
1863    let (bank_code, account) = (&digits[2..10], &digits[10..]);
1864    let significant = account.trim_start_matches('0');
1865    let number = if significant.is_empty() {
1866        "0"
1867    } else {
1868        significant
1869    };
1870    Some((bank_code.to_owned(), number.to_owned()))
1871}
1872
1873// ── Dialog<Open> ─────────────────────────────────────────────────────────────
1874
1875impl Dialog<Open> {
1876    /// Send a business order, with the 9075 retry and learning.
1877    pub(crate) async fn send_order(&mut self, segment: Segment, code: &str) -> Result<Response> {
1878        let (mut response, decision) = self
1879            .send_order_decided(&[], segment.clone(), code, None)
1880            .await?;
1881        match on_sca_required(&decision, response.all_codes().map(ReturnCode::kind)) {
1882            Retry::No => {}
1883            Retry::SameDialog => {
1884                info!(
1885                    "[FinTS] {}: 9075 without HKTAN, sending it again with HKTAN",
1886                    code
1887                );
1888                let (retry, _) = self
1889                    .send_order_decided(&[], segment.clone(), code, Some(true))
1890                    .await?;
1891                if !retry.all_codes().any(|c| c.is_error()) {
1892                    info!("[FinTS] {}: 9075 without HKTAN, learned", code);
1893                    self.params
1894                        .tan_required_learned
1895                        .insert(SegmentType::new(code));
1896                }
1897                response = retry;
1898            }
1899            Retry::DialogGone => {
1900                info!("[FinTS] {}: 9075 with 9800 without HKTAN, learned", code);
1901                self.params
1902                    .tan_required_learned
1903                    .insert(SegmentType::new(code));
1904                return Ok(response);
1905            }
1906        }
1907        Ok(response)
1908    }
1909
1910    /// A payment order (HKCCS, HKIPZ) after the `extra` segments (HKVPP in
1911    /// message 1, HKVPA in the execution message), with HKTAN process 4 as
1912    /// `order_tan` decides (always, unless a profile override says
1913    /// otherwise). No 9075 retry: a payment is never sent twice.
1914    pub(crate) async fn send_payment(
1915        &mut self,
1916        extra: &[Segment],
1917        order: Segment,
1918        code: &str,
1919    ) -> Result<Response> {
1920        Ok(self.send_order_decided(extra, order, code, None).await?.0)
1921    }
1922
1923    /// HKVPP alone: a payee check poll (VoP C.10.7.1.1). No order, no
1924    /// HKTAN.
1925    pub(crate) async fn send_vop_poll(&mut self, poll: Segment) -> Result<Response> {
1926        self.send_segments(&[poll]).await
1927    }
1928
1929    /// Send an order after the `extra` segments, with HKTAN as `order_tan`
1930    /// decides, or as `force` says (the 9075 retry). Returns the decision
1931    /// that was used.
1932    async fn send_order_decided(
1933        &mut self,
1934        extra: &[Segment],
1935        segment: Segment,
1936        code: &str,
1937        force: Option<bool>,
1938    ) -> Result<(Response, TanDecision)> {
1939        let mut segments = extra.to_vec();
1940        segments.push(segment);
1941        let mut decision = order_tan(
1942            &SegmentType::new(code),
1943            self.params.selected_security_function != SecurityFunction::pin_only(),
1944            self.params.bpd().and_then(|b| b.tan_required(code)),
1945            &self.tan_overrides,
1946            &self.params.tan_required_learned,
1947        );
1948        if let Some(hktan) = force {
1949            decision.hktan = hktan;
1950        }
1951        if decision.hktan {
1952            info!("[FinTS] {}: + HKTAN:4 ({:?})", code, decision.reason);
1953            segments.push(Segment::TanProcess4 {
1954                reference_seg: SegmentRef::new(code),
1955                tan_medium: self.params.selected_tan_medium.clone(),
1956            });
1957        } else {
1958            info!("[FinTS] {}: no HKTAN ({:?})", code, decision.reason);
1959        }
1960        let response = self.send_segments(&segments).await?;
1961        for c in response.all_codes() {
1962            if matches!(c.class(), Class::Error | Class::Warning) {
1963                info!("[FinTS] {}: {} - {}", code, c.code, c.text);
1964            }
1965        }
1966        Ok((response, decision))
1967    }
1968}
1969
1970// ═══════════════════════════════════════════════════════════════════════════════
1971// Response parsing
1972// ═══════════════════════════════════════════════════════════════════════════════
1973
1974/// The segments of a message with HNVSD replaced by the segments it holds.
1975fn unwrap_hnvsd(outer_segments: Vec<RawSegment>) -> Result<Vec<RawSegment>> {
1976    let mut all_segments = Vec::new();
1977    for seg in outer_segments {
1978        if seg.segment_type() == "HNVSD" {
1979            match crate::segments::read::hnvsd_data(&seg)
1980                .map_err(|e| e.to_string())
1981                .and_then(|data| crate::codec::wire::tokenize(&data).map_err(|e| e.to_string()))
1982            {
1983                Ok(inner) => all_segments.extend(inner),
1984                // The encrypted envelope holds the whole message: if it does
1985                // not read, nothing in it is known.
1986                Err(e) => return Err(FinTSError::Parse(format!("unreadable HNVSD: {e}"))),
1987            }
1988        } else {
1989            all_segments.push(seg);
1990        }
1991    }
1992    Ok(all_segments)
1993}
1994
1995/// Parses the bank's answer to `request` (the sent message) and names the
1996/// order each HIRMS code refers to.
1997fn parse_answer(data: &[u8], expected_msg_num: u16, request: &[u8]) -> Result<Response> {
1998    let mut response = parse_response(data, expected_msg_num)?;
1999    // Our own message: it always tokenizes; if not, orders stay unnamed.
2000    if let Ok(sent) = crate::codec::wire::tokenize(request)
2001        .map_err(|e| FinTSError::Parse(e.to_string()))
2002        .and_then(unwrap_hnvsd)
2003    {
2004        response.name_orders(&sent);
2005    }
2006    Ok(response)
2007}
2008
2009fn parse_response(data: &[u8], expected_msg_num: u16) -> Result<Response> {
2010    use crate::segments::read;
2011
2012    let outer_segments =
2013        crate::codec::wire::tokenize(data).map_err(|e| FinTSError::Parse(e.to_string()))?;
2014
2015    if let Some((_, resp_num)) = outer_segments
2016        .iter()
2017        .find(|s| s.segment_type() == "HNHBK")
2018        .and_then(read::message_header)
2019        && resp_num != u64::from(expected_msg_num)
2020    {
2021        warn!(
2022            "Message number mismatch: expected {}, got {}",
2023            expected_msg_num, resp_num
2024        );
2025    }
2026
2027    // The size in HNHBK is mandatory; a bank that gets it wrong is still
2028    // read (the answer may be complete), but the mismatch is logged: it is
2029    // the first sign of a cut or re-encoded answer.
2030    if let Some(stated) = outer_segments
2031        .iter()
2032        .find(|s| s.segment_type() == "HNHBK")
2033        .and_then(read::message_size)
2034        && stated != data.len() as u64
2035    {
2036        warn!(
2037            "HNHBK states {} bytes, the answer has {} bytes",
2038            stated,
2039            data.len()
2040        );
2041    }
2042
2043    let all_segments = unwrap_hnvsd(outer_segments)?;
2044
2045    // Every answer carries HIRMG (Formals B.7.1, message layout: "Rückmeldungen zur
2046    // Gesamtnachricht" is M). Without it the answer is cut off or not
2047    // a FinTS answer, and must not pass as a success.
2048    if !all_segments.iter().any(|s| s.segment_type() == "HIRMG") {
2049        return Err(FinTSError::InvalidResponse(
2050            "answer without HIRMG (cut off or not a FinTS answer)".into(),
2051        ));
2052    }
2053
2054    let mut global_codes = Vec::new();
2055    let mut segment_codes = Vec::new();
2056    for seg in &all_segments {
2057        let target = match seg.segment_type() {
2058            "HIRMG" => &mut global_codes,
2059            "HIRMS" => &mut segment_codes,
2060            _ => continue,
2061        };
2062        // An unreadable HIRMG/HIRMS makes `check_errors` fail.
2063        match read::response_codes(seg) {
2064            Ok(codes) => target.extend(codes),
2065            Err(e) => read::report(&e),
2066        }
2067    }
2068
2069    Ok(Response {
2070        segments: all_segments,
2071        global_codes,
2072        segment_codes,
2073    })
2074}
2075
2076#[cfg(test)]
2077mod tests {
2078    use super::*;
2079
2080    #[test]
2081    fn response_surfaces_codec_errors_of_raw_segments() {
2082        let response = Response {
2083            segments: crate::codec::wire::tokenize(
2084                b"HIRMG:2:2+0010::ok'\
2085                  HITANS:3:6:4+1+1+1+J:N:0:921:2:T:HHD:1.4:Name:6:1:TAN:6:N:1:N:0:0:N:N:00:0:N:0'\
2086                  HITANS:4:6:4+1+1+1+J:N:0:921:2:T:HHD:1.4:Name:6:1:TAN:x'",
2087            )
2088            .unwrap(),
2089            global_codes: vec![],
2090            segment_codes: vec![],
2091        };
2092        let decoded = response.decode_segments();
2093        assert_eq!(decoded.len(), 3);
2094        assert!(decoded[1].typed().is_some());
2095        let errors = response.segment_errors();
2096        assert_eq!(errors.len(), 1, "HIRMG has no definition yet: not an error");
2097        assert_eq!(
2098            errors[0].field,
2099            "parameters.methods[0].max_return_value_length"
2100        );
2101    }
2102
2103    #[test]
2104    fn camt_format_choice_by_version_number() {
2105        let pick = |formats: &str| {
2106            params_with_bpd(&format!("HICAZS:1:1:4+1+1+1+450:N:N:{formats}'")).camt052_format()
2107        };
2108        let u = "urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001";
2109        let plain = |n: &str| format!("urn:iso:std:iso:20022:tech:xsd:camt.052.001.{n}");
2110        // Same version: the descriptor without .xsd, as the bank wrote it.
2111        assert_eq!(pick(&format!("{u}.02.xsd:{u}.02")), plain("02"));
2112        assert_eq!(pick(&format!("{u}.02:{u}.02.xsd")), plain("02"));
2113        assert_eq!(pick(&format!("{u}.02:{u}.08")), plain("08"));
2114        assert_eq!(
2115            pick(&format!("{u}.08.xsd:{u}.02")),
2116            format!("{}.xsd", plain("08"))
2117        );
2118        // Numeric, not string order.
2119        assert_eq!(pick(&format!("{u}.10:{u}.9")), plain("10"));
2120    }
2121
2122    #[test]
2123    fn camt_format_from_hicazs() {
2124        assert_eq!(
2125            BankParams::new().camt052_format(),
2126            "urn:iso:std:iso:20022:tech:xsd:camt.052.001.02"
2127        );
2128        let p = params_with_bpd(
2129            "HICAZS:1:1:4+1+1+1+450:N:N:urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.08:urn?:iso?:std?:iso?:20022?:tech?:xsd?:camt.052.001.02'",
2130        );
2131        assert_eq!(
2132            p.camt052_format(),
2133            "urn:iso:std:iso:20022:tech:xsd:camt.052.001.08"
2134        );
2135        let seg = Segment::CamtTransactions {
2136            account: Account::new("DE00120300009900012345", "BYLADEM1001").unwrap(),
2137            start_date: Date::new(2026, 1, 1).unwrap(),
2138            end_date: Date::new(2026, 1, 31).unwrap(),
2139            touchdown: None,
2140        };
2141        assert!(seg.encode(&p, 3).is_ok());
2142        // A bank without HICAZS: VersionMismatch, not a guessed version.
2143        let no_camt = params_with_bpd("HIKAZS:1:7:4+1+1+1'");
2144        assert!(matches!(
2145            seg.encode(&no_camt, 3),
2146            Err(FinTSError::VersionMismatch(_))
2147        ));
2148    }
2149
2150    fn params_with_bpd(raw: &str) -> BankParams {
2151        // The model needs a HIBPA; the tests only care about what follows it.
2152        let mut p = BankParams::new();
2153        let wire = format!("HIBPA:1:3:4+1+280:1+Bank+1+1+300'{raw}");
2154        p.set_bpd(crate::codec::wire::tokenize(wire.as_bytes()).unwrap());
2155        p
2156    }
2157
2158    /// The orders a job exists for: all.
2159    fn built_orders() -> impl Iterator<Item = Order> {
2160        Order::ALL.iter().copied()
2161    }
2162
2163    /// The parameter segment of an order offering `versions`.
2164    fn param_segments(order: Order, versions: &[u16]) -> String {
2165        let code = order.code();
2166        let param = format!("{}I{}S", &code[..1], &code[2..]);
2167        versions
2168            .iter()
2169            .enumerate()
2170            .map(|(i, v)| format!("{param}:{}:{v}:4+1+1+0'", i + 2))
2171            .collect()
2172    }
2173
2174    #[test]
2175    fn order_version_picks_highest_common_version() {
2176        for order in built_orders() {
2177            let implemented = order.implemented();
2178            let max = *implemented.last().unwrap();
2179            let mut offered = implemented.to_vec();
2180            offered.push(max + 1);
2181            let p = params_with_bpd(&param_segments(order, &offered));
2182            assert_eq!(p.order_version(order).unwrap(), max, "{order:?}");
2183            let p = params_with_bpd(&param_segments(order, &implemented[..1]));
2184            assert_eq!(p.order_version(order).unwrap(), implemented[0], "{order:?}");
2185        }
2186    }
2187
2188    #[test]
2189    fn order_version_without_overlap_names_both_sides() {
2190        for order in built_orders() {
2191            let max = *order.implemented().last().unwrap();
2192            let p = params_with_bpd(&param_segments(order, &[max + 1, max + 2]));
2193            let Err(FinTSError::VersionMismatch(m)) = p.order_version(order) else {
2194                panic!("{order:?}: expected VersionMismatch");
2195            };
2196            assert_eq!(m.code.as_str(), order.code());
2197            assert_eq!(m.offered, [max + 1, max + 2]);
2198            assert_eq!(m.implemented, order.implemented());
2199        }
2200        let p = params_with_bpd("HICAZS:1:2:4+1+1+1'");
2201        assert_eq!(
2202            p.order_version(Order::Camt).unwrap_err().to_string(),
2203            "HKCAZ: no common version (bank offers 2, client implements 1)"
2204        );
2205    }
2206
2207    #[test]
2208    fn order_version_order_not_in_bpd() {
2209        let p = params_with_bpd("HIKAZS:1:7:4+1+1+1'");
2210        for &order in Order::ALL.iter().filter(|o| **o != Order::Transactions) {
2211            let Err(FinTSError::VersionMismatch(m)) = p.order_version(order) else {
2212                panic!("{order:?}: expected VersionMismatch");
2213            };
2214            assert!(m.offered.is_empty(), "{order:?}");
2215        }
2216        assert_eq!(
2217            p.order_version(Order::Camt).unwrap_err().to_string(),
2218            "HKCAZ: bank does not offer this order (client implements 1)"
2219        );
2220    }
2221
2222    #[test]
2223    fn order_version_without_bpd_is_an_error() {
2224        for &order in Order::ALL {
2225            let err = BankParams::new().order_version(order).unwrap_err();
2226            assert!(
2227                matches!(&err, FinTSError::NoBpd { code } if code.as_str() == order.code()),
2228                "{order:?}: {err}"
2229            );
2230        }
2231        assert_eq!(
2232            BankParams::new()
2233                .order_version(Order::Balance)
2234                .unwrap_err()
2235                .to_string(),
2236            "HKSAL: no bank parameter data (BPD) known; synchronise first"
2237        );
2238    }
2239
2240    fn tan_method(sf: &str, v: u16) -> TanMethod {
2241        TanMethod {
2242            security_function: SecurityFunction::new(sf),
2243            tan_process: TanProcess::TwoStep,
2244            name: sf.into(),
2245            needs_tan_medium: false,
2246            decoupled_max_polls: -1,
2247            wait_before_first_poll: 0,
2248            wait_before_next_poll: 0,
2249            is_decoupled: false,
2250            hktan_version: v,
2251            zka_name: None,
2252            decoupled_auto_polling: None,
2253            challenge_structured: false,
2254        }
2255    }
2256
2257    fn params_with_methods(methods: &[(&str, u16)], selected: &str) -> BankParams {
2258        let mut p = BankParams::new();
2259        p.tan_methods = methods.iter().map(|(sf, v)| tan_method(sf, *v)).collect();
2260        p.selected_security_function = SecurityFunction::new(selected);
2261        p
2262    }
2263
2264    fn hktan_wire(p: &BankParams) -> String {
2265        let seg = Segment::TanProcess4 {
2266            reference_seg: SegmentRef::new("HKIDN"),
2267            tan_medium: None,
2268        };
2269        let raw = seg.encode(p, 3).unwrap();
2270        String::from_utf8(crate::codec::wire::serialize_segment(&raw).unwrap()).unwrap()
2271    }
2272
2273    #[test]
2274    fn hktan_version_is_the_highest_buildable_of_the_selected_method() {
2275        let p = params_with_methods(&[("902", 6), ("902", 7), ("902", 8), ("912", 6)], "902");
2276        assert_eq!(p.hktan_version().unwrap(), 7);
2277        assert_eq!(p.init_hktan_version().unwrap(), Some(7));
2278        let p = params_with_methods(&[("902", 6), ("902", 7), ("912", 6)], "912");
2279        assert_eq!(p.hktan_version().unwrap(), 6, "not another method's 7");
2280    }
2281
2282    #[test]
2283    fn hktan_version_without_a_buildable_version_names_both_sides() {
2284        let p = params_with_methods(&[("902", 8), ("912", 7)], "902");
2285        let err = p.hktan_version().unwrap_err();
2286        assert!(
2287            matches!(
2288                &err,
2289                FinTSError::VersionMismatch(v)
2290                    if v.code.as_str() == "HKTAN" && v.offered == [8] && v.implemented == [5, 6, 7]
2291            ),
2292            "{err}"
2293        );
2294        // The backstop reaches the wire builder and the init decision.
2295        assert!(p.init_hktan_version().is_err());
2296        let seg = Segment::TanPollDecoupled {
2297            task_reference: TaskReference::new("T"),
2298            tan_medium: None,
2299        };
2300        assert!(matches!(
2301            seg.encode(&p, 3),
2302            Err(FinTSError::VersionMismatch(_))
2303        ));
2304        // A method no HITANS lists has no version either (empty `offered`).
2305        let p = params_with_methods(&[("912", 7)], "902");
2306        assert!(matches!(
2307            p.hktan_version(),
2308            Err(FinTSError::VersionMismatch(v)) if v.offered.is_empty()
2309        ));
2310    }
2311
2312    #[test]
2313    fn hktan_version_without_hitans_is_7() {
2314        let p = BankParams::new();
2315        assert_eq!(p.hktan_version().unwrap(), 7);
2316        assert_eq!(p.init_hktan_version().unwrap(), Some(7));
2317        assert_eq!(hktan_wire(&p), "HKTAN:3:7+4+HKIDN'");
2318    }
2319
2320    #[test]
2321    fn init_without_hktan_when_the_method_is_below_6() {
2322        let p = params_with_methods(&[("902", 5), ("912", 7)], "902");
2323        assert_eq!(
2324            p.hktan_version().unwrap(),
2325            5,
2326            "orders use the method's version"
2327        );
2328        assert_eq!(p.init_hktan_version().unwrap(), None);
2329        assert!(hktan_wire(&p).starts_with("HKTAN:3:5+4+"));
2330        // PIN only with HITANS known: nothing to signal at init.
2331        let p = params_with_methods(&[("912", 7)], "999");
2332        assert_eq!(p.init_hktan_version().unwrap(), None);
2333    }
2334
2335    #[test]
2336    fn unbuildable_tan_methods_are_not_offered_or_selected() {
2337        let v8 = "HITANS:53:8:4+1+1+1+N:N:0:941:2:TESTAPP:Decoupled::Neue App:::Freigabe:2048:N:2:N:0:0:N:N:00:2:N:1:60:4:2:J:J'";
2338        let v7 = "HITANS:42:7:4+1+1+1+N:N:0:\
2339            931:2:TESTHHD:HHD:1.4:Kartenleser Test:6:1:TAN:6:N:1:N:0:0:N:N:00:0:N:0::::::\
2340            932:2:TESTAPP:Decoupled::App-Freigabe Test:::Freigabe:2048:N:2:N:0:0:N:N:00:2:N:1:60:4:2:J:J:\
2341            933:2:TESTSMS:mobileTAN::SMS Test:6:1:TAN:6:N:1:N:0:0:N:N:00:2:N:1:::::'";
2342        let wire = format!("HIBPA:1:3:4+1+280:1+Bank+1+1+300'{v7}{v8}");
2343        let mut p = BankParams::new();
2344        p.set_bpd(crate::codec::wire::tokenize(wire.as_bytes()).unwrap());
2345        let offered: Vec<&str> = p
2346            .tan_methods
2347            .iter()
2348            .map(|m| m.security_function.as_str())
2349            .collect();
2350        assert_eq!(offered, ["931", "932", "933"], "941 is HITANS 8");
2351
2352        // The bank allows 941, but we cannot build its HKTAN: it is skipped
2353        // like an unknown method, also as a stored preference.
2354        p.allowed_security_functions =
2355            vec![SecurityFunction::new("941"), SecurityFunction::new("932")];
2356        p.preferred_security_function = Some(SecurityFunction::new("941"));
2357        p.select_security_function();
2358        assert_eq!(p.selected_security_function, SecurityFunction::new("932"));
2359
2360        // The backstop still names the HITANS versions of an unbuildable method.
2361        p.selected_security_function = SecurityFunction::new("941");
2362        assert!(matches!(
2363            p.hktan_version(),
2364            Err(FinTSError::VersionMismatch(v)) if v.offered == [8]
2365        ));
2366    }
2367
2368    /// Decoupled status with the HKTAN version the BPD offers: process S
2369    /// with HKTAN 7, process 2 with HKTAN 5 and 6 (PIN/TAN B.5.2; owner
2370    /// decision 2026-11-15; common client behaviour, S only from version 7).
2371    #[test]
2372    fn decoupled_poll_follows_the_hktan_version() {
2373        let poll = Segment::TanPollDecoupled {
2374            task_reference: TaskReference::new("TASK-1"),
2375            tan_medium: None,
2376        };
2377        let mut p = BankParams::new();
2378        let wire = |p: &BankParams| {
2379            let raw = poll.encode(p, 3).unwrap();
2380            String::from_utf8(crate::codec::wire::serialize_segment(&raw).unwrap()).unwrap()
2381        };
2382        for (version, expected) in [
2383            (7, "HKTAN:3:7+S++++TASK-1+N'"),
2384            (6, "HKTAN:3:6+2++++TASK-1+N'"),
2385            (5, "HKTAN:3:5+2++++TASK-1++N'"),
2386        ] {
2387            p.tan_methods = vec![TanMethod {
2388                security_function: SecurityFunction::new("902"),
2389                tan_process: TanProcess::TwoStep,
2390                name: "App".into(),
2391                needs_tan_medium: false,
2392                decoupled_max_polls: -1,
2393                wait_before_first_poll: 0,
2394                wait_before_next_poll: 0,
2395                is_decoupled: true,
2396                hktan_version: version,
2397                zka_name: None,
2398                decoupled_auto_polling: None,
2399                challenge_structured: false,
2400            }];
2401            p.selected_security_function = SecurityFunction::new("902");
2402            assert_eq!(wire(&p), expected);
2403        }
2404    }
2405
2406    /// Feeds `data` to everything that reads bank answers. Used by the
2407    /// property tests below, which only check that nothing panics.
2408    fn read_everything(data: &[u8]) {
2409        use crate::segments::{read, response};
2410        let Ok(answer) = parse_response(data, 1) else {
2411            return;
2412        };
2413        let _ = (
2414            answer.check_errors(),
2415            answer.get_tan_challenge(),
2416            answer.touchdown(),
2417        );
2418
2419        let mut params = BankParams::new();
2420        params.ingest_response(&answer, &mut SystemId::unassigned());
2421        params.select_security_function();
2422        let _ = params.camt052_format();
2423
2424        for segment in &answer.segments {
2425            let _ = (read::balance(segment), read::tan_challenge(segment));
2426            let _ = (read::upd_account(segment), read::tan_methods(segment));
2427            let _ = (
2428                response::parse_hiupd(segment),
2429                response::parse_hitans(segment),
2430            );
2431        }
2432
2433        let all = &answer.segments;
2434        let _ = (read::parse_hiwpd(all), read::parse_hiwdu(all));
2435        let _ = read::extract_mt940_data(all);
2436        let camt = read::extract_camt_data(all);
2437        for report in camt.booked.iter().chain(&camt.pending) {
2438            let _ = crate::camt::parse_camt052(report, crate::banks::BookingIdSource::None);
2439        }
2440    }
2441
2442    /// Pieces that look like parts of real answers, so that random
2443    /// combinations reach deep into the readers.
2444    const ANSWER_PIECES: &[&str] = &[
2445        "HIRMG:2:2+",
2446        "HIRMS:3:2:4+",
2447        "HISAL:4:7:5+",
2448        "HITAN:5:7:6+",
2449        "HITANS:6:7:4+1+1+0+",
2450        "HIUPD:7:6:4+",
2451        "HICAZ:8:1:5+",
2452        "HICAZS:9:1:4+1+1+0+400:J:N:",
2453        "HIWPD:10:6:5+",
2454        "HIWDU:11:5:5+",
2455        "HNVSD:999:1+",
2456        "@4@",
2457        "@123456789012345678901@",
2458        "3040::mehr:TP",
2459        "DE14123456780000004711:TESTDEFFXXX:4711::280:12345678",
2460        "C:1,5:EUR:20260115",
2461        ":16R:GENL\r\n:35B:ISIN DE0000000001\r\n:16S:FIN\r\n",
2462    ];
2463
2464    use proptest::strategy::Strategy as _;
2465
2466    proptest::proptest! {
2467        #[test]
2468        fn readers_survive_arbitrary_bytes(
2469            bytes in proptest::collection::vec(proptest::num::u8::ANY, 0..600)
2470        ) {
2471            read_everything(&bytes);
2472        }
2473
2474        #[test]
2475        fn readers_survive_shuffled_answer_pieces(
2476            picks in proptest::collection::vec(
2477                proptest::prop_oneof![
2478                    proptest::sample::select(ANSWER_PIECES).prop_map(str::to_owned),
2479                    "[0-9A-Z:+?'@ ,]{0,10}",
2480                ],
2481                0..30,
2482            )
2483        ) {
2484            read_everything(picks.concat().as_bytes());
2485        }
2486    }
2487
2488    /// Return code 3072 hands out a new user ID (Formals, return codes).
2489    /// The old UPD belongs to the old ID and is asked for again.
2490    #[test]
2491    fn new_user_id_from_3072_is_kept_and_the_upd_dropped() {
2492        let mut params = BankParams::new();
2493        let upd = b"HIUPA:4:4:3+kunde7+5+0'HIUPD:5:6:3+4711::280:12345678+DE14123456780000004711+kunde7++EUR+Erika Muster'";
2494        params.set_upd(crate::codec::wire::tokenize(upd).unwrap());
2495        assert_eq!(params.upd_version, 5);
2496
2497        let answer = parse_response(
2498            b"HIRMG:2:2+0010::Nachricht entgegengenommen.'\
2499              HIRMS:3:2:3+3072::Neue Zugangsdaten:kunde8:kundenid8'",
2500            1,
2501        )
2502        .unwrap();
2503        // A warning, not an error.
2504        answer.check_errors().unwrap();
2505        params.ingest_response(&answer, &mut SystemId::new("SYS-0042"));
2506        assert_eq!(
2507            params.changed_user_id.as_ref().map(UserId::as_str),
2508            Some("kunde8")
2509        );
2510        assert_eq!(params.upd_version, 0);
2511        assert!(params.upd().is_none());
2512    }
2513
2514    /// An answer that carries the BPD again (here: the same answer twice)
2515    /// replaces the stored BPD; nothing is listed twice.
2516    #[test]
2517    fn repeated_bpd_replaces_the_stored_one() {
2518        let answer = parse_response(
2519            b"HIRMG:2:2+0010::ok'\
2520              HIBPA:3:3:4+21+280:12345678+Testbank+1+1+300'\
2521              HITANS:4:7:4+1+1+1+J:N:0:902:2:TEST902:Decoupled:1.0:Test-App:::Freigabe:0:N:1:N:0:0:N:N:00:0:N:0:0:0:0:N:J'",
2522            1,
2523        )
2524        .unwrap();
2525        let mut params = params_with_bpd("");
2526        let mut system_id = SystemId::unassigned();
2527        for _ in 0..2 {
2528            params.ingest_response(&answer, &mut system_id);
2529        }
2530        assert_eq!(params.bpd_version, 21);
2531        let codes: Vec<_> = params
2532            .tan_methods
2533            .iter()
2534            .map(|m| m.security_function.as_str())
2535            .collect();
2536        assert_eq!(codes, ["902"]);
2537    }
2538
2539    /// A bank wraps the reason for a rejected order in a generic global
2540    /// 9050; the segment code must win.
2541    #[test]
2542    fn segment_error_wins_over_generic_global_code() {
2543        let resp = parse_response(
2544            b"HIRMG:2:2+9050::Die Nachricht enthaelt Fehler'              HIRMS:3:2:3+0020::ok'HIRMS:4:2:4+9010::Verarbeitung nicht moeglich+9210::Keine gueltige Kontoverbindung'",
2545            1,
2546        )
2547        .unwrap();
2548        let err = resp.check_errors().unwrap_err();
2549        assert_eq!(
2550            err.to_string(),
2551            "Bank error 9210: Keine gueltige Kontoverbindung"
2552        );
2553        // Only generic codes: the segment one first.
2554        let resp = parse_response(
2555            b"HIRMG:2:2+9050::Teilweise fehlerhaft'HIRMS:3:2:3+9010::Abgelehnt'",
2556            1,
2557        )
2558        .unwrap();
2559        assert!(
2560            resp.check_errors()
2561                .unwrap_err()
2562                .to_string()
2563                .contains("9010")
2564        );
2565        // A wrong PIN anywhere still wins.
2566        let resp = parse_response(
2567            b"HIRMG:2:2+9050::Fehler'HIRMS:3:2:3+9210::Konto'HIRMS:4:2:1+9942::PIN falsch'",
2568            1,
2569        )
2570        .unwrap();
2571        assert_eq!(
2572            resp.check_errors().unwrap_err().kind(),
2573            Category::Credentials(crate::return_code::Credentials::PinWrong)
2574        );
2575    }
2576
2577    /// Notices: warnings and unknown codes; not success, errors or the
2578    /// codes the protocol consumes (docs/return-codes-design.md section 2).
2579    #[test]
2580    fn notices_skip_success_errors_and_consumed_codes() {
2581        let answer = b"HIRMG:2:2+0010::ok+3050::veraltet+3060::Hinweise'\
2582            HIRMS:3:2:3+0030::TAN+3040::mehr:abc+3076::SCA+3920::Verfahren:912\
2583            +3955::decoupled+3956::offen+3091::VOP+3945::VOP+3072::neu:A:B\
2584            +3010::leer+3957::Push+3958::App+3999::bank+1234::note+9210::Konto'";
2585        let resp = parse_response(answer, 1).unwrap();
2586        let codes: Vec<String> = resp
2587            .notices(NoticeDialog::Job)
2588            .iter()
2589            .map(|n| n.code().unwrap().code.as_str().to_string())
2590            .collect();
2591        assert_eq!(
2592            codes,
2593            [
2594                "3050", "3060", "3072", "3010", "3957", "3958", "3999", "1234"
2595            ]
2596        );
2597        let none = parse_response(b"HIRMG:2:2+0010::ok'HIRMS:3:2:3+0020::ok'", 1).unwrap();
2598        assert!(none.notices(NoticeDialog::Job).is_empty());
2599    }
2600
2601    /// A wrong typed TAN leaves the order for another TAN only when 9941
2602    /// is the one cause (docs/return-codes-design.md section 1): (answer,
2603    /// attempts left when it does).
2604    #[test]
2605    fn tan_rejection_only_where_the_order_stays() {
2606        let cases: &[(&[u8], Option<Option<u32>>)] = &[
2607            (b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9941::TAN ungueltig'", Some(None)),
2608            (
2609                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9941::TAN ungueltig+9360::Sperre nach weiteren 2:2'",
2610                Some(Some(2)),
2611            ),
2612            // 9360 with no attempts left, or without P1 (locked).
2613            (
2614                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9941::TAN ungueltig+9360::Sperre:0'",
2615                None,
2616            ),
2617            (b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9941::T+9360::gesperrt'", None),
2618            // The dialog ended, the order was deleted, the access locked.
2619            (
2620                b"HIRMG:2:2+9050::F+9800::Dialog abgebrochen'HIRMS:3:2:3+9941::T'",
2621                None,
2622            ),
2623            (
2624                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9941::T+9210::Auftrag geloescht'",
2625                None,
2626            ),
2627            (b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9931::gesperrt'", None),
2628            // Timed out or used: not a wrong TAN.
2629            (b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9951::Zeit'", None),
2630            (b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9943::verbraucht'", None),
2631            // Success.
2632            (b"HIRMG:2:2+0010::ok'HIRMS:3:2:3+0020::ok'", None),
2633        ];
2634        for (answer, want) in cases {
2635            let resp = parse_response(answer, 1).unwrap();
2636            let got = resp.tan_rejection();
2637            let wire = String::from_utf8_lossy(answer);
2638            assert_eq!(got.as_ref().map(|(_, n)| *n), *want, "{wire}");
2639            if let Some((code, _)) = got {
2640                assert_eq!(code.code.as_str(), "9941", "{wire}");
2641            }
2642        }
2643    }
2644
2645    /// The selection rule (docs/return-codes-design.md section 3) over
2646    /// multi-code answers: (answer, selected code).
2647    #[test]
2648    fn select_error_order() {
2649        let cases: &[(&[u8], Option<&str>)] = &[
2650            // Warnings and successes only.
2651            (b"HIRMG:2:2+3060::Hinweise'HIRMS:3:2:3+0020::ok'", None),
2652            // Rule 1: credentials, then system ID, wherever they are.
2653            (
2654                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9210::Konto'HIRMS:4:2:1+9942::PIN'",
2655                Some("9942"),
2656            ),
2657            (
2658                b"HIRMG:2:2+9391::Kundensystem-ID'HIRMS:3:2:3+9931::gesperrt'",
2659                Some("9931"),
2660            ),
2661            (
2662                b"HIRMG:2:2+9391::Kundensystem-ID'HIRMS:3:2:3+9210::Konto'",
2663                Some("9391"),
2664            ),
2665            // Live sets (2026-11-17), synthetic texts. A wrong BLZ for the
2666            // user: 9210 names the cause, 9340 is its consequence.
2667            (
2668                b"HIRMG:2:2+9050::Nachricht enthaelt Fehler+9800::Dialog abgebrochen\
2669                  +9210::Bankleitzahl passt nicht zum Benutzer+9340::Ungueltige Signatur'",
2670                Some("9210"),
2671            ),
2672            // A wrong PIN: 9942 next to 9800.
2673            (
2674                b"HIRMG:2:2+9800::Dialog abgebrochen+9942::PIN ungueltig'",
2675                Some("9942"),
2676            ),
2677            // 9340 loses to a named credentials cause and to any specific
2678            // error, segment or message scope; it wins over generic codes.
2679            (
2680                b"HIRMG:2:2+9340::Signatur'HIRMS:3:2:1+9942::PIN'",
2681                Some("9942"),
2682            ),
2683            (
2684                b"HIRMG:2:2+9340::Signatur'HIRMS:3:2:3+9380::nicht berechtigt'",
2685                Some("9380"),
2686            ),
2687            (
2688                b"HIRMG:2:2+9050::F+9800::Dialog abgebrochen'HIRMS:3:2:1+9340::Signatur'",
2689                Some("9340"),
2690            ),
2691            // Rule 2: the first specific segment error; 9800 is generic.
2692            (
2693                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9010::V+9210::Konto'",
2694                Some("9210"),
2695            ),
2696            (
2697                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9800::Dialog abgebrochen+9210::Konto'",
2698                Some("9210"),
2699            ),
2700            (
2701                b"HIRMG:2:2+9800::Dialog abgebrochen'HIRMS:3:2:3+9210::Konto'",
2702                Some("9210"),
2703            ),
2704            (
2705                b"HIRMG:2:2+9000::Status indifferent'HIRMS:3:2:3+9210::Konto'",
2706                Some("9210"),
2707            ),
2708            // Rule 3: else the first specific message error.
2709            (
2710                b"HIRMG:2:2+9800::Dialog abgebrochen+9075::SCA'HIRMS:3:2:3+9010::V'",
2711                Some("9075"),
2712            ),
2713            (
2714                b"HIRMG:2:2+9050::F+9000::Status indifferent:HKCAZ'",
2715                Some("9000"),
2716            ),
2717            // Rule 5: only generic codes; segment scope first.
2718            (
2719                b"HIRMG:2:2+9050::F'HIRMS:3:2:3+9010::Abgelehnt'",
2720                Some("9010"),
2721            ),
2722            (
2723                b"HIRMG:2:2+9800::Dialog abgebrochen'HIRMS:3:2:3+9050::F'",
2724                Some("9050"),
2725            ),
2726            (b"HIRMG:2:2+9050::F+9800::Dialog abgebrochen'", Some("9050")),
2727        ];
2728        for (answer, want) in cases {
2729            let resp = parse_response(answer, 1).unwrap();
2730            let got = resp.select_error();
2731            let wire = String::from_utf8_lossy(answer);
2732            assert_eq!(
2733                got.as_ref().map(|e| e.code().code.as_str()),
2734                *want,
2735                "{wire}"
2736            );
2737            if let Some(e) = got {
2738                // The error keeps every code of the response.
2739                assert_eq!(e.codes().len(), resp.all_codes().count(), "{wire}");
2740                assert!(resp.check_errors().is_err());
2741            }
2742        }
2743    }
2744
2745    /// 9000: the outcome is unknown; P1 names the order to ask with.
2746    #[test]
2747    fn outcome_unknown_names_the_order_to_check() {
2748        let resp = parse_response(b"HIRMG:2:2+9000::Status indifferent:HKCAZ'", 1).unwrap();
2749        let err = resp.check_errors().unwrap_err();
2750        assert_eq!(err.kind(), Category::OutcomeUnknown);
2751        assert!(!err.is_retryable());
2752        assert_eq!(
2753            err.bank_error().map(|e| e.code().kind()),
2754            Some(Kind::OutcomeUnknown {
2755                query: Some(SegmentType::new("HKCAZ"))
2756            })
2757        );
2758    }
2759
2760    /// A HIRMS code names the order it refers to, read from the sent
2761    /// message's segment numbers (also inside HNVSD); the error keeps the
2762    /// whole code line.
2763    #[test]
2764    fn segment_codes_name_their_order() {
2765        let request = b"HNHBK:1:3+000000000100+300+0+1'HNVSK:998:3+PIN:2'\
2766            HNVSD:999:1+@55@HNSHK:2:4+PIN:2'HKSAL:3:7+DE00:BIC+N'HKTAN:4:7+4+HKSAL''\
2767            HNHBS:5:1+1'";
2768        let answer = b"HIRMG:2:2+9050::Fehler'HIRMS:3:2:3+9210:2:Konto unbekannt:P1'\
2769            HIRMS:4:2:4+0020::ok'HIRMS:5:2:7+3920::Verfahren:912'";
2770        let resp = parse_answer(answer, 1, request).unwrap();
2771        let orders: Vec<_> = resp
2772            .segment_codes
2773            .iter()
2774            .map(|c| match &c.scope {
2775                Scope::Segment { number, order } => (*number, order.clone()),
2776                Scope::Message => panic!("HIRMS has segment scope"),
2777            })
2778            .collect();
2779        assert_eq!(
2780            orders,
2781            [
2782                (3, Some(SegmentType::new("HKSAL"))),
2783                (4, Some(SegmentType::new("HKTAN"))),
2784                (7, None),
2785            ]
2786        );
2787        assert_eq!(resp.global_codes[0].scope, Scope::Message);
2788        match resp.check_errors() {
2789            Err(FinTSError::Bank(e)) => {
2790                let code = e.code();
2791                assert_eq!(code.code.as_str(), "9210");
2792                assert_eq!(code.reference_element.as_deref(), Some("2"));
2793                assert_eq!(code.parameters, ["P1"]);
2794                assert!(matches!(code.scope, Scope::Segment { number: 3, .. }));
2795            }
2796            other => panic!("{other:?}"),
2797        }
2798    }
2799
2800    /// A notice carries its dialog and the segment code its HIRMS
2801    /// reference names (segment number 3 is the HKSAL, 4 the HKTAN); a
2802    /// HIRMG notice is message-level, a reference outside the request
2803    /// shows only the number.
2804    #[test]
2805    fn notices_name_dialog_and_order() {
2806        let request = b"HNHBK:1:3+000000000100+300+0+1'HNVSK:998:3+PIN:2'\
2807            HNVSD:999:1+@55@HNSHK:2:4+PIN:2'HKSAL:3:7+DE00:BIC+N'HKTAN:4:7+4+HKSAL''\
2808            HNHBS:5:1+1'";
2809        let answer = b"HIRMG:2:2+3060::Hinweise'HIRMS:3:2:3+3010::leer'\
2810            HIRMS:4:2:4+3072::neu:A:B'HIRMS:5:2:7+3999::bank'";
2811        let resp = parse_answer(answer, 1, request).unwrap();
2812        let notices = resp.notices(NoticeDialog::Sync);
2813        let shown: Vec<String> = notices.iter().map(|n| n.to_string()).collect();
2814        assert_eq!(
2815            shown,
2816            [
2817                "3060 [sync, HIRMG]: Hinweise",
2818                "3010 [sync, HKSAL]: leer",
2819                "3072 [sync, HKTAN]: neu",
2820                "3999 [sync, HIRMS #7]: bank",
2821            ]
2822        );
2823        assert!(notices.iter().all(|n| n.dialog() == NoticeDialog::Sync));
2824        assert_eq!(
2825            resp.notices(NoticeDialog::Job)[0].dialog(),
2826            NoticeDialog::Job
2827        );
2828    }
2829
2830    #[test]
2831    fn utf8_text_in_latin1_answer_is_a_client_notice() {
2832        // "für" as UTF-8 bytes in a Latin-1 answer; the real "ü" (0xFC) is fine.
2833        let bad = parse_response(b"HIRMG:2:2+3060::Hinweis f\xC3\xBCr Sie'", 1).unwrap();
2834        let notices = bad.notices(NoticeDialog::Job);
2835        assert_eq!(notices.len(), 2);
2836        assert_eq!(
2837            notices[1].client_warning(),
2838            Some(ClientWarning::Utf8TextInLatin1)
2839        );
2840        assert!(notices[1].code().is_none());
2841        assert!(notices[1].to_string().starts_with("client [job]:"));
2842        assert_eq!(bad.global_codes[0].text, "Hinweis f\u{c3}\u{bc}r Sie");
2843        let good = parse_response(b"HIRMG:2:2+3060::Hinweis f\xFCr Sie'", 1).unwrap();
2844        assert_eq!(good.notices(NoticeDialog::Job).len(), 1);
2845    }
2846
2847    /// Every 9xxx code is an error, also one no table lists; the message
2848    /// keeps the bank's code and text.
2849    #[test]
2850    fn unlisted_error_code_fails_with_the_banks_words() {
2851        let answer = parse_response(b"HIRMG:2:2+9876::Systemfehler, bitte spaeter erneut'", 1);
2852        let error = answer.unwrap().check_errors().unwrap_err();
2853        let shown = error.to_string();
2854        assert_eq!(shown, "Bank error 9876: Systemfehler, bitte spaeter erneut");
2855    }
2856
2857    /// HIRMG/HIRMS stay strict (Formals C.8.1: text `an ..80`): a code the
2858    /// codec cannot read is not taken for a success.
2859    #[test]
2860    fn unreadable_response_codes_are_an_error() {
2861        let wire = format!("HIRMG:2:2+0010::ok'HIRMS:3:2:3+0020::{}'", "x".repeat(81));
2862        let resp = parse_response(wire.as_bytes(), 1).unwrap();
2863        assert_eq!(resp.segment_codes.len(), 0);
2864        assert_eq!(resp.segment_errors().len(), 1);
2865        let err = resp.check_errors().unwrap_err();
2866        assert!(matches!(err, FinTSError::InvalidResponse(_)), "{err}");
2867    }
2868
2869    /// Bank text is ISO 8859-1 (Formals B.1): 0xE4 is 'ä'.
2870    #[test]
2871    fn response_text_is_latin1() {
2872        let resp = parse_response(b"HIRMG:2:2+0010::Auftr\xe4ge ok'", 1).unwrap();
2873        assert_eq!(resp.global_codes[0].text, "Aufträge ok");
2874    }
2875
2876    /// A depot listed in the UPD without IBAN reaches every order that
2877    /// addresses accounts nationally, and gets a clear error from the ones
2878    /// that need an IBAN.
2879    #[test]
2880    fn national_only_account_through_all_orders() {
2881        let depot = Account::national(
2882            "0123456789",
2883            Some("01"),
2884            &Blz::new("12030000"),
2885            "BYLADEM1001",
2886        )
2887        .unwrap();
2888        assert_eq!(depot.account_number(), Some("0123456789"));
2889        assert_eq!(depot.subaccount(), Some("01"));
2890
2891        let p = params_with_bpd(
2892            "HISALS:1:6:4+1+1+1'HIKAZS:2:6:4+1+1+1'HIWPDS:3:6:4+1+1+1'HIWDUS:4:5:4+1+1+0'HICAZS:7:1:4+1+1+1'",
2893        );
2894        let date = Date::new(2026, 1, 1).unwrap();
2895        let national = [
2896            Segment::Balance {
2897                account: depot.clone(),
2898            },
2899            Segment::Transactions {
2900                account: depot.clone(),
2901                start_date: date,
2902                end_date: date,
2903                touchdown: None,
2904            },
2905            Segment::Holdings {
2906                account: depot.clone(),
2907                currency: None,
2908                touchdown: None,
2909            },
2910            Segment::DepotTransactions {
2911                account: depot.clone(),
2912                start_date: None,
2913                end_date: None,
2914                touchdown: None,
2915            },
2916        ];
2917        for seg in &national {
2918            let degs = seg.encode(&p, 3).unwrap().degs;
2919            assert_eq!(degs[1].get_str(0), "0123456789", "{seg:?}");
2920            assert_eq!(degs[1].get_str(3), "12030000", "{seg:?}");
2921        }
2922        let camt = Segment::CamtTransactions {
2923            account: depot,
2924            start_date: date,
2925            end_date: date,
2926            touchdown: None,
2927        };
2928        let err = camt.encode(&p, 3).unwrap_err();
2929        assert!(
2930            matches!(
2931                err,
2932                FinTSError::AccountNotAddressable {
2933                    version: 1,
2934                    reason: crate::error::AddressingReason::NoIbanBic,
2935                    ..
2936                }
2937            ),
2938            "{err}"
2939        );
2940        assert_eq!(
2941            err.to_string(),
2942            "HKCAZ v1 cannot address this account: it needs an IBAN and BIC, which the account lacks"
2943        );
2944        assert!(
2945            Account::national("1", None, &Blz::new("1203000"), "X").is_err(),
2946            "BLZ has 8 digits"
2947        );
2948    }
2949
2950    #[test]
2951    fn german_iban_gives_the_national_details() {
2952        let german = Account::new(" de14 1234 5678 0000 0047 11 ", "TESTDEFFXXX").unwrap();
2953        assert_eq!(german.iban(), "DE14123456780000004711");
2954        assert_eq!(german.blz(), Some("12345678"));
2955        assert_eq!(german.account_number(), Some("4711"));
2956        assert_eq!(german.subaccount(), None);
2957
2958        let zeros = Account::new("DE00123456780000000000", "TESTDEFFXXX").unwrap();
2959        assert_eq!(zeros.account_number(), Some("0"));
2960    }
2961
2962    #[test]
2963    fn other_ibans_need_explicit_national_details() {
2964        let other = Account::new("XX00000000000000004711", "TESTXXXXXXX").unwrap();
2965        assert_eq!((other.blz(), other.account_number()), (None, None));
2966
2967        let with = other.with_national("4711", Some(""), &Blz::new("12345678"));
2968        assert_eq!(with.account_number(), Some("4711"));
2969        assert_eq!(with.subaccount(), None);
2970        assert_eq!(with.blz(), Some("12345678"));
2971        assert_eq!(with.iban(), "XX00000000000000004711");
2972    }
2973
2974    #[test]
2975    fn accounts_without_identifier_are_refused() {
2976        assert!(Account::new(" ", "TESTDEFFXXX").is_err());
2977        assert!(Account::new("DE14123456780000004711", "").is_err());
2978        let code = Blz::new("12345678");
2979        assert!(Account::national("", None, &code, "TESTDEFFXXX").is_err());
2980        assert!(Account::national("4711", None, &Blz::new("1234"), "TESTDEFFXXX").is_err());
2981        let depot = Account::national(" 4711 ", Some("01"), &code, "TESTDEFFXXX").unwrap();
2982        assert_eq!(depot.account_number(), Some("4711"));
2983        assert_eq!(depot.subaccount(), Some("01"));
2984        assert_eq!(depot.iban(), "");
2985    }
2986}