hanseatic-export 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """Public API for the unofficial Hanseatic transaction exporter."""
2
+
3
+ from .client import Client, ExportError, TransactionResult
4
+ from .export import CSV_COLUMNS, export_csv, export_json
5
+
6
+ __all__ = ["Client", "ExportError", "TransactionResult", "CSV_COLUMNS", "export_csv", "export_json"]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,190 @@
1
+ """Interactive wrapper around the public exporter API."""
2
+
3
+ import argparse
4
+ import getpass
5
+ import math
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import warnings
10
+ from pathlib import Path
11
+
12
+ from . import Client, ExportError, export_csv, export_json
13
+
14
+
15
+ def _positive(value):
16
+ number = float(value)
17
+ if not math.isfinite(number) or number <= 0:
18
+ raise argparse.ArgumentTypeError("must be finite and positive")
19
+ return number
20
+
21
+
22
+ def _message(message):
23
+ print(message, file=sys.stderr, flush=True)
24
+
25
+
26
+ def _ask(prompt):
27
+ print(prompt, end="", file=sys.stderr, flush=True)
28
+ answer = sys.stdin.readline()
29
+ if not answer:
30
+ raise EOFError
31
+ return answer.rstrip("\r\n")
32
+
33
+
34
+ def _secret(prompt):
35
+ with warnings.catch_warnings():
36
+ warnings.simplefilter("error", getpass.GetPassWarning)
37
+ try:
38
+ return getpass.getpass(prompt, stream=sys.stderr)
39
+ except getpass.GetPassWarning:
40
+ raise ExportError("A terminal with hidden input is required for secrets.") from None
41
+
42
+
43
+ def _credentials():
44
+ user = os.environ.get("HANSEATIC_USER")
45
+ password = os.environ.get("HANSEATIC_PASSWORD")
46
+ if user is not None and password is not None:
47
+ return user.strip(), password
48
+ if user is not None or password is not None:
49
+ raise ExportError("Both HANSEATIC_USER and HANSEATIC_PASSWORD must be set, or neither.")
50
+ if not sys.stdin.isatty():
51
+ raise ExportError("Run from an interactive terminal to sign in.")
52
+ return _ask("Login ID: ").strip(), _secret("Password: ")
53
+
54
+
55
+ def _choose_account(accounts, requested):
56
+ if requested is not None:
57
+ if requested not in accounts:
58
+ raise ExportError("--account must be an account returned by discovery.")
59
+ return requested
60
+ if len(accounts) == 1:
61
+ return accounts[0]
62
+ if not sys.stdin.isatty():
63
+ raise ExportError("Multiple accounts found; select one with --account.")
64
+ for index, account in enumerate(accounts, 1):
65
+ _message(f"{index}. {ascii(account)}")
66
+ choice = _ask("Select account number from the list: ").strip()
67
+ for index, account in enumerate(accounts, 1):
68
+ if choice == str(index):
69
+ return account
70
+ raise ExportError("Invalid account selection.")
71
+
72
+
73
+ def _publish(outputs, overwrite):
74
+ # Stage every file before publishing any file. Hard links provide atomic
75
+ # no-clobber publication in the destination directory.
76
+ staged = []
77
+ written = []
78
+ try:
79
+ for path, contents in outputs:
80
+ with tempfile.NamedTemporaryFile(
81
+ dir=path.parent, prefix=".hanseatic-", delete=False
82
+ ) as handle:
83
+ temporary = Path(handle.name)
84
+ staged.append((temporary, path))
85
+ handle.write(contents)
86
+ handle.flush()
87
+ os.fsync(handle.fileno())
88
+ for temporary, path in staged:
89
+ if overwrite:
90
+ os.replace(temporary, path)
91
+ else:
92
+ os.link(temporary, path)
93
+ written.append(path)
94
+ except OSError:
95
+ if written:
96
+ _message("Files already written: " + ", ".join(ascii(str(path)) for path in written))
97
+ raise ExportError(
98
+ "Could not write export files; check destination and overwrite settings."
99
+ ) from None
100
+ finally:
101
+ for temporary, _ in staged:
102
+ temporary.unlink(missing_ok=True)
103
+
104
+
105
+ def main(argv=None):
106
+ parser = argparse.ArgumentParser(
107
+ prog="hanseatic-export", description="Export your Hanseatic card transactions."
108
+ )
109
+ parser.add_argument("--csv", action="store_true", help="select CSV (both formats by default)")
110
+ parser.add_argument(
111
+ "--json", action="store_true", help="select raw JSON (both formats by default)"
112
+ )
113
+ destination = parser.add_mutually_exclusive_group()
114
+ destination.add_argument("--output", help="output path or - for stdout; select one format")
115
+ destination.add_argument("--output-dir", type=Path, help="directory for default filenames")
116
+ parser.add_argument("--overwrite", action="store_true", help="replace existing output files")
117
+ parser.add_argument(
118
+ "--all", action="store_true", help="request older history with bank approval"
119
+ )
120
+ parser.add_argument(
121
+ "--booked-only", action="store_true", help="CSV only: include explicitly booked rows"
122
+ )
123
+ parser.add_argument("--account", help="select a discovered account by ID")
124
+ parser.add_argument(
125
+ "--timeout", type=_positive, default=20, help="HTTP timeout (default: 20 seconds)"
126
+ )
127
+ parser.add_argument(
128
+ "--sca-timeout",
129
+ type=_positive,
130
+ default=120,
131
+ help="approval deadline (default: 120 seconds)",
132
+ )
133
+ parser.add_argument("--max-pages", type=int, default=100, help="page limit (default: 100)")
134
+ args = parser.parse_args(argv)
135
+ formats = [fmt for fmt in ("csv", "json") if getattr(args, fmt)] or ["csv", "json"]
136
+ if args.output is not None and len(formats) != 1:
137
+ parser.error("--output requires exactly one of --csv or --json")
138
+ if args.booked_only and formats != ["csv"]:
139
+ parser.error("--booked-only requires --csv without --json")
140
+ if args.max_pages < 1:
141
+ parser.error("--max-pages must be positive")
142
+ stdout = args.output == "-"
143
+ paths = (
144
+ [Path(args.output)]
145
+ if args.output is not None
146
+ else [(args.output_dir or Path.cwd()) / f"transactions.{fmt}" for fmt in formats]
147
+ )
148
+ try:
149
+ if not stdout:
150
+ for path in paths:
151
+ if not path.parent.is_dir() or path.is_dir():
152
+ raise ExportError("Invalid output destination; use an existing directory.")
153
+ if not args.overwrite and (path.exists() or path.is_symlink()):
154
+ raise ExportError(
155
+ "Output already exists; choose a different path or use --overwrite."
156
+ )
157
+ with Client(
158
+ timeout=args.timeout, sca_timeout=args.sca_timeout, max_pages=args.max_pages
159
+ ) as client:
160
+ client.login(credentials=_credentials, tan=_secret, notify=_message)
161
+ account = _choose_account(client.accounts(), args.account)
162
+ result = client.transactions(
163
+ account, all_history=args.all, tan=_secret, notify=_message
164
+ )
165
+ if result.history_status == "limited_by_sca":
166
+ _message("History limited by bank approval. Use --all to request older transactions.")
167
+ try:
168
+ contents = [
169
+ export_csv(result.pages, booked_only=args.booked_only)
170
+ if fmt == "csv"
171
+ else export_json(result.pages)
172
+ for fmt in formats
173
+ ]
174
+ except (ValueError, ArithmeticError, RecursionError):
175
+ raise ExportError("Could not serialize bank transaction data.") from None
176
+ if stdout:
177
+ sys.stdout.buffer.write(contents[0])
178
+ sys.stdout.buffer.flush()
179
+ else:
180
+ _publish(zip(paths, contents), args.overwrite)
181
+ except ExportError as error:
182
+ _message(f"Error: {error}")
183
+ return 1
184
+ except (EOFError, KeyboardInterrupt):
185
+ _message("Export cancelled.")
186
+ return 1
187
+ except OSError:
188
+ _message("Error: Local input or output failed.")
189
+ return 1
190
+ return 0
@@ -0,0 +1,456 @@
1
+ """Read-only client for the unofficial banking protocol."""
2
+
3
+ import base64
4
+ import re
5
+ import time
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timezone
8
+ from email.utils import parsedate_to_datetime
9
+ from math import isfinite
10
+ from typing import Literal
11
+ from urllib.parse import quote
12
+
13
+ import requests
14
+ import simplejson
15
+
16
+ LOGIN_URL = "https://meine.hanseaticbank.de/de/register/sign-in"
17
+ API = "https://connecthb.hanseaticbank.de"
18
+ ACCOUNTS = "/customerportal/1.0/accounts"
19
+ TRANSACTIONS = "/transaction/1.0/transactionsEnriched/"
20
+ PENDING = ("open", "accepted")
21
+
22
+
23
+ class ExportError(Exception):
24
+ """A sanitized error suitable for display to the user."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class TransactionResult:
29
+ pages: tuple[dict, ...]
30
+ history_status: Literal["complete", "limited_by_sca"]
31
+
32
+
33
+ def _configuration(html):
34
+ values = {}
35
+ for key in (
36
+ "BASIC_AUTH",
37
+ "NORTHLAYER_BASE_URL",
38
+ "NORTHLAYER_CLIENT_KEY",
39
+ "NORTHLAYER_CLIENT_SECRET",
40
+ ):
41
+ matches = re.findall(rf'\b{key}["\']?\s*:\s*["\']([^"\'\r\n]+)["\']', html)
42
+ if len(matches) != 1 or not matches[0].strip():
43
+ raise ExportError(
44
+ "Bank configuration missing or ambiguous; the portal may have changed."
45
+ )
46
+ values[key] = matches[0]
47
+ if values["NORTHLAYER_BASE_URL"] not in (API, API + "/"):
48
+ raise ExportError("Unexpected bank API URL; no credentials were sent.")
49
+ if not re.fullmatch(r"Basic [A-Za-z0-9+/]+={0,2}", values["BASIC_AUTH"]):
50
+ raise ExportError("Invalid bank authorization configuration.")
51
+ return values
52
+
53
+
54
+ def _object(value):
55
+ if not isinstance(value, dict):
56
+ raise ExportError("Unexpected bank response structure.")
57
+ return value
58
+
59
+
60
+ def _unique_keys(items):
61
+ result = {}
62
+ for key, value in items:
63
+ if key in result:
64
+ raise ValueError("Duplicate JSON field.")
65
+ result[key] = value
66
+ return result
67
+
68
+
69
+ def _header_value(value):
70
+ if not isinstance(value, str) or not re.fullmatch(r"[!-~]+", value):
71
+ raise ExportError("Missing or invalid bank token.")
72
+ return value
73
+
74
+
75
+ def _segment(value):
76
+ if (
77
+ not isinstance(value, str)
78
+ or not value.strip()
79
+ or value in (".", "..")
80
+ or any(char in "/\\%" or ord(char) < 32 or ord(char) == 127 for char in value)
81
+ ):
82
+ raise ExportError("Missing or invalid bank identifier.")
83
+ return quote(value, safe="")
84
+
85
+
86
+ def _challenge_id(token):
87
+ try:
88
+ _, payload, _ = token.split(".")
89
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", payload):
90
+ raise ValueError
91
+ claims = simplejson.loads(
92
+ base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)),
93
+ object_pairs_hook=_unique_keys,
94
+ )
95
+ return _object(claims).get("sca_id")
96
+ except (AttributeError, ValueError, UnicodeError, RecursionError):
97
+ raise ExportError("Missing or invalid login challenge metadata.") from None
98
+
99
+
100
+ def _retry_delay(header):
101
+ if header is None:
102
+ return 1
103
+ try:
104
+ if re.fullmatch(r"[0-9]+", header):
105
+ return int(header)
106
+ return max(0, (parsedate_to_datetime(header) - datetime.now(timezone.utc)).total_seconds())
107
+ except (ValueError, TypeError, OverflowError):
108
+ return None
109
+
110
+
111
+ class Client:
112
+ """Context-managed banking session; all user interaction is caller-supplied."""
113
+
114
+ def __init__(
115
+ self,
116
+ *,
117
+ session=None,
118
+ timeout=20,
119
+ sca_timeout=120,
120
+ max_pages=100,
121
+ clock=time.monotonic,
122
+ sleep=time.sleep,
123
+ ):
124
+ if not (
125
+ isfinite(timeout)
126
+ and timeout > 0
127
+ and isfinite(sca_timeout)
128
+ and sca_timeout > 0
129
+ and type(max_pages) is int
130
+ and max_pages > 0
131
+ ):
132
+ raise ValueError("Timeouts and page limit must be finite and positive.")
133
+ self._session = session if session is not None else requests.Session()
134
+ self._session.trust_env = False
135
+ self._timeout = timeout
136
+ self._sca_timeout = sca_timeout
137
+ self._max_pages = max_pages
138
+ self._clock = clock
139
+ self._sleep = sleep
140
+ self._authorization = None
141
+ self._login_id = None
142
+ self._account_ids = ()
143
+ self._closed = False
144
+
145
+ def __enter__(self):
146
+ return self
147
+
148
+ def __exit__(self, *_):
149
+ self.close()
150
+
151
+ def close(self):
152
+ """Close the session and discard authorization and session cookies."""
153
+ self._authorization = None
154
+ self._login_id = None
155
+ self._account_ids = ()
156
+ self._closed = True
157
+ self._session.cookies.clear()
158
+ self._session.close()
159
+
160
+ def _remaining(self, deadline):
161
+ remaining = deadline - self._clock()
162
+ if remaining <= 0:
163
+ raise ExportError("Bank approval timed out.")
164
+ return remaining
165
+
166
+ def _request(
167
+ self,
168
+ method,
169
+ path,
170
+ *,
171
+ authorization=None,
172
+ deadline=None,
173
+ read_retry=False,
174
+ html=False,
175
+ headers=None,
176
+ **kwargs,
177
+ ):
178
+ if self._closed:
179
+ raise ExportError("The bank session is closed.")
180
+ target = LOGIN_URL if html else API + path
181
+ request_headers = {
182
+ "User-Agent": "hanseatic-export/0.1",
183
+ "Accept-Language": "de-DE,de;q=0.9",
184
+ }
185
+ request_headers.update(headers or {})
186
+ if authorization is not None:
187
+ request_headers["Authorization"] = authorization
188
+ attempts = 2 if method == "GET" and read_retry else 1
189
+ for attempt in range(attempts):
190
+ timeout = (
191
+ self._timeout if deadline is None else min(self._timeout, self._remaining(deadline))
192
+ )
193
+ try:
194
+ response = self._session.request(
195
+ method,
196
+ target,
197
+ headers=request_headers,
198
+ timeout=timeout,
199
+ allow_redirects=False,
200
+ verify=True,
201
+ **kwargs,
202
+ )
203
+ except (requests.Timeout, requests.ConnectionError) as error:
204
+ if attempt + 1 < attempts and not isinstance(error, requests.exceptions.SSLError):
205
+ self._sleep(1)
206
+ continue
207
+ message = (
208
+ "Bank request timed out."
209
+ if isinstance(error, requests.Timeout)
210
+ else ("Could not connect securely to the bank.")
211
+ )
212
+ raise ExportError(message) from None
213
+ except requests.RequestException:
214
+ raise ExportError("Bank request failed.") from None
215
+ with response:
216
+ if deadline is not None:
217
+ self._remaining(deadline)
218
+ status = response.status_code
219
+ if status == 200:
220
+ if html:
221
+ return response.text
222
+ try:
223
+ return simplejson.loads(
224
+ response.content,
225
+ use_decimal=True,
226
+ allow_nan=False,
227
+ object_pairs_hook=_unique_keys,
228
+ )
229
+ except (ValueError, ArithmeticError, RecursionError):
230
+ raise ExportError("Bank returned invalid JSON.") from None
231
+ if attempt + 1 < attempts and (status == 429 or 500 <= status < 600):
232
+ delay = _retry_delay(response.headers.get("Retry-After"))
233
+ if delay is not None and delay <= 5:
234
+ self._sleep(max(1, delay))
235
+ continue
236
+ if status in (401, 403):
237
+ raise ExportError(
238
+ f"Bank denied the request (HTTP {status}); check the official portal."
239
+ )
240
+ if status == 429:
241
+ raise ExportError("Bank rate limit reached (HTTP 429); try again later.")
242
+ if 300 <= status < 400:
243
+ raise ExportError("Unexpected redirect from the bank; request stopped.")
244
+ raise ExportError(f"Bank request failed (HTTP {status}).")
245
+
246
+ def _token(self, authorization, fields, *, headers=None, deadline=None):
247
+ return _object(
248
+ self._request(
249
+ "POST",
250
+ "/token",
251
+ authorization=authorization,
252
+ deadline=deadline,
253
+ data=fields,
254
+ headers={
255
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
256
+ **(headers or {}),
257
+ },
258
+ )
259
+ )
260
+
261
+ def _pause(self, deadline):
262
+ self._sleep(min(5, self._remaining(deadline)))
263
+
264
+ def _tan(self, prompt, deadline):
265
+ self._remaining(deadline)
266
+ value = prompt("SMS TAN: ")
267
+ self._remaining(deadline)
268
+ if not isinstance(value, str) or not value.strip():
269
+ raise ExportError("SMS approval cancelled.")
270
+ return value.strip()
271
+
272
+ def login(self, *, credentials, tan, notify):
273
+ """Sign in using a `(login_id, password)` callback and SCA callbacks."""
274
+ if self._authorization is not None:
275
+ raise ExportError("Already signed in; open a new session to sign in again.")
276
+ config = _configuration(self._request("GET", "", html=True, read_retry=True))
277
+ user, password = credentials()
278
+ if (
279
+ not isinstance(user, str)
280
+ or not user.strip()
281
+ or not isinstance(password, str)
282
+ or not password
283
+ ):
284
+ raise ExportError("Login ID and password are required.")
285
+ user_path = _segment(user)
286
+ generic = self._token(
287
+ "Bearer undefined",
288
+ {
289
+ "grant_type": "client_credentials",
290
+ "client_id": config["NORTHLAYER_CLIENT_KEY"],
291
+ "client_secret": config["NORTHLAYER_CLIENT_SECRET"],
292
+ },
293
+ )
294
+ generic_auth = "Bearer " + _header_value(generic.get("access_token"))
295
+ basic = config["BASIC_AUTH"]
296
+ grant = {"grant_type": "hbSCACustomPassword", "loginId": user}
297
+ password_form = {**grant, "password": password}
298
+ result = self._token(basic, password_form)
299
+ if result.get("access_token") in (None, ""):
300
+ sca_id = _challenge_id(result.get("id_token"))
301
+ route = f"/openScaBroker/1.0/customer/{user_path}/status/{_segment(sca_id)}"
302
+ deadline = self._clock() + self._sca_timeout
303
+ app_notified = False
304
+ while True:
305
+ state = _object(
306
+ self._request("GET", route, authorization=generic_auth, deadline=deadline)
307
+ )
308
+ status = state.get("status")
309
+ if status == "complete":
310
+ device = _object(state.get("resultData") or {}).get("DEVICETOKEN")
311
+ headers = {"DEVICETOKEN": _header_value(device)} if device else None
312
+ result = self._token(basic, password_form, headers=headers, deadline=deadline)
313
+ break
314
+ if status not in PENDING:
315
+ raise ExportError(
316
+ "Login approval declined, expired, or returned an unknown status."
317
+ )
318
+ kind = state.get("scaType")
319
+ if kind == "SMS" and not app_notified:
320
+ code = self._tan(tan, deadline)
321
+ result = self._token(
322
+ basic, {**grant, "otp": code, "scaId": sca_id}, deadline=deadline
323
+ )
324
+ break
325
+ if kind != "APP":
326
+ raise ExportError("Unsupported login approval method.")
327
+ if not app_notified:
328
+ notify("Approve the login in the Hanseatic Bank app.")
329
+ app_notified = True
330
+ self._pause(deadline)
331
+ scheme = result.get("token_type", "Bearer")
332
+ if not isinstance(scheme, str) or scheme.lower() != "bearer":
333
+ raise ExportError("Unexpected bank token type.")
334
+ self._authorization = scheme + " " + _header_value(result.get("access_token"))
335
+ self._login_id = user
336
+
337
+ def accounts(self):
338
+ """Return the account IDs matching the authenticated login."""
339
+ if self._authorization is None:
340
+ raise ExportError("Sign in before discovering accounts.")
341
+ data = self._request(
342
+ "GET",
343
+ ACCOUNTS,
344
+ authorization=self._authorization,
345
+ params={"skipCache": "false"},
346
+ read_retry=True,
347
+ )
348
+ if not isinstance(data, list):
349
+ raise ExportError("Unexpected bank account response.")
350
+ ids = []
351
+ for row in data:
352
+ row = _object(row)
353
+ number = row.get("customerNumber")
354
+ if (str(number) if type(number) is int else number) == self._login_id:
355
+ account = row.get("accountNumber")
356
+ account = str(account) if type(account) is int else account
357
+ _segment(account)
358
+ if account not in ids:
359
+ ids.append(account)
360
+ self._account_ids = tuple(ids)
361
+ if not ids:
362
+ raise ExportError(
363
+ "No matching account found; check your account in the official portal."
364
+ )
365
+ return self._account_ids
366
+
367
+ def _approve_history(self, tan, notify):
368
+ deadline = self._clock() + self._sca_timeout
369
+ auth = self._authorization
370
+ challenge = _object(
371
+ self._request(
372
+ "POST",
373
+ "/scaBroker/1.0/session",
374
+ authorization=auth,
375
+ deadline=deadline,
376
+ json={"initiator": "ton-sca-fe", "lang": "de", "session": auth},
377
+ )
378
+ )
379
+ route = "/scaBroker/1.0/status/" + _segment(challenge.get("scaUniqueId"))
380
+ kind = challenge.get("scaType")
381
+ if kind == "SMS":
382
+ state = _object(
383
+ self._request(
384
+ "PUT",
385
+ route,
386
+ authorization=auth,
387
+ deadline=deadline,
388
+ json={"otp": self._tan(tan, deadline)},
389
+ )
390
+ )
391
+ elif kind == "APP":
392
+ notify("Approve access to older transactions in the Hanseatic Bank app.")
393
+ state = _object(self._request("GET", route, authorization=auth, deadline=deadline))
394
+ else:
395
+ raise ExportError("Unsupported history approval method.")
396
+ while state.get("status") in PENDING:
397
+ self._pause(deadline)
398
+ state = _object(self._request("GET", route, authorization=auth, deadline=deadline))
399
+ if state.get("status") != "complete" or state.get("resultCode") != 200:
400
+ raise ExportError("History approval declined, expired, or returned an unknown status.")
401
+
402
+ def transactions(self, account_id, *, all_history=False, tan, notify):
403
+ """Retrieve pages for a discovered account, with optional history approval."""
404
+ if account_id not in self._account_ids:
405
+ raise ExportError("Select an account returned by account discovery.")
406
+ route = TRANSACTIONS + _segment(account_id)
407
+ pages = []
408
+ seen = set()
409
+ page_number = 1
410
+ approved = False
411
+ for attempt in range(self._max_pages):
412
+ page = _object(
413
+ self._request(
414
+ "GET",
415
+ route,
416
+ authorization=self._authorization,
417
+ read_retry=True,
418
+ params={
419
+ "page": page_number,
420
+ "withReservations": "true",
421
+ "withEnrichments": "true",
422
+ },
423
+ )
424
+ )
425
+ records = page.get("transactions")
426
+ more, gated = page.get("more", False), page.get("moreWithSCA", False)
427
+ if (
428
+ not isinstance(records, list)
429
+ or not all(isinstance(row, dict) for row in records)
430
+ or type(more) is not bool
431
+ or type(gated) is not bool
432
+ ):
433
+ raise ExportError("Unexpected bank transaction response.")
434
+ if records:
435
+ identity = simplejson.dumps(records, use_decimal=True, sort_keys=True)
436
+ if identity in seen:
437
+ raise ExportError("Bank repeated a transaction page; export stopped.")
438
+ seen.add(identity)
439
+ elif more or gated:
440
+ raise ExportError("Bank returned an empty page with more history; export stopped.")
441
+ pages.append(page)
442
+ if more:
443
+ page_number += 1
444
+ elif not gated:
445
+ return TransactionResult(tuple(pages), "complete")
446
+ elif not all_history:
447
+ return TransactionResult(tuple(pages), "limited_by_sca")
448
+ elif approved:
449
+ raise ExportError("Bank still requires history approval; export stopped.")
450
+ elif attempt + 1 < self._max_pages:
451
+ self._approve_history(tan, notify)
452
+ approved = True
453
+ page_number = 1
454
+ pages.clear()
455
+ seen.clear()
456
+ raise ExportError("Transaction page limit reached; no export was written.")
@@ -0,0 +1,140 @@
1
+ """Serialize transaction pages without mutating the bank data."""
2
+
3
+ import csv
4
+ import re
5
+ from datetime import date, time
6
+ from decimal import Decimal
7
+ from io import StringIO
8
+
9
+ import simplejson
10
+
11
+ CSV_COLUMNS = (
12
+ "transaction_id",
13
+ "booking_date",
14
+ "transaction_date",
15
+ "transaction_time",
16
+ "amount",
17
+ "currency",
18
+ "description",
19
+ "recipient_name",
20
+ "status",
21
+ "credit_debit_key",
22
+ "mcc",
23
+ "foreign_amount",
24
+ "transaction_type",
25
+ )
26
+
27
+
28
+ def _classify(row):
29
+ """Derive a human-friendly transaction type from the bank's classification."""
30
+ key = row.get("creditDebitKey") or ""
31
+ if key == "LS-EINZUG":
32
+ return "settlement"
33
+ amount = row.get("amount")
34
+ if amount is not None:
35
+ try:
36
+ numeric = float(amount) if not isinstance(amount, Decimal) else float(amount)
37
+ if numeric > 0:
38
+ return "card_refund"
39
+ if numeric == 0:
40
+ return "pending_authorisation"
41
+ except (ValueError, OverflowError):
42
+ pass
43
+ return "card_transaction"
44
+
45
+
46
+ def export_json(pages):
47
+ """Return UTF-8 bytes containing the unchanged page data in a JSON array."""
48
+ return (
49
+ simplejson.dumps(
50
+ list(pages), use_decimal=True, ensure_ascii=False, allow_nan=False, indent=2
51
+ )
52
+ + "\n"
53
+ ).encode("utf-8")
54
+
55
+
56
+ def _text(value):
57
+ if type(value) is int:
58
+ value = str(value)
59
+ if not isinstance(value, str):
60
+ return ""
61
+ if value.startswith(("\t", "\r", "\n")) or value.lstrip().startswith(("=", "+", "-", "@")):
62
+ return "'" + value
63
+ return value
64
+
65
+
66
+ def _date(value):
67
+ if not isinstance(value, str):
68
+ return ""
69
+ try:
70
+ if match := re.fullmatch(r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})", value):
71
+ day, month, year = map(int, match.groups())
72
+ return date(year, month, day).isoformat()
73
+ if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
74
+ return date.fromisoformat(value).isoformat()
75
+ except ValueError:
76
+ pass
77
+ return ""
78
+
79
+
80
+ def _time(value):
81
+ if isinstance(value, str) and re.fullmatch(
82
+ r"[0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]+)?)?(?:Z|[+-][0-9]{2}:[0-9]{2})?", value
83
+ ):
84
+ try:
85
+ time.fromisoformat(value)
86
+ except ValueError:
87
+ return ""
88
+ return value
89
+ return ""
90
+
91
+
92
+ def _amount(value):
93
+ if value is None:
94
+ return ""
95
+ if isinstance(value, float):
96
+ value = Decimal(str(value))
97
+ if isinstance(value, str) and re.fullmatch(
98
+ r"[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", value
99
+ ):
100
+ value = Decimal(value)
101
+ if type(value) is int:
102
+ return str(value)
103
+ if (
104
+ isinstance(value, Decimal)
105
+ and value.is_finite()
106
+ and abs(value.adjusted()) <= 1000
107
+ and abs(value.as_tuple().exponent) <= 1000
108
+ ):
109
+ return format(value, "f")
110
+ raise ValueError("Invalid transaction amount.")
111
+
112
+
113
+ def export_csv(pages, *, booked_only=False):
114
+ """Return UTF-8 CSV bytes; optionally keep only explicitly booked records."""
115
+ out = StringIO(newline="")
116
+ writer = csv.writer(out)
117
+ writer.writerow(CSV_COLUMNS)
118
+ for page in pages:
119
+ for row in page["transactions"]:
120
+ booked = row.get("booked")
121
+ if booked_only and booked is not True:
122
+ continue
123
+ writer.writerow(
124
+ (
125
+ _text(row.get("transactionId")),
126
+ _date(row.get("date")),
127
+ _date(row.get("transactionDate")),
128
+ _time(row.get("transactionTime")),
129
+ _amount(row.get("amount")),
130
+ _text(row.get("currencyCode")),
131
+ _text(row.get("description")),
132
+ _text(row.get("recipientName")),
133
+ "booked" if booked is True else "pending" if booked is False else "",
134
+ _text(row.get("creditDebitKey")),
135
+ _text(row.get("mcc")),
136
+ _text(row.get("foreignAmount")),
137
+ _classify(row),
138
+ )
139
+ )
140
+ return out.getvalue().encode("utf-8")
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: hanseatic-export
3
+ Version: 0.1.0
4
+ Summary: Unofficial Hanseatic credit card transaction exporter
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/ChristianKuehnel/hanseatic-csv-exporter
7
+ Project-URL: Documentation, https://github.com/ChristianKuehnel/hanseatic-csv-exporter#documentation
8
+ Project-URL: Issues, https://github.com/ChristianKuehnel/hanseatic-csv-exporter/issues
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: requests<3,>=2.32.4
13
+ Requires-Dist: simplejson<4,>=3.19
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=8; extra == "test"
16
+ Requires-Dist: responses>=0.25; extra == "test"
17
+ Provides-Extra: quality
18
+ Requires-Dist: ruff==0.15.0; extra == "quality"
19
+ Dynamic: license-file
20
+
21
+ # Hanseatic Credit Card CSV Exporter
22
+
23
+ **AI-generated, unofficial, and not affiliated with, endorsed by, or supported by Hanseatic Bank.**
24
+
25
+ This project is a workaround for the lack of a built-in CSV export for Hanseatic Bank credit card statements. It is designed to let account holders export their own credit card transactions without parsing statement PDFs.
26
+
27
+ ## Quickstart
28
+
29
+ The exporter was manually tested successfully with one Hanseatic Bank GenialCard account. Automated tests use mocked HTTP and do not contact the bank. The unofficial API may change without notice.
30
+
31
+ Install from source with Python 3.11 or newer. On macOS or Linux:
32
+
33
+ ```sh
34
+ git clone https://github.com/ChristianKuehnel/hanseatic-csv-exporter.git
35
+ cd hanseatic-csv-exporter
36
+ python3 -m venv .venv
37
+ . .venv/bin/activate
38
+ python -m pip install .
39
+ hanseatic-export --help
40
+ hanseatic-export
41
+ ```
42
+
43
+ Enter your login ID and password in the terminal and follow any bank approval prompts. The command writes `transactions.csv` and `transactions.json` in the current directory without replacing existing files. The [CLI guide](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/cli.md) covers Windows setup, selecting formats, supplying credentials, and troubleshooting.
44
+
45
+ Use the [Python library guide](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/python-library.md) to start with a runnable offline example or integrate account discovery and exports into an application.
46
+
47
+ ## Development
48
+
49
+ To run the same checks locally:
50
+
51
+ ```sh
52
+ python -m pip install -e '.[test,quality]'
53
+ python -m ruff format --check .
54
+ python -m ruff check .
55
+ python -m pytest -q
56
+ ```
57
+
58
+ Run `python -m ruff format .` to fix formatting, or `python -m ruff check --fix .` to apply safe lint fixes. The [CI workflow](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/.github/workflows/ci.yml) checks formatting, lints Python, and runs offline tests on pull requests targeting `main`; tests cover Python 3.11–3.14. To enforce the merge gate, once the workflow has run on GitHub, configure a branch ruleset for `main` and add **PR gate** as a required status check. This single check requires formatting, linting, and every test job to pass.
59
+
60
+ Maintainers can follow the [release checklist](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/releasing.md) to rehearse on TestPyPI and publish to PyPI.
61
+
62
+ ## Documentation
63
+
64
+ | File | Purpose |
65
+ |---|---|
66
+ | [Command-line guide](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/cli.md) | Installation, options, recipes, and troubleshooting. |
67
+ | [Python library guide](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/python-library.md) | Offline example, authentication callbacks, and public API reference. |
68
+ | [Transaction CSV format](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/csv-format.md) | Column contract, type, source JSON field, synthetic examples, and spreadsheet safety rules. |
69
+ | [Bank API JSON fields](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/bank-api-fields.md) | Observed fields in the enriched transaction response and their availability. |
70
+ | [Synthetic JSON example](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/tests/fixtures/example-pages.json) | Example response pages for trying the serializers without signing in. |
71
+ | [Protocol notes](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/docs/protocol.md) | Observed HTTP routes and request/response patterns from SyncusGnampfus, with uncertainties. |
72
+ | [Implementation brief](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/doc/hanseatic-opencode-prompt.md) | Original design specification for the exporter. |
73
+ | [Changelog](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/CHANGELOG.md) | Release notes. |
74
+
75
+ ## Acknowledgments
76
+
77
+ Thanks to the maintainers and contributors of these projects for figuring out Hanseatic Bank's unofficial protocol and sharing their work:
78
+
79
+ - [SyncusGnampfus](https://github.com/gnampf1/SyncusGnampfus), a Hibiscus plugin and our primary reference for authentication and transaction retrieval. Its README reports testing with AWA7, not GenialCard.
80
+ - [moneymoney-hanseaticbank](https://github.com/davyd15/moneymoney-hanseaticbank), David Lemke's MoneyMoney extension and a secondary reference for the API host and approval flows.
81
+
82
+ ## Privacy
83
+
84
+ **You are responsible for managing and protecting your own banking credentials and exports.** The CLI prompts for credentials by default; applications using the library provide their own callbacks. The exporter does not save credentials for later use, but both output formats can contain sensitive financial and personal information.
85
+
86
+ Never commit or share credentials, TANs, session tokens, logs containing account data, or financial exports. Use only synthetic data in tests, examples, and issue reports.
87
+
88
+ ## License
89
+
90
+ [Apache License, Version 2.0](https://github.com/ChristianKuehnel/hanseatic-csv-exporter/blob/main/LICENSE).
@@ -0,0 +1,11 @@
1
+ hanseatic_export/__init__.py,sha256=1oAtHs42m06GdC9VhawDNrNEbEF__A1KmS3cPQptBng,287
2
+ hanseatic_export/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
3
+ hanseatic_export/cli.py,sha256=PA9enaWWJJHy1STifybsdznudWuxUfA9AZQMVLVgHRU,7361
4
+ hanseatic_export/client.py,sha256=eQuk-urrbWQ4fd5N6pgkedNV6XSSyjhMl1CjYPUesb4,17523
5
+ hanseatic_export/export.py,sha256=A9FgU_pjLL6Ns3eZFyhtqB4nsxFYiHQHqAJYT9lCiQ8,4155
6
+ hanseatic_export-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
7
+ hanseatic_export-0.1.0.dist-info/METADATA,sha256=Uri1IeU2ESXzrJjd7EDr1kkoOhq71dTL_MvKuyx9wF0,5900
8
+ hanseatic_export-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ hanseatic_export-0.1.0.dist-info/entry_points.txt,sha256=49CsmLx2io0lGdfBtmMA94IDEnfwTnEL_Qbeo0ERInw,63
10
+ hanseatic_export-0.1.0.dist-info/top_level.txt,sha256=7uI0iJTcJ9Y7Ti3hDjff6vuSjFg59I87yzKi_TiUy28,17
11
+ hanseatic_export-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hanseatic-export = hanseatic_export.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ hanseatic_export