-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfints_agent_cli.py
More file actions
1588 lines (1409 loc) · 58.6 KB
/
fints_agent_cli.py
File metadata and controls
1588 lines (1409 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import getpass
import json
import logging
import os
import pickle
import re
import subprocess
import time
import uuid
import urllib.parse
import warnings
from dataclasses import asdict, dataclass
from datetime import date, datetime, timedelta
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Optional
from fints.client import FinTS3PinTanClient, NeedRetryResponse, NeedTANResponse, NeedVOPResponse
from fints.exceptions import FinTSClientError
from fints.parser import FinTSParserWarning
from fints.utils import minimal_interactive_cli_bootstrap
DEFAULT_BLZ = "12030000"
DEFAULT_SERVER = "https://fints.dkb.de/fints"
DEFAULT_PRODUCT_ID = "6151256F3D4F9975B877BD4A2"
DEFAULT_DECOUPLED_POLL_INTERVAL = 2.0
DEFAULT_DECOUPLED_TIMEOUT = 300
ENV_PRODUCT_ID = "FINTS_AGENT_CLI_PRODUCT_ID"
APP_DIR = Path.home() / ".config" / "fints-agent-cli"
CFG_PATH = APP_DIR / "config.json"
STATE_PATH = APP_DIR / "client_state.bin"
PENDING_DIR = APP_DIR / "pending"
BUNDLED_PROVIDERS_PATH = Path(__file__).resolve().with_name("providers.json")
USER_PROVIDERS_PATH = APP_DIR / "providers.json"
AQBANKING_BANKINFO_DE_CANDIDATES = [
Path("/opt/homebrew/Cellar/aqbanking/6.9.1/share/aqbanking/bankinfo/de/banks.data"),
Path("/opt/homebrew/share/aqbanking/bankinfo/de/banks.data"),
Path("/usr/local/share/aqbanking/bankinfo/de/banks.data"),
Path("/usr/share/aqbanking/bankinfo/de/banks.data"),
]
@dataclass
class Config:
blz: str = DEFAULT_BLZ
server: str = DEFAULT_SERVER
user_id: Optional[str] = None
customer_id: Optional[str] = None
product_id: Optional[str] = None
provider_id: Optional[str] = "dkb"
provider_name: Optional[str] = "DKB"
keychain_service: str = "fints-agent-cli-pin"
keychain_account: Optional[str] = None
@staticmethod
def load() -> "Config":
if CFG_PATH.exists():
data = json.loads(CFG_PATH.read_text(encoding="utf-8"))
return Config(**data)
return Config()
def save(self) -> None:
APP_DIR.mkdir(parents=True, exist_ok=True)
CFG_PATH.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
try:
os.chmod(CFG_PATH, 0o600)
except OSError:
pass
def load_state() -> Optional[bytes]:
if STATE_PATH.exists():
return STATE_PATH.read_bytes()
return None
def save_state(blob: bytes) -> None:
APP_DIR.mkdir(parents=True, exist_ok=True)
STATE_PATH.write_bytes(blob)
try:
os.chmod(STATE_PATH, 0o600)
except OSError:
pass
def pending_path(pending_id: str) -> Path:
return PENDING_DIR / f"{pending_id}.pkl"
def save_pending(pending_id: str, payload: dict) -> None:
PENDING_DIR.mkdir(parents=True, exist_ok=True)
path = pending_path(pending_id)
with path.open("wb") as f:
pickle.dump(payload, f)
try:
os.chmod(path, 0o600)
except OSError:
pass
def load_pending(pending_id: str) -> dict:
path = pending_path(pending_id)
if not path.exists():
raise SystemExit(f"Pending ID not found: {pending_id}")
with path.open("rb") as f:
return pickle.load(f)
def delete_pending(pending_id: str) -> None:
path = pending_path(pending_id)
if path.exists():
path.unlink()
def list_pending_ids() -> list[str]:
if not PENDING_DIR.exists():
return []
ids = []
for p in PENDING_DIR.glob("*.pkl"):
ids.append(p.stem)
return sorted(ids, key=lambda x: pending_path(x).stat().st_mtime, reverse=True)
def _default_seed_providers() -> list[dict]:
return [
{
"id": "dkb",
"name": "DKB",
"country": "DE",
"blz": "12030000",
"bic": "BYLADEM1001",
"fints_url": "https://fints.dkb.de/fints",
"auth_mode": "PINTAN",
"source": "manual",
"supports": {
"accounts": "yes",
"balance": "yes",
"transactions": "yes",
"transfer": "yes",
"instant": "unknown",
"vop": "unknown",
},
},
{
"id": "ing",
"name": "ING",
"country": "DE",
"blz": "50010517",
"bic": "INGDDEFFXXX",
"fints_url": "https://fints.ing.de/fints/",
"auth_mode": "PINTAN",
"source": "aqbanking-bankinfo-de",
"supports": {
"accounts": "yes",
"balance": "yes",
"transactions": "yes",
"transfer": "yes",
"instant": "unknown",
"vop": "unknown",
},
},
{
"id": "comdirect",
"name": "comdirect",
"country": "DE",
"blz": "20041111",
"bic": "COBADEHDXXX",
"fints_url": "https://fints.comdirect.de/fints",
"auth_mode": "PINTAN",
"source": "aqbanking-bankinfo-de",
"supports": {
"accounts": "yes",
"balance": "yes",
"transactions": "yes",
"transfer": "yes",
"instant": "unknown",
"vop": "unknown",
},
},
{
"id": "consorsbank",
"name": "Consorsbank",
"country": "DE",
"blz": "70120400",
"bic": "CSDBDE71XXX",
"fints_url": "https://brokerage-hbci.consorsbank.de/hbci",
"auth_mode": "PINTAN",
"source": "aqbanking-bankinfo-de",
"supports": {
"accounts": "yes",
"balance": "yes",
"transactions": "yes",
"transfer": "yes",
"instant": "unknown",
"vop": "unknown",
},
},
{
"id": "norisbank",
"name": "norisbank",
"country": "DE",
"blz": "10077777",
"bic": "NORSDE51XXX",
"fints_url": "https://fints.norisbank.de/",
"auth_mode": "PINTAN",
"source": "aqbanking-bankinfo-de",
"supports": {
"accounts": "yes",
"balance": "yes",
"transactions": "yes",
"transfer": "yes",
"instant": "unknown",
"vop": "unknown",
},
},
]
def _decode_text(value: str) -> str:
return urllib.parse.unquote(value or "").strip()
def _provider_id_for_blz(blz: str) -> str:
return f"de-{blz}"
def detect_aqbanking_bankinfo_path() -> Optional[Path]:
env = os.getenv("AQBANKING_BANKINFO_DE", "").strip()
if env:
p = Path(env).expanduser()
if p.exists():
return p
for path in AQBANKING_BANKINFO_DE_CANDIDATES:
if path.exists():
return path
return None
def import_aqbanking_bankinfo(path: Optional[Path] = None) -> list[dict]:
path = path or detect_aqbanking_bankinfo_path()
if path is None:
return []
if not path.exists():
return []
text = path.read_text(encoding="utf-8", errors="ignore")
raw_blocks = text.split('\n\nbankId="')
if raw_blocks and raw_blocks[0].startswith("#"):
raw_blocks = raw_blocks[1:]
providers: dict[str, dict] = {}
for idx, block in enumerate(raw_blocks):
if idx > 0 or not block.startswith('bankId="'):
block = 'bankId="' + block
bank_id = re.search(r'bankId="([0-9]+)"', block)
if not bank_id:
continue
blz = bank_id.group(1)
name_m = re.search(r'bankName="([^"]*)"', block)
bic_m = re.search(r'bic="([^"]*)"', block)
name = _decode_text(name_m.group(1) if name_m else "")
bic = _decode_text(bic_m.group(1) if bic_m else "")
svc_matches = re.finditer(
r'element\s*\{\s*type="([^"]+)"\s*address="([^"]*)"\s*pversion="([^"]*)"\s*mode="([^"]*)"\s*userFlags="([^"]*)"\s*\}',
block,
re.S,
)
for svc in svc_matches:
typ, addr, pversion, mode, user_flags = svc.groups()
typ = _decode_text(typ).upper()
addr = _decode_text(addr)
mode = _decode_text(mode).upper()
pversion = _decode_text(pversion)
if typ != "HBCI" or mode != "PINTAN" or not addr:
continue
pid = _provider_id_for_blz(blz)
old = providers.get(pid)
if old and old.get("source") == "manual":
continue
providers[pid] = {
"id": pid,
"name": name or f"Bank {blz}",
"country": "DE",
"blz": blz,
"bic": bic or None,
"fints_url": addr,
"auth_mode": mode,
"hbci_version_hint": pversion or None,
"user_flags": user_flags or None,
"source": "aqbanking-bankinfo-de",
"supports": {
"accounts": "unknown",
"balance": "unknown",
"transactions": "unknown",
"transfer": "unknown",
"instant": "unknown",
"vop": "unknown",
},
}
break
return sorted(providers.values(), key=lambda p: (p.get("name", ""), p.get("blz", "")))
def save_providers(providers: list[dict]) -> None:
APP_DIR.mkdir(parents=True, exist_ok=True)
USER_PROVIDERS_PATH.write_text(
json.dumps({"generated_at": datetime.now().isoformat(), "providers": providers}, indent=2, ensure_ascii=False),
encoding="utf-8",
)
try:
os.chmod(USER_PROVIDERS_PATH, 0o600)
except OSError:
pass
def merge_providers(*provider_lists: list[dict]) -> list[dict]:
merged: dict[str, dict] = {}
for items in provider_lists:
for item in items:
if not item.get("id"):
continue
merged[item["id"]] = {**merged.get(item["id"], {}), **item}
providers = [p for p in merged.values() if p.get("fints_url")]
return sorted(providers, key=lambda p: (p.get("name", ""), p.get("id", "")))
def normalize_provider_labels(providers: list[dict]) -> list[dict]:
# Keep canonical short labels for common providers even when imported data differs.
for p in providers:
if p.get("id") == "dkb":
p["name"] = "DKB"
return providers
def load_providers() -> list[dict]:
if USER_PROVIDERS_PATH.exists():
data = json.loads(USER_PROVIDERS_PATH.read_text(encoding="utf-8"))
if isinstance(data, list):
return normalize_provider_labels(data)
return normalize_provider_labels(data.get("providers", []))
if BUNDLED_PROVIDERS_PATH.exists():
data = json.loads(BUNDLED_PROVIDERS_PATH.read_text(encoding="utf-8"))
if isinstance(data, list):
return normalize_provider_labels(data)
if isinstance(data, dict):
providers = data.get("providers", [])
if providers:
return normalize_provider_labels(providers)
providers = merge_providers(_default_seed_providers(), import_aqbanking_bankinfo())
save_providers(providers)
return normalize_provider_labels(providers)
def resolve_provider(provider_ref: str, providers: list[dict]) -> dict:
ref = (provider_ref or "").strip()
if not ref:
raise SystemExit("Missing --provider.")
by_id = {p.get("id"): p for p in providers}
if ref in by_id:
return by_id[ref]
for p in providers:
if p.get("blz") == ref:
return p
low = ref.lower()
matches = [p for p in providers if low in (p.get("name", "").lower())]
if len(matches) == 1:
return matches[0]
if len(matches) > 1:
names = ", ".join(f"{m.get('id')} ({m.get('name')})" for m in matches[:8])
raise SystemExit(f"Ambiguous provider: {ref}. Matches: {names}")
raise SystemExit(f"Provider not found: {ref}")
def ensure_product_id(cfg: Config, cli_product_id: Optional[str]) -> None:
if cli_product_id:
cfg.product_id = cli_product_id
if not cfg.product_id:
cfg.product_id = os.getenv(ENV_PRODUCT_ID, "").strip() or None
if not cfg.product_id:
cfg.product_id = DEFAULT_PRODUCT_ID
def apply_provider_to_config(cfg: Config, provider: dict) -> None:
if not provider.get("fints_url"):
raise SystemExit(
f"Provider '{provider.get('id')}' hat keinen FinTS-Endpunkt. "
"This CLI mode only supports FinTS/HBCI PIN/TAN."
)
cfg.provider_id = provider.get("id")
cfg.provider_name = provider.get("name")
blz = provider.get("blz")
url = provider.get("fints_url")
if blz:
cfg.blz = blz
if url:
cfg.server = url
def serialize_supported_operations(info_map) -> dict[str, bool]:
out: dict[str, bool] = {}
for key, value in (info_map or {}).items():
name = getattr(key, "name", str(key))
out[str(name).lower()] = bool(value)
return out
def build_client(cfg: Config, pin: str) -> FinTS3PinTanClient:
return FinTS3PinTanClient(
cfg.blz,
cfg.user_id,
pin,
cfg.server,
customer_id=cfg.customer_id,
product_id=cfg.product_id,
from_data=load_state(),
)
def build_client_with_state(cfg: Config, pin: str, state_blob: Optional[bytes]) -> FinTS3PinTanClient:
return FinTS3PinTanClient(
cfg.blz,
cfg.user_id,
pin,
cfg.server,
customer_id=cfg.customer_id,
product_id=cfg.product_id,
from_data=state_blob,
)
def pin_key(cfg: Config) -> str:
user = cfg.user_id or "user"
return f"PIN_{cfg.blz}_{user}"
def clean_text(value) -> str:
if value is None:
return ""
text = str(value).replace("\n", " ").replace("\r", " ").replace("\t", " ")
return " ".join(text.split())
def normalize_iban(value: str) -> str:
return re.sub(r"\s+", "", (value or "")).upper()
def validate_iban(value: str) -> bool:
iban = normalize_iban(value)
if len(iban) < 15 or len(iban) > 34:
return False
if not re.match(r"^[A-Z0-9]+$", iban):
return False
moved = iban[4:] + iban[:4]
converted = ""
for ch in moved:
if ch.isdigit():
converted += ch
else:
converted += str(ord(ch) - 55)
try:
return int(converted) % 97 == 1
except ValueError:
return False
def validate_bic(value: str) -> bool:
bic = (value or "").strip().upper()
return bool(re.match(r"^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$", bic))
def _normalize_iban_candidate(value) -> str:
if value is None:
return ""
if isinstance(value, list):
value = " ".join(str(x) for x in value if x is not None)
text = str(value).strip().upper()
if not text:
return ""
compact = normalize_iban(text)
if validate_iban(compact):
return compact
return ""
def extract_counterparty_iban(data: dict, purpose: str = "") -> str:
if not isinstance(data, dict):
data = {}
direct_keys = [
"recipient_iban",
"applicant_iban",
"counterparty_iban",
"remote_iban",
"iban",
"creditor_iban",
"debtor_iban",
]
for key in direct_keys:
iban = _normalize_iban_candidate(data.get(key))
if iban:
return iban
for key, raw in data.items():
if "iban" not in str(key).lower():
continue
iban = _normalize_iban_candidate(raw)
if iban:
return iban
# Fallback for purpose lines that contain "IBAN <...>" or plain IBAN-like tokens.
haystack = f"{purpose} {data.get('purpose', '')}".upper()
for match in re.finditer(r"[A-Z]{2}[0-9A-Z ]{13,40}", haystack):
candidate = normalize_iban(match.group(0))
if validate_iban(candidate):
return candidate
return ""
def print_transactions(rows, out_format: str, max_purpose: int) -> None:
if out_format == "json":
print(json.dumps(rows, ensure_ascii=False))
return
if out_format == "tsv":
print("date\tamount\tcounterparty\tcounterparty_iban\tpurpose")
for row in rows:
print(
f"{row['date']}\t{row['amount']}\t{row['counterparty']}\t"
f"{row.get('counterparty_iban', '')}\t{row['purpose']}"
)
return
date_w = 10
amount_w = max(12, max((len(r["amount"]) for r in rows), default=12))
cp_w = max(16, min(40, max((len(r["counterparty"]) for r in rows), default=16)))
iban_w = max(12, min(34, max((len(r.get("counterparty_iban", "")) for r in rows), default=12)))
header = (
f"{'Date':<{date_w}} {'Amount':>{amount_w}} {'Counterparty':<{cp_w}} "
f"{'IBAN':<{iban_w}} Purpose"
)
print(header)
print("-" * len(header))
for row in rows:
purpose = row["purpose"]
if max_purpose > 0 and len(purpose) > max_purpose:
purpose = purpose[: max_purpose - 3] + "..."
cp = row["counterparty"][:cp_w]
iban = row.get("counterparty_iban", "")[:iban_w]
print(
f"{row['date']:<{date_w}} {row['amount']:>{amount_w}} "
f"{cp:<{cp_w}} {iban:<{iban_w}} {purpose}"
)
def keychain_get_pin(service: str, account: str) -> Optional[str]:
proc = subprocess.run(
["security", "find-generic-password", "-s", service, "-a", account, "-w"],
check=False,
capture_output=True,
text=True,
)
if proc.returncode != 0:
return None
val = proc.stdout.strip()
return val or None
def keychain_store_pin(service: str, account: str, pin: str) -> None:
proc = subprocess.run(
["security", "add-generic-password", "-U", "-a", account, "-s", service, "-w", pin],
check=False,
capture_output=True,
text=True,
)
if proc.returncode != 0:
err = (proc.stderr or "").strip()
raise SystemExit(f"Failed to save to Keychain: {err or 'no details'}")
def resolve_keychain(args, cfg: Config) -> tuple[str, str]:
service = (getattr(args, "keychain_service", None) or cfg.keychain_service).strip()
account = (
getattr(args, "keychain_account", None)
or cfg.keychain_account
or cfg.user_id
or ""
).strip()
if not service or not account:
raise SystemExit("Missing Keychain service/account.")
return service, account
def get_pin(args, cfg: Config) -> str:
if getattr(args, "no_keychain", False):
return getpass.getpass("Bank PIN: ")
try:
service, account = resolve_keychain(args, cfg)
except SystemExit:
return getpass.getpass("Bank PIN: ")
pin = keychain_get_pin(service, account)
if pin:
return pin
return getpass.getpass("Bank PIN: ")
def complete_tan(
client: FinTS3PinTanClient,
resp,
*,
auto_approve_vop: bool = False,
decoupled_auto_poll: bool = True,
decoupled_poll_interval: float = DEFAULT_DECOUPLED_POLL_INTERVAL,
decoupled_timeout: int = DEFAULT_DECOUPLED_TIMEOUT,
):
decoupled_attempts = 0
decoupled_started = None
while True:
if isinstance(resp, NeedVOPResponse):
print("Received bank VoP warning (payee verification).")
if auto_approve_vop:
print("VoP auto-approved.")
else:
input("Continue with VoP confirmation? Enter = yes, Ctrl+C = abort: ")
resp = client.approve_vop_response(resp)
continue
if not isinstance(resp, NeedTANResponse):
return resp
# Do not print raw bank challenge text (often localized); keep CLI output consistently English.
print("\nSCA challenge: Please confirm this action in your banking app.")
if getattr(resp, "decoupled", False):
# Always poll in decoupled mode: no Enter required.
if decoupled_started is None:
decoupled_started = time.time()
print(
f"Waiting for app approval (poll every {decoupled_poll_interval:.1f}s, "
f"timeout {decoupled_timeout}s) ..."
)
else:
if int(time.time() - decoupled_started) >= decoupled_timeout:
raise SystemExit("SCA app approval timeout. Please restart.")
time.sleep(decoupled_poll_interval)
try:
resp = client.send_tan(resp, "")
except FinTSClientError as exc:
decoupled_attempts += 1
if decoupled_attempts >= 200:
raise SystemExit("SCA app approval did not complete (polling).") from exc
continue
continue
tan = getpass.getpass("TAN: ")
try:
resp = client.send_tan(resp, tan)
except FinTSClientError as exc:
raise SystemExit(f"TAN failed: {exc}") from exc
def complete_vop_only(client: FinTS3PinTanClient, resp, *, auto_approve_vop: bool = False):
while isinstance(resp, NeedVOPResponse):
print("Received bank VoP warning (payee verification).")
if auto_approve_vop:
print("VoP auto-approved.")
else:
input("Continue with VoP confirmation? Enter = yes, Ctrl+C = abort: ")
resp = client.approve_vop_response(resp)
return resp
def pick_account(accounts, from_iban: Optional[str]):
if not accounts:
raise SystemExit("No SEPA accounts found.")
if from_iban:
needle = from_iban.replace(" ", "").upper()
for acc in accounts:
if acc.iban.replace(" ", "").upper() == needle:
return acc
raise SystemExit(f"from-iban not found: {from_iban}")
if len(accounts) == 1:
return accounts[0]
print("Multiple accounts found. Please set --from-iban:")
for acc in accounts:
print(" -", acc.iban)
raise SystemExit(2)
def ensure_init_ok(client: FinTS3PinTanClient) -> None:
while isinstance(getattr(client, "init_tan_response", None), NeedTANResponse):
client.init_tan_response = complete_tan(client, client.init_tan_response)
def cmd_providers_list(args, _cfg: Config) -> int:
providers = load_providers()
rows = providers
if args.search:
needle = args.search.lower()
rows = [
p for p in rows if needle in p.get("name", "").lower() or needle in p.get("id", "").lower() or needle in p.get("blz", "")
]
if args.country:
rows = [p for p in rows if p.get("country") == args.country]
rows = rows[: args.limit]
print("id\tblz\tname\turl")
for p in rows:
print(f"{p.get('id','')}\t{p.get('blz','')}\t{p.get('name','')}\t{p.get('fints_url','')}")
print(f"\nMatches: {len(rows)}")
return 0
def cmd_providers_show(args, _cfg: Config) -> int:
providers = load_providers()
provider = resolve_provider(args.provider, providers)
print(json.dumps(provider, indent=2, ensure_ascii=False))
return 0
def cmd_capabilities(args, cfg: Config) -> int:
if not cfg.user_id:
raise SystemExit("Please run bootstrap first.")
ensure_product_id(cfg, args.product_id)
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
with client:
ensure_init_ok(client)
info = client.get_information()
bank_info = info.get("bank", {})
out = {
"provider_id": cfg.provider_id,
"provider_name": cfg.provider_name,
"bank_name": bank_info.get("name"),
"bank_supported_operations": serialize_supported_operations(bank_info.get("supported_operations", {})),
"accounts": [],
}
for acc in info.get("accounts", []):
if args.iban and normalize_iban(acc.get("iban", "")) != normalize_iban(args.iban):
continue
out["accounts"].append(
{
"iban": acc.get("iban"),
"product_name": acc.get("product_name"),
"currency": acc.get("currency"),
"supported_operations": serialize_supported_operations(acc.get("supported_operations", {})),
}
)
print(json.dumps(out, indent=2, ensure_ascii=False))
save_state(client.deconstruct(including_private=True))
cfg.save()
return 0
def cmd_bootstrap(args, cfg: Config) -> int:
print("Starting bootstrap.")
print("This will refresh TAN/SCA setup with your bank.")
if args.provider:
provider = resolve_provider(args.provider, load_providers())
apply_provider_to_config(cfg, provider)
print(
f"Provider set: {provider.get('id')} - {provider.get('name')} "
f"({provider.get('blz')} -> {provider.get('fints_url')})"
)
if args.user_id:
cfg.user_id = args.user_id
if args.customer_id is not None:
cfg.customer_id = args.customer_id
if args.server:
cfg.server = args.server
if args.blz:
cfg.blz = args.blz
ensure_product_id(cfg, args.product_id)
if not cfg.user_id:
raise SystemExit("Missing --user-id")
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
minimal_interactive_cli_bootstrap(client)
save_state(client.deconstruct(including_private=True))
cfg.save()
print("Bootstrap ok.")
print("Next step: run `fints-agent-cli accounts`.")
return 0
def cmd_accounts(args, cfg: Config) -> int:
if not cfg.user_id:
raise SystemExit("Please run bootstrap first.")
print("Fetching accounts and balances...")
ensure_product_id(cfg, args.product_id)
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
row_count = 0
with client:
ensure_init_ok(client)
accounts = complete_tan(client, client.get_sepa_accounts())
if not accounts:
print("No SEPA accounts returned by bank.")
return 0
print("Output format: <IBAN> <TAB> <Amount> <TAB> <Currency>")
for acc in accounts:
bal = complete_tan(client, client.get_balance(acc))
amount = getattr(bal, "amount", None)
currency = getattr(amount, "currency", "")
print(f"{acc.iban}\t{amount}\t{currency}")
row_count += 1
save_state(client.deconstruct(including_private=True))
cfg.save()
print(f"Done. {row_count} account(s) listed.")
print("Tip: `fints-agent-cli transactions --iban <IBAN> --days 30`.")
return 0
def cmd_transactions(args, cfg: Config) -> int:
if not cfg.user_id:
raise SystemExit("Please run bootstrap first.")
print("Fetching transactions...")
ensure_product_id(cfg, args.product_id)
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
from_date = date.today() - timedelta(days=args.days)
to_date = date.today()
print(f"Date window: {from_date.isoformat()} .. {to_date.isoformat()} ({args.days} days)")
with client:
ensure_init_ok(client)
accounts = complete_tan(client, client.get_sepa_accounts())
account = None
for acc in accounts:
if args.iban and acc.iban.replace(" ", "") == args.iban.replace(" ", ""):
account = acc
break
if args.iban and not account:
raise SystemExit(f"IBAN not found: {args.iban}")
if not account:
# Default: first account
account = accounts[0]
print(f"No --iban provided. Using first account: {account.iban}")
else:
print(f"Using account: {account.iban}")
tx = client.get_transactions(account, start_date=from_date, end_date=to_date)
tx = complete_tan(client, tx)
rows = []
for item in tx:
if hasattr(item, "data"):
raw_purpose = item.data.get("purpose")
if isinstance(raw_purpose, list):
purpose = " ".join(str(x) for x in raw_purpose if x is not None)
elif raw_purpose is None:
purpose = ""
else:
purpose = str(raw_purpose)
amount = item.data.get("amount", "")
booking_date = item.data.get("date", "")
counterparty_iban = extract_counterparty_iban(item.data, purpose)
counterparty = (
item.data.get("applicant_name")
or item.data.get("recipient_name")
or item.data.get("name")
or ""
)
if isinstance(counterparty, list):
counterparty = " ".join(str(x) for x in counterparty if x is not None)
counterparty = str(counterparty)
else:
purpose = ""
amount = ""
booking_date = ""
counterparty = ""
counterparty_iban = ""
rows.append(
{
"date": clean_text(booking_date),
"amount": clean_text(amount),
"counterparty": clean_text(counterparty),
"counterparty_iban": clean_text(counterparty_iban),
"purpose": clean_text(purpose),
}
)
print_transactions(rows, args.format, args.max_purpose)
print(f"Done. {len(rows)} transaction(s) returned.")
if not rows:
print("No transactions in selected range/account.")
print("Try `--days 90` or set `--iban <IBAN>` explicitly.")
save_state(client.deconstruct(including_private=True))
cfg.save()
return 0
def validate_transfer_args(args) -> Decimal:
try:
amount = Decimal(args.amount)
except InvalidOperation as exc:
raise SystemExit(f"Invalid amount: {args.amount}") from exc
if amount <= 0:
raise SystemExit("Amount must be > 0.")
if not validate_iban(args.to_iban):
raise SystemExit(f"Invalid recipient IBAN: {args.to_iban}")
if args.to_bic and not validate_bic(args.to_bic):
raise SystemExit(f"Invalid recipient BIC: {args.to_bic}")
if len((args.to_name or "").strip()) < 2:
raise SystemExit("Recipient name is too short.")
if len((args.reason or "").strip()) < 2:
raise SystemExit("Purpose is too short.")
if len(args.reason) > 140:
raise SystemExit("Purpose is too long (max 140 chars).")
return amount
def submit_transfer_request(client: FinTS3PinTanClient, cfg: Config, args, amount: Decimal, account):
return client.simple_sepa_transfer(
account=account,
iban=args.to_iban,
bic=args.to_bic,
recipient_name=args.to_name,
amount=amount,
account_name=args.sender_name or cfg.user_id or "Bankkonto",
reason=args.reason,
instant_payment=bool(args.instant),
)
def cmd_transfer(args, cfg: Config) -> int:
if not cfg.user_id:
raise SystemExit("Please run bootstrap first.")
print("Starting transfer flow...")
ensure_product_id(cfg, args.product_id)
amount = validate_transfer_args(args)
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
with client:
ensure_init_ok(client)
accounts = complete_tan(client, client.get_sepa_accounts())
account = pick_account(accounts, args.from_iban)
auto_mode = bool(args.auto)
auto_approve_vop = auto_mode or bool(args.auto_vop)
auto_poll = auto_mode or bool(args.auto_poll)
if args.dry_run:
print("DRY-RUN OK (no order sent)")
print(" From: ", account.iban)
print(" To: ", normalize_iban(args.to_iban), f"({args.to_name})")
print(" Amount:", amount, "EUR")
print(" Purpose:", args.reason)
print(" Instant:", bool(args.instant))
return 0
if not (args.yes or auto_mode):
print("\nTransfer (preview)")
print(" From: ", account.iban)
print(" To: ", args.to_iban, f"({args.to_name})")
print(" Amount:", amount, "EUR")
print(" Purpose:", args.reason)
print(" Instant:", bool(args.instant))
input("Send? Enter = yes, Ctrl+C = abort: ")
resp = submit_transfer_request(client, cfg, args, amount, account)
resp = complete_tan(
client,
complete_vop_only(client, resp, auto_approve_vop=auto_approve_vop),
auto_approve_vop=auto_approve_vop,
decoupled_auto_poll=auto_poll,
decoupled_poll_interval=args.poll_interval,
decoupled_timeout=args.poll_timeout,
)
print("\nResult:")
print(getattr(resp, "status", resp))
responses = getattr(resp, "responses", None)
if responses:
for line in responses:
code = getattr(line, "code", None)
text = getattr(line, "text", None)
if code or text:
print(" -", code, text)
print("Transfer flow finished.")
save_state(client.deconstruct(including_private=True))
cfg.save()
return 0
def cmd_transfer_submit(args, cfg: Config) -> int:
if not cfg.user_id:
raise SystemExit("Please run bootstrap first.")
print("Starting async transfer submission...")
ensure_product_id(cfg, args.product_id)
amount = validate_transfer_args(args)
pin = get_pin(args, cfg)
client = build_client(cfg, pin)
with client:
ensure_init_ok(client)