statement-fetch 0.5.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.
- statement_fetch/__init__.py +126 -0
- statement_fetch/_contracts.py +532 -0
- statement_fetch/_playwright.py +518 -0
- statement_fetch/_registry.py +132 -0
- statement_fetch/_runner.py +538 -0
- statement_fetch/_staging.py +409 -0
- statement_fetch/_validators.py +242 -0
- statement_fetch/api.py +133 -0
- statement_fetch/cli.py +686 -0
- statement_fetch/demo.py +111 -0
- statement_fetch/providers/__init__.py +1 -0
- statement_fetch/providers/example_bank.py +152 -0
- statement_fetch/py.typed +0 -0
- statement_fetch/sinks/__init__.py +1 -0
- statement_fetch/sinks/directory.py +260 -0
- statement_fetch-0.5.0.dist-info/METADATA +95 -0
- statement_fetch-0.5.0.dist-info/RECORD +20 -0
- statement_fetch-0.5.0.dist-info/WHEEL +4 -0
- statement_fetch-0.5.0.dist-info/entry_points.txt +8 -0
- statement_fetch-0.5.0.dist-info/licenses/LICENSE +21 -0
statement_fetch/demo.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Zero-dependency loopback demo bank portal for testing and demonstrating `example-bank`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import contextlib
|
|
5
|
+
import threading
|
|
6
|
+
from http import HTTPStatus
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
8
|
+
|
|
9
|
+
DEMO_CSV = b"Date,Description,Amount,Currency,Balance\n2026-11-30,PAYROLL,1000.00,USD,2500.00\n"
|
|
10
|
+
DEMO_PDF = b"%PDF-1.4\n% synthetic example-bank statement\n%%EOF\n"
|
|
11
|
+
|
|
12
|
+
_LOGIN_HTML = """<!doctype html>
|
|
13
|
+
<html><head><title>Example Bank Login</title></head>
|
|
14
|
+
<body>
|
|
15
|
+
<h1>Example Bank (Demo Portal)</h1>
|
|
16
|
+
<p>Click below to sign in (no credentials required in demo mode).</p>
|
|
17
|
+
<form method="GET" action="/dashboard">
|
|
18
|
+
<button type="submit" data-testid="login-button">Sign in</button>
|
|
19
|
+
</form>
|
|
20
|
+
</body></html>
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
_DASHBOARD_HTML = """<!doctype html>
|
|
24
|
+
<html><head><title>Example Bank Dashboard</title></head>
|
|
25
|
+
<body>
|
|
26
|
+
<div data-testid="dashboard-ready">Signed in to Example Bank</div>
|
|
27
|
+
<a href="/download/checking.csv" download="checking-txns.csv" data-testid="download-csv-checking">Download Checking CSV</a>
|
|
28
|
+
<a href="/download/checking.pdf" download="checking-stmt.pdf" data-testid="download-pdf-checking">Download Checking PDF</a>
|
|
29
|
+
<a href="/download/savings.csv" download="savings-txns.csv" data-testid="download-csv-savings">Download Savings CSV</a>
|
|
30
|
+
<a href="/download/savings.pdf" download="savings-stmt.pdf" data-testid="download-pdf-savings">Download Savings PDF</a>
|
|
31
|
+
<form method="GET" action="/logout">
|
|
32
|
+
<button type="submit" data-testid="logout-button">Log out</button>
|
|
33
|
+
</form>
|
|
34
|
+
</body></html>
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
_LOGOUT_HTML = """<!doctype html>
|
|
38
|
+
<html><head><title>Signed Out</title></head>
|
|
39
|
+
<body><div data-testid="logged-out">Signed out.</div></body></html>
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _DemoHandler(BaseHTTPRequestHandler):
|
|
44
|
+
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
def _send(self, body: bytes, content_type: str, *, filename: str = "") -> None:
|
|
48
|
+
self.send_response(HTTPStatus.OK)
|
|
49
|
+
self.send_header("Content-Type", content_type)
|
|
50
|
+
self.send_header("Content-Length", str(len(body)))
|
|
51
|
+
if filename:
|
|
52
|
+
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
|
|
53
|
+
self.end_headers()
|
|
54
|
+
self.wfile.write(body)
|
|
55
|
+
|
|
56
|
+
def do_GET(self) -> None: # noqa: N802
|
|
57
|
+
path = self.path.split("?", 1)[0]
|
|
58
|
+
if path in ("/", "/login"):
|
|
59
|
+
self._send(_LOGIN_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
60
|
+
elif path == "/dashboard":
|
|
61
|
+
self._send(_DASHBOARD_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
62
|
+
elif path == "/logout":
|
|
63
|
+
self._send(_LOGOUT_HTML.encode("utf-8"), "text/html; charset=utf-8")
|
|
64
|
+
elif path.startswith("/download/") and path.endswith(".csv"):
|
|
65
|
+
self._send(DEMO_CSV, "text/csv; charset=utf-8", filename=path.rsplit("/", 1)[-1])
|
|
66
|
+
elif path.startswith("/download/") and path.endswith(".pdf"):
|
|
67
|
+
self._send(DEMO_PDF, "application/pdf", filename=path.rsplit("/", 1)[-1])
|
|
68
|
+
else:
|
|
69
|
+
self.send_error(HTTPStatus.NOT_FOUND)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@contextlib.contextmanager
|
|
73
|
+
def run_demo_server(host: str = "127.0.0.1", port: int = 0):
|
|
74
|
+
"""Context manager running the loopback Example Bank demo portal on `http://127.0.0.1:<port>`."""
|
|
75
|
+
srv = ThreadingHTTPServer((host, port), _DemoHandler)
|
|
76
|
+
actual_port = srv.server_address[1]
|
|
77
|
+
thread = threading.Thread(target=srv.serve_forever, daemon=True)
|
|
78
|
+
thread.start()
|
|
79
|
+
try:
|
|
80
|
+
yield f"http://{host}:{actual_port}"
|
|
81
|
+
finally:
|
|
82
|
+
srv.shutdown()
|
|
83
|
+
srv.server_close()
|
|
84
|
+
thread.join(timeout=2.0)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main(argv: list[str] | None = None) -> int:
|
|
88
|
+
"""Run the loopback Example Bank demo portal until interrupted."""
|
|
89
|
+
import argparse
|
|
90
|
+
|
|
91
|
+
parser = argparse.ArgumentParser(
|
|
92
|
+
prog="python -m statement_fetch.demo",
|
|
93
|
+
description="Run the local loopback Example Bank demo portal for testing.",
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument("--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1).")
|
|
96
|
+
parser.add_argument("--port", type=int, default=8765, help="TCP port (default: 8765; 0 for ephemeral).")
|
|
97
|
+
args = parser.parse_args(argv)
|
|
98
|
+
srv = ThreadingHTTPServer((args.host, args.port), _DemoHandler)
|
|
99
|
+
actual_port = srv.server_address[1]
|
|
100
|
+
print(f"Example Bank demo portal listening on http://{args.host}:{actual_port} (Ctrl-C to stop)", flush=True)
|
|
101
|
+
try:
|
|
102
|
+
srv.serve_forever()
|
|
103
|
+
except KeyboardInterrupt:
|
|
104
|
+
pass
|
|
105
|
+
finally:
|
|
106
|
+
srv.server_close()
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Provider plugins for statement-fetch."""
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Public example provider template for `statement-fetch` (`example-bank`).
|
|
2
|
+
|
|
3
|
+
Demonstrates the complete Zero-LLM-in-Bank async `Provider` contract importing
|
|
4
|
+
exclusively from `statement_fetch.api`:
|
|
5
|
+
- Declarative `ProviderSpec`, `ArtifactSpec` (with structural validators), and `OptionSpec`
|
|
6
|
+
- Optional loopback `base_url` override so `example-bank` runs end-to-end against `statement_fetch.demo`
|
|
7
|
+
- Human login detection (`is_logged_in`)
|
|
8
|
+
- Deterministic download (`page.download(Click(...))`) + manifest-first staging (`Stage.add`)
|
|
9
|
+
- Cooperative `--skip-existing` support when re-running against an existing `--output-dir`
|
|
10
|
+
- Guaranteed session logoff (`logoff`)
|
|
11
|
+
|
|
12
|
+
Real institution providers live in separate packages registered via the
|
|
13
|
+
`statement_fetch.providers` entry-point group.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
from ..api import (
|
|
20
|
+
AccountsRequest,
|
|
21
|
+
ArtifactSpec,
|
|
22
|
+
Click,
|
|
23
|
+
FetchRequest,
|
|
24
|
+
OptionSpec,
|
|
25
|
+
Page,
|
|
26
|
+
ProviderSpec,
|
|
27
|
+
Stage,
|
|
28
|
+
validate_csv,
|
|
29
|
+
validate_pdf,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _host_of(url: str, *, loopback_only: bool = False) -> str:
|
|
37
|
+
if not url or "\\" in url or any(ord(c) < 32 for c in url):
|
|
38
|
+
raise ValueError(f"Invalid base_url: {url!r}")
|
|
39
|
+
parts = urlsplit(url)
|
|
40
|
+
host = (parts.hostname or "").lower().rstrip(".")
|
|
41
|
+
if not host or parts.username is not None or parts.password is not None or parts.query or parts.fragment:
|
|
42
|
+
raise ValueError(f"Invalid base_url: {url!r}")
|
|
43
|
+
if loopback_only and host not in _LOOPBACK_HOSTS:
|
|
44
|
+
raise ValueError(f"base_url override must target loopback (127.0.0.1/localhost/::1), got {url!r}")
|
|
45
|
+
if parts.scheme == "http" and host not in _LOOPBACK_HOSTS:
|
|
46
|
+
raise ValueError(f"Insecure non-loopback base_url: {url!r}")
|
|
47
|
+
if parts.scheme not in ("https", "http"):
|
|
48
|
+
raise ValueError(f"Unsupported base_url scheme: {url!r}")
|
|
49
|
+
return host
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ExampleBankProvider:
|
|
53
|
+
"""Reference async provider template targeting a synthetic local or demo portal."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, *, base_url: str = "https://demo.example-bank.invalid") -> None:
|
|
56
|
+
self.base_url = base_url.rstrip("/")
|
|
57
|
+
self.spec = ProviderSpec(
|
|
58
|
+
id="example-bank",
|
|
59
|
+
display_name="Example Bank (Template)",
|
|
60
|
+
login_url=f"{self.base_url}/login",
|
|
61
|
+
allowed_hosts=(_host_of(self.base_url),),
|
|
62
|
+
artifacts=(
|
|
63
|
+
ArtifactSpec(id="csv", default=True, description="Monthly transactions CSV", validator=validate_csv),
|
|
64
|
+
ArtifactSpec(id="pdf", default=True, description="Monthly statement PDF", validator=validate_pdf),
|
|
65
|
+
),
|
|
66
|
+
options=(
|
|
67
|
+
OptionSpec(name="account", type="str", default="checking", choices=("checking", "savings"), help="Account slug"),
|
|
68
|
+
OptionSpec(name="base_url", type="str", default="", help="Override portal base URL (e.g. local demo server)"),
|
|
69
|
+
),
|
|
70
|
+
supports_accounts=False,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def resolve_target(self, req: FetchRequest | AccountsRequest) -> tuple[str, tuple[str, ...]]:
|
|
74
|
+
raw = str(req.options.get("base_url") or "").strip().rstrip("/")
|
|
75
|
+
if raw:
|
|
76
|
+
return f"{raw}/login", (_host_of(raw, loopback_only=True),)
|
|
77
|
+
return self.spec.login_url, self.spec.allowed_hosts
|
|
78
|
+
|
|
79
|
+
async def is_logged_in(self, page: Page) -> bool:
|
|
80
|
+
cur = await page.url()
|
|
81
|
+
if "/login" in cur:
|
|
82
|
+
return False
|
|
83
|
+
return (await page.locator('[data-testid="dashboard-ready"]').count()) > 0
|
|
84
|
+
|
|
85
|
+
async def fetch(self, page: Page, req: FetchRequest, stage: Stage) -> None:
|
|
86
|
+
selected = req.artifacts or self.spec.default_artifact_ids()
|
|
87
|
+
account = str(req.options.get("account") or "checking").strip().lower()
|
|
88
|
+
period = f"{req.period_start.isoformat()}_to_{req.period_end.isoformat()}"
|
|
89
|
+
|
|
90
|
+
if "csv" in selected:
|
|
91
|
+
csv_name = f"example-bank--{account}-transactions_{period}.csv"
|
|
92
|
+
reused_csv = (
|
|
93
|
+
stage.reuse_existing(
|
|
94
|
+
csv_name,
|
|
95
|
+
artifact_id="csv",
|
|
96
|
+
kind=f"{account}-transactions",
|
|
97
|
+
period=period,
|
|
98
|
+
currency="USD",
|
|
99
|
+
meta={"account": account},
|
|
100
|
+
)
|
|
101
|
+
if req.skip_existing
|
|
102
|
+
else None
|
|
103
|
+
)
|
|
104
|
+
if reused_csv is None:
|
|
105
|
+
dl_csv = await page.download(
|
|
106
|
+
Click(f'[data-testid="download-csv-{account}"]'),
|
|
107
|
+
suffixes=(".csv",),
|
|
108
|
+
timeout_s=20.0,
|
|
109
|
+
)
|
|
110
|
+
stage.add(
|
|
111
|
+
dl_csv,
|
|
112
|
+
artifact_id="csv",
|
|
113
|
+
kind=f"{account}-transactions",
|
|
114
|
+
period=period,
|
|
115
|
+
filename=csv_name,
|
|
116
|
+
currency="USD",
|
|
117
|
+
meta={"account": account},
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
if "pdf" in selected:
|
|
121
|
+
pdf_name = f"example-bank--{account}-statement_{req.period_end:%Y-%m}.pdf"
|
|
122
|
+
reused_pdf = (
|
|
123
|
+
stage.reuse_existing(
|
|
124
|
+
pdf_name,
|
|
125
|
+
artifact_id="pdf",
|
|
126
|
+
kind=f"{account}-statement",
|
|
127
|
+
period=f"{req.period_end:%Y-%m}",
|
|
128
|
+
meta={"account": account},
|
|
129
|
+
)
|
|
130
|
+
if req.skip_existing
|
|
131
|
+
else None
|
|
132
|
+
)
|
|
133
|
+
if reused_pdf is None:
|
|
134
|
+
dl_pdf = await page.download(
|
|
135
|
+
Click(f'[data-testid="download-pdf-{account}"]'),
|
|
136
|
+
suffixes=(".pdf",),
|
|
137
|
+
timeout_s=20.0,
|
|
138
|
+
)
|
|
139
|
+
stage.add(
|
|
140
|
+
dl_pdf,
|
|
141
|
+
artifact_id="pdf",
|
|
142
|
+
kind=f"{account}-statement",
|
|
143
|
+
period=f"{req.period_end:%Y-%m}",
|
|
144
|
+
filename=pdf_name,
|
|
145
|
+
meta={"account": account},
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
async def logoff(self, page: Page) -> None:
|
|
149
|
+
btn = page.locator('[data-testid="logout-button"]').first()
|
|
150
|
+
if await btn.count() > 0:
|
|
151
|
+
await btn.click(timeout_ms=5_000)
|
|
152
|
+
await page.sleep(0.1)
|
statement_fetch/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Built-in sinks for statement-fetch."""
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Public filesystem (`dir`) sink: atomic `0o600` SHA-256 verified export with immutable per-run manifests."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ..api import (
|
|
16
|
+
ManifestArtifact,
|
|
17
|
+
SinkResult,
|
|
18
|
+
iter_verified_manifest_artifacts,
|
|
19
|
+
open_private_exclusive,
|
|
20
|
+
publish_exclusive_file,
|
|
21
|
+
sanitize_filename,
|
|
22
|
+
sha256_file,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _slug_provider(raw: object) -> str:
|
|
27
|
+
slug = re.sub(r"[^a-z0-9-]+", "-", str(raw or "").strip().lower()).strip("-")
|
|
28
|
+
return slug[:64] or "run"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DirectorySink:
|
|
32
|
+
"""Verify staged manifest artifacts, publish atomically at `0o600`, and record an immutable per-run manifest."""
|
|
33
|
+
|
|
34
|
+
id = "dir"
|
|
35
|
+
|
|
36
|
+
def __init__(self, dest_dir: Path | None = None) -> None:
|
|
37
|
+
self.dest_dir = Path(dest_dir).resolve() if dest_dir is not None else None
|
|
38
|
+
|
|
39
|
+
def _resolve_dest(self, config: Mapping[str, str] | None) -> Path:
|
|
40
|
+
raw = str((config or {}).get("dir") or "").strip()
|
|
41
|
+
if raw:
|
|
42
|
+
return Path(raw).expanduser().resolve()
|
|
43
|
+
if self.dest_dir is not None:
|
|
44
|
+
return self.dest_dir
|
|
45
|
+
raise ValueError("DirectorySink ('dir') requires --sink-dir or config['dir'].")
|
|
46
|
+
|
|
47
|
+
def validate_config(self, config: Mapping[str, str] | None = None) -> None:
|
|
48
|
+
dest = self._resolve_dest(config)
|
|
49
|
+
if dest.exists() and not dest.is_dir():
|
|
50
|
+
raise ValueError(f"DirectorySink destination is not a directory: {dest}")
|
|
51
|
+
|
|
52
|
+
def deliver(
|
|
53
|
+
self,
|
|
54
|
+
manifest_path: Path,
|
|
55
|
+
*,
|
|
56
|
+
config: Mapping[str, str] | None = None,
|
|
57
|
+
dry_run: bool = False,
|
|
58
|
+
) -> SinkResult:
|
|
59
|
+
dest_dir = self._resolve_dest(config)
|
|
60
|
+
if dest_dir.exists() and not dest_dir.is_dir():
|
|
61
|
+
raise ValueError(f"DirectorySink destination is not a directory: {dest_dir}")
|
|
62
|
+
|
|
63
|
+
# Phase 1: pre-validate ALL manifest entries before publishing any file (all-or-nothing integrity).
|
|
64
|
+
_resolved_manifest, manifest, verified_items, errors = iter_verified_manifest_artifacts(
|
|
65
|
+
manifest_path,
|
|
66
|
+
verify_sha256=dry_run,
|
|
67
|
+
)
|
|
68
|
+
failed: list[dict[str, str]] = list(errors)
|
|
69
|
+
planned: list[tuple[ManifestArtifact, str, Path]] = []
|
|
70
|
+
seen_names: set[str] = set()
|
|
71
|
+
|
|
72
|
+
for item in verified_items:
|
|
73
|
+
try:
|
|
74
|
+
safe_name = sanitize_filename(item.name)
|
|
75
|
+
except ValueError as exc:
|
|
76
|
+
failed.append({"name": item.name, "error": str(exc)})
|
|
77
|
+
continue
|
|
78
|
+
if safe_name in seen_names:
|
|
79
|
+
failed.append({"name": safe_name, "error": "duplicate destination filename in manifest"})
|
|
80
|
+
continue
|
|
81
|
+
seen_names.add(safe_name)
|
|
82
|
+
|
|
83
|
+
raw_target = dest_dir / safe_name
|
|
84
|
+
if raw_target.is_symlink():
|
|
85
|
+
failed.append({"name": safe_name, "error": "destination symlink not allowed"})
|
|
86
|
+
continue
|
|
87
|
+
target = raw_target.resolve()
|
|
88
|
+
if target.parent != dest_dir:
|
|
89
|
+
failed.append({"name": safe_name, "error": "unsafe destination filename"})
|
|
90
|
+
continue
|
|
91
|
+
if target.exists() and not target.is_file():
|
|
92
|
+
failed.append({"name": safe_name, "error": "destination path exists and is not a regular file"})
|
|
93
|
+
continue
|
|
94
|
+
planned.append((item, safe_name, target))
|
|
95
|
+
|
|
96
|
+
if failed:
|
|
97
|
+
return SinkResult(
|
|
98
|
+
sink_id=self.id,
|
|
99
|
+
ok=False,
|
|
100
|
+
status="failed",
|
|
101
|
+
delivered=(),
|
|
102
|
+
failed=tuple(failed),
|
|
103
|
+
skipped=(),
|
|
104
|
+
details={"dest_dir": str(dest_dir)},
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
delivered: list[str] = []
|
|
108
|
+
skipped: list[str] = []
|
|
109
|
+
exported_artifacts: list[dict[str, Any]] = []
|
|
110
|
+
|
|
111
|
+
if dry_run:
|
|
112
|
+
for item, safe_name, target in planned:
|
|
113
|
+
if target.exists():
|
|
114
|
+
existing_sha = sha256_file(target)
|
|
115
|
+
if hmac.compare_digest(existing_sha, item.sha256):
|
|
116
|
+
skipped.append(safe_name)
|
|
117
|
+
continue
|
|
118
|
+
failed.append({"name": safe_name, "error": "destination file exists with different bytes"})
|
|
119
|
+
continue
|
|
120
|
+
delivered.append(safe_name)
|
|
121
|
+
ok = not failed
|
|
122
|
+
return SinkResult(
|
|
123
|
+
sink_id=self.id,
|
|
124
|
+
ok=ok,
|
|
125
|
+
status="dry_run" if ok else "failed",
|
|
126
|
+
delivered=tuple(delivered),
|
|
127
|
+
failed=tuple(failed),
|
|
128
|
+
skipped=tuple(skipped),
|
|
129
|
+
details={"dest_dir": str(dest_dir)},
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
if not planned:
|
|
133
|
+
return SinkResult(
|
|
134
|
+
sink_id=self.id,
|
|
135
|
+
ok=True,
|
|
136
|
+
status="empty",
|
|
137
|
+
delivered=(),
|
|
138
|
+
failed=(),
|
|
139
|
+
skipped=(),
|
|
140
|
+
details={"dest_dir": str(dest_dir)},
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
dest_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
144
|
+
|
|
145
|
+
# Phase 2a: stream + SHA-256-verify ALL planned items into exclusive 0o600 temp files and check
|
|
146
|
+
# destination collisions before publishing any file (all-or-nothing integrity).
|
|
147
|
+
staged_temps: list[tuple[ManifestArtifact, str, Path, Path, str]] = []
|
|
148
|
+
try:
|
|
149
|
+
for item, safe_name, target in planned:
|
|
150
|
+
tmp = dest_dir / f".part-{os.getpid()}-{secrets.token_hex(6)}-{safe_name}"
|
|
151
|
+
h = hashlib.sha256()
|
|
152
|
+
try:
|
|
153
|
+
with item.path.open("rb") as rf, open_private_exclusive(tmp) as wf:
|
|
154
|
+
while True:
|
|
155
|
+
chunk = rf.read(65536)
|
|
156
|
+
if not chunk:
|
|
157
|
+
break
|
|
158
|
+
h.update(chunk)
|
|
159
|
+
wf.write(chunk)
|
|
160
|
+
except BaseException:
|
|
161
|
+
tmp.unlink(missing_ok=True)
|
|
162
|
+
raise
|
|
163
|
+
actual_sha = h.hexdigest()
|
|
164
|
+
if not hmac.compare_digest(actual_sha, item.sha256):
|
|
165
|
+
tmp.unlink(missing_ok=True)
|
|
166
|
+
failed.append({"name": safe_name, "error": "sha256 mismatch"})
|
|
167
|
+
continue
|
|
168
|
+
if target.exists():
|
|
169
|
+
if target.is_symlink() or not target.is_file():
|
|
170
|
+
tmp.unlink(missing_ok=True)
|
|
171
|
+
failed.append({"name": safe_name, "error": "destination path exists and is not a regular file"})
|
|
172
|
+
continue
|
|
173
|
+
existing_sha = sha256_file(target)
|
|
174
|
+
if not hmac.compare_digest(existing_sha, actual_sha):
|
|
175
|
+
tmp.unlink(missing_ok=True)
|
|
176
|
+
failed.append({"name": safe_name, "error": "destination file exists with different bytes"})
|
|
177
|
+
continue
|
|
178
|
+
staged_temps.append((item, safe_name, target, tmp, actual_sha))
|
|
179
|
+
|
|
180
|
+
if failed:
|
|
181
|
+
for _item, _name, _target, tmp, _sha in staged_temps:
|
|
182
|
+
tmp.unlink(missing_ok=True)
|
|
183
|
+
return SinkResult(
|
|
184
|
+
sink_id=self.id,
|
|
185
|
+
ok=False,
|
|
186
|
+
status="failed",
|
|
187
|
+
delivered=(),
|
|
188
|
+
failed=tuple(failed),
|
|
189
|
+
skipped=(),
|
|
190
|
+
details={"dest_dir": str(dest_dir)},
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# Phase 2b: publish all verified temp files atomically.
|
|
194
|
+
for item, safe_name, target, tmp, actual_sha in staged_temps:
|
|
195
|
+
try:
|
|
196
|
+
publish_exclusive_file(tmp, target)
|
|
197
|
+
except FileExistsError:
|
|
198
|
+
tmp.unlink(missing_ok=True)
|
|
199
|
+
if target.is_symlink() or not target.is_file():
|
|
200
|
+
failed.append({"name": safe_name, "error": "destination path exists and is not a regular file"})
|
|
201
|
+
continue
|
|
202
|
+
existing_sha = sha256_file(target)
|
|
203
|
+
if hmac.compare_digest(existing_sha, actual_sha):
|
|
204
|
+
skipped.append(safe_name)
|
|
205
|
+
exported_artifacts.append({**item.entry, "name": safe_name, "path": safe_name})
|
|
206
|
+
continue
|
|
207
|
+
failed.append({"name": safe_name, "error": "destination file exists with different bytes"})
|
|
208
|
+
continue
|
|
209
|
+
delivered.append(safe_name)
|
|
210
|
+
exported_artifacts.append({**item.entry, "name": safe_name, "path": safe_name})
|
|
211
|
+
except BaseException:
|
|
212
|
+
for _item, _name, _target, tmp, _sha in staged_temps:
|
|
213
|
+
tmp.unlink(missing_ok=True)
|
|
214
|
+
raise
|
|
215
|
+
|
|
216
|
+
written_manifest: Path | None = None
|
|
217
|
+
if not failed and exported_artifacts:
|
|
218
|
+
provider_slug = _slug_provider(manifest.get("provider"))
|
|
219
|
+
run_stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
220
|
+
for _attempt in range(16):
|
|
221
|
+
run_id = f"{run_stamp}-{secrets.token_hex(4)}"
|
|
222
|
+
candidate = dest_dir / f"manifest-{run_id}--{provider_slug}.json"
|
|
223
|
+
out_payload = {
|
|
224
|
+
**manifest,
|
|
225
|
+
"run_id": run_id,
|
|
226
|
+
"delivered_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
227
|
+
"artifacts": exported_artifacts,
|
|
228
|
+
}
|
|
229
|
+
out_payload.pop("stage_dir", None)
|
|
230
|
+
encoded = (json.dumps(out_payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
|
|
231
|
+
tmp_manifest = dest_dir / f".part-{os.getpid()}-{secrets.token_hex(6)}-{candidate.name}"
|
|
232
|
+
try:
|
|
233
|
+
with open_private_exclusive(tmp_manifest) as wf:
|
|
234
|
+
wf.write(encoded)
|
|
235
|
+
publish_exclusive_file(tmp_manifest, candidate)
|
|
236
|
+
written_manifest = candidate
|
|
237
|
+
break
|
|
238
|
+
except FileExistsError:
|
|
239
|
+
tmp_manifest.unlink(missing_ok=True)
|
|
240
|
+
continue
|
|
241
|
+
except BaseException:
|
|
242
|
+
tmp_manifest.unlink(missing_ok=True)
|
|
243
|
+
raise
|
|
244
|
+
else:
|
|
245
|
+
raise RuntimeError("Unable to allocate unique manifest filename in destination directory.")
|
|
246
|
+
|
|
247
|
+
ok = not failed
|
|
248
|
+
status = "delivered" if ok else "failed"
|
|
249
|
+
details: dict[str, Any] = {"dest_dir": str(dest_dir)}
|
|
250
|
+
if written_manifest is not None:
|
|
251
|
+
details["manifest_path"] = str(written_manifest)
|
|
252
|
+
return SinkResult(
|
|
253
|
+
sink_id=self.id,
|
|
254
|
+
ok=ok,
|
|
255
|
+
status=status,
|
|
256
|
+
delivered=tuple(delivered),
|
|
257
|
+
failed=tuple(failed),
|
|
258
|
+
skipped=tuple(skipped),
|
|
259
|
+
details=details,
|
|
260
|
+
)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: statement-fetch
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Zero-LLM-in-Bank async financial statement fetcher, validator, and pluggable sink runner.
|
|
5
|
+
Project-URL: Homepage, https://github.com/benjamin-di/statement-fetch-oss
|
|
6
|
+
Project-URL: Repository, https://github.com/benjamin-di/statement-fetch-oss
|
|
7
|
+
Author: benjamin-di
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Provides-Extra: playwright
|
|
19
|
+
Requires-Dist: playwright<2,>=1.52; extra == 'playwright'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# statement-fetch
|
|
23
|
+
|
|
24
|
+
Zero-LLM-in-Bank async financial statement fetcher, structural validator, and pluggable sink runner.
|
|
25
|
+
|
|
26
|
+
## Security Model ("Zero-LLM-in-Bank")
|
|
27
|
+
|
|
28
|
+
1. **Human sign-in:** A real Chromium browser opens the institution's login URL. The human completes authentication and 2FA; no credentials or LLM tokens touch the bank session.
|
|
29
|
+
2. **Host confinement:** Top-level navigations, HTTP 3xx redirects (single/multi-hop and POST), `target="_blank"` popups, and in-page `fetch_bytes()` calls are confined to the provider's declared `allowed_hosts` via Chromium CDP `Fetch.enable` and context routing.
|
|
30
|
+
3. **Deterministic fetch & atomic staging:** After `is_logged_in()` succeeds, deterministic provider code downloads statements into a per-run `0o700` staging directory, validates every artifact using its declared validator (defaulting to non-empty; built-in validators cover PDF, CSV, JSON, and bounded ZIP), writes `0o600` artifacts with SHA-256 digests, and produces a portable `manifest.json`.
|
|
31
|
+
4. **Guaranteed logoff & pluggable sinks:** `logoff()` and browser teardown run in `finally:` even on error or Ctrl-C. Sinks (`statement_fetch.sinks`) verify every manifest entry and SHA-256 before delivering.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
Requires Python 3.11+:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install "statement-fetch[playwright]"
|
|
39
|
+
playwright install chromium
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quickstart (Demo Portal, From a Clone)
|
|
43
|
+
|
|
44
|
+
Install Chromium into the project environment:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
uv run --extra playwright playwright install chromium
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
In one terminal, start the bundled zero-dependency loopback demo bank:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
uv run python -m statement_fetch.demo --port 8765
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
In another terminal, fetch statements and export them to a local directory with an immutable receipt manifest:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
uv run --extra playwright statement-fetch fetch example-bank \
|
|
60
|
+
--opt base_url=http://127.0.0.1:8765 \
|
|
61
|
+
--upload --sink dir --sink-dir ./exported
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Verify a staged or exported manifest offline:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
uv run statement-fetch upload ./exported/manifest-*.json --local-only --json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Plugin API (`API_VERSION = 1`)
|
|
71
|
+
|
|
72
|
+
Third-party providers and sinks import from `statement_fetch.api` (or top-level `statement_fetch`) and register via Python entry points:
|
|
73
|
+
|
|
74
|
+
```toml
|
|
75
|
+
[project.entry-points."statement_fetch.providers"]
|
|
76
|
+
my-bank = "my_pkg.provider:MyBankProvider"
|
|
77
|
+
|
|
78
|
+
[project.entry-points."statement_fetch.sinks"]
|
|
79
|
+
my-sink = "my_pkg.sink:MySink"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- Reference provider: `src/statement_fetch/providers/example_bank.py`
|
|
83
|
+
- Reference sink: `src/statement_fetch/sinks/directory.py`
|
|
84
|
+
- Versioning: the entry-point group names (`statement_fetch.providers`, `statement_fetch.sinks`) define the `API_VERSION = 1` compatibility boundary.
|
|
85
|
+
|
|
86
|
+
## CLI Exit Codes & Manifest Schema
|
|
87
|
+
|
|
88
|
+
- **Exit codes:** `0` (`EXIT_OK`, ok/empty), `1` (`EXIT_ERROR`), `2` (`EXIT_USAGE`), `3` (`EXIT_LOGIN_TIMEOUT`), `4` (`EXIT_PARTIAL`), `130` (interrupted / Ctrl-C).
|
|
89
|
+
- **`manifest.json` (`schema_version = 1`):** `schema_version`, `api_version`, `tool_version`, `created_at`, `provider`, `period_start`, `period_end`, `artifacts[]` (`artifact_id`, `name`, `path` relative to manifest dir, `sha256`, `bytes`, `provider`, `kind`, `period`, `valid`, optional `currency`/`error`/`observed_start`/`observed_end`/`meta`), `skipped[]`, `errors[]`, `timings_s`.
|
|
90
|
+
|
|
91
|
+
## Development Checks
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
make check
|
|
95
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
statement_fetch/__init__.py,sha256=q-hlgF_6Y5XN2_YldDINjD-mCbfCEA5-rt_P6LXDz6w,2684
|
|
2
|
+
statement_fetch/_contracts.py,sha256=jckfHHzni1YtxtuCaD9kYdtfRAixKYw-2UJO_Y_tMLc,18459
|
|
3
|
+
statement_fetch/_playwright.py,sha256=JMo2bWYwG2cII0w0ZGFEobygXrz6AgvMnF-xQvOczhE,20657
|
|
4
|
+
statement_fetch/_registry.py,sha256=M2y89xvWulFouaTeC5EgbH_URchiiHjGNYP8DxXiD0Y,5826
|
|
5
|
+
statement_fetch/_runner.py,sha256=HwyppP3cuibWKFoS5U-iizxno1jR4mT3bmPyUWSeac0,21854
|
|
6
|
+
statement_fetch/_staging.py,sha256=pvS7Q3aeg9PgCGOX65SPn5dAXJ88F01Zfb8dXCQJte0,15109
|
|
7
|
+
statement_fetch/_validators.py,sha256=OGL6kbavRKnNPibPatDAbS6-ErnQVhimCrygD_C7pek,10599
|
|
8
|
+
statement_fetch/api.py,sha256=GOXfLn_6-yjY-0NHgwPYyKrwW95L5p72RCbf89y5pZM,2889
|
|
9
|
+
statement_fetch/cli.py,sha256=g5-ioa5CDzRMV8grlt1qJEtvUghrDVeqIR4ngzk-dJE,27966
|
|
10
|
+
statement_fetch/demo.py,sha256=unStK-XnwQaO-5etTkUKPivwTJye7Sr4hk944XaBEzg,4597
|
|
11
|
+
statement_fetch/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
statement_fetch/providers/__init__.py,sha256=X7GvEO3Pm_KZ7bOooBPZ41bfgujg3v4gQFbJYceDtSU,44
|
|
13
|
+
statement_fetch/providers/example_bank.py,sha256=JQ7f8-YKdzmINGe5mt5x7CS0Bde5N2t4iGSFpdRyuvo,6245
|
|
14
|
+
statement_fetch/sinks/__init__.py,sha256=p-YlFjgv6q3yj1t2MTQoPn30BmvvDP465mvmW3OjQYo,42
|
|
15
|
+
statement_fetch/sinks/directory.py,sha256=BN1ToqSGHX_gl5OxyeYZXiE0xoIRvd0pq-P-PiEL3JQ,10932
|
|
16
|
+
statement_fetch-0.5.0.dist-info/METADATA,sha256=cnxF5tLIjmeEjIrger0092-Ryosp-XiXDQ2i8FFl85w,4177
|
|
17
|
+
statement_fetch-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
18
|
+
statement_fetch-0.5.0.dist-info/entry_points.txt,sha256=X3TePPXii6WJ-Nx6AyhNNhr22GJbVGwhSkVUcZaOa_U,241
|
|
19
|
+
statement_fetch-0.5.0.dist-info/licenses/LICENSE,sha256=R9rLPJhizyGD3Z958_ZKuwCeUq77gz732CEJq5rq-gw,1068
|
|
20
|
+
statement_fetch-0.5.0.dist-info/RECORD,,
|