suca-pt 0.0.1__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.
- suca_pt/__init__.py +8 -0
- suca_pt/__main__.py +3 -0
- suca_pt/cli.py +77 -0
- suca_pt/engine/__init__.py +1 -0
- suca_pt/ingest/__init__.py +1 -0
- suca_pt/paths.py +77 -0
- suca_pt/selfcheck.py +154 -0
- suca_pt/server/__init__.py +1 -0
- suca_pt/server/app.py +81 -0
- suca_pt/server/guard.py +61 -0
- suca_pt/server/middleware.py +144 -0
- suca_pt/server/runner.py +106 -0
- suca_pt/updates.py +95 -0
- suca_pt/web/static/app.css +35 -0
- suca_pt/web/static/app.js +50 -0
- suca_pt/web/static/favicon.svg +1 -0
- suca_pt/web/static/index.html +27 -0
- suca_pt-0.0.1.dist-info/METADATA +101 -0
- suca_pt-0.0.1.dist-info/RECORD +21 -0
- suca_pt-0.0.1.dist-info/WHEEL +4 -0
- suca_pt-0.0.1.dist-info/entry_points.txt +3 -0
suca_pt/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""SUCA Portfolio Tracker: a local-first portfolio tracker for family investment managers."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("suca-pt")
|
|
7
|
+
except PackageNotFoundError: # a source tree without install metadata
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
suca_pt/__main__.py
ADDED
suca_pt/cli.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""The `suca-pt` command.
|
|
2
|
+
|
|
3
|
+
Starts the app on this computer only (127.0.0.1) and opens it in the browser.
|
|
4
|
+
There is deliberately no option to listen on another address.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import os
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
|
|
13
|
+
from suca_pt import __version__
|
|
14
|
+
|
|
15
|
+
ENV_NO_UPDATE_CHECK = "SUCA_PT_NO_UPDATE_CHECK"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _port(text: str) -> int:
|
|
19
|
+
try:
|
|
20
|
+
n = int(text)
|
|
21
|
+
except ValueError:
|
|
22
|
+
raise argparse.ArgumentTypeError("port must be a number") from None
|
|
23
|
+
if n != 0 and not 1024 <= n <= 65535:
|
|
24
|
+
raise argparse.ArgumentTypeError("port must be 0 (any free port) or 1024-65535")
|
|
25
|
+
return n
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
29
|
+
p = argparse.ArgumentParser(
|
|
30
|
+
prog="suca-pt",
|
|
31
|
+
description="SUCA Portfolio Tracker. Runs only on this computer; nothing is uploaded.",
|
|
32
|
+
)
|
|
33
|
+
p.add_argument("--version", action="version", version=f"suca-pt {__version__}")
|
|
34
|
+
p.add_argument(
|
|
35
|
+
"--port", type=_port, default=0, help="port on 127.0.0.1 (default: any free port)"
|
|
36
|
+
)
|
|
37
|
+
p.add_argument("--no-browser", action="store_true", help="don't open the browser")
|
|
38
|
+
p.add_argument("--data-dir", help="data folder (default: this user's app data folder)")
|
|
39
|
+
p.add_argument(
|
|
40
|
+
"--self-check",
|
|
41
|
+
action="store_true",
|
|
42
|
+
help="check this installation and print the result (contains no personal data)",
|
|
43
|
+
)
|
|
44
|
+
p.add_argument(
|
|
45
|
+
"--keyring", action="store_true", help="with --self-check: also test the keychain"
|
|
46
|
+
)
|
|
47
|
+
p.add_argument("--check-update", action="store_true", help="check for a newer version and exit")
|
|
48
|
+
p.add_argument("--no-update-check", action="store_true", help="don't check for updates")
|
|
49
|
+
return p
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
53
|
+
args = build_parser().parse_args(argv)
|
|
54
|
+
|
|
55
|
+
if args.self_check:
|
|
56
|
+
from suca_pt.selfcheck import run_self_check
|
|
57
|
+
|
|
58
|
+
return run_self_check(include_keyring=args.keyring)
|
|
59
|
+
|
|
60
|
+
if args.check_update:
|
|
61
|
+
from suca_pt.updates import check_for_update, describe
|
|
62
|
+
|
|
63
|
+
print(describe(check_for_update()), flush=True)
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
from suca_pt.paths import ensure_data_dir, record_run, resolve_data_dir
|
|
67
|
+
from suca_pt.server.runner import serve
|
|
68
|
+
|
|
69
|
+
data_dir = ensure_data_dir(resolve_data_dir(args.data_dir))
|
|
70
|
+
state = record_run(data_dir)
|
|
71
|
+
update_check = not (args.no_update_check or os.environ.get(ENV_NO_UPDATE_CHECK))
|
|
72
|
+
return serve(
|
|
73
|
+
port=args.port,
|
|
74
|
+
open_browser=not args.no_browser,
|
|
75
|
+
first_version=str(state["first_version"]),
|
|
76
|
+
update_check=update_check,
|
|
77
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Pure portfolio calculations: no I/O, no clock reads, no globals (Phase 1)."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Readers that turn broker files into records for the engine (Phase 1-2)."""
|
suca_pt/paths.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Where SUCA PT keeps its data on this computer.
|
|
2
|
+
|
|
3
|
+
Order of precedence: the --data-dir flag, then the SUCA_PT_DATA_DIR environment
|
|
4
|
+
variable, then the per-user app data folder (on macOS,
|
|
5
|
+
~/Library/Application Support/suca-pt).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import tempfile
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from platformdirs import user_data_path
|
|
18
|
+
|
|
19
|
+
from suca_pt import __version__
|
|
20
|
+
|
|
21
|
+
APP_NAME = "suca-pt"
|
|
22
|
+
ENV_DATA_DIR = "SUCA_PT_DATA_DIR"
|
|
23
|
+
STATE_FILE = "state.json"
|
|
24
|
+
STATE_SCHEMA = 1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_data_dir(override: str | None = None) -> Path:
|
|
28
|
+
if override:
|
|
29
|
+
return Path(override).expanduser()
|
|
30
|
+
env = os.environ.get(ENV_DATA_DIR)
|
|
31
|
+
if env:
|
|
32
|
+
return Path(env).expanduser()
|
|
33
|
+
return user_data_path(APP_NAME, appauthor=False, roaming=False)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def ensure_data_dir(path: Path) -> Path:
|
|
37
|
+
"""Create the data folder, readable only by this user."""
|
|
38
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
if os.name == "posix":
|
|
40
|
+
path.chmod(0o700)
|
|
41
|
+
return path
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def record_run(
|
|
45
|
+
data_dir: Path, version: str = __version__, now: datetime | None = None
|
|
46
|
+
) -> dict[str, Any]:
|
|
47
|
+
"""Create or update state.json with the first and latest version that ran here.
|
|
48
|
+
|
|
49
|
+
Later phases use `first_version` to detect upgrades (and back up before migrating);
|
|
50
|
+
the upgrade test uses it to prove data survives `uv tool upgrade`.
|
|
51
|
+
"""
|
|
52
|
+
stamp = (now or datetime.now(UTC)).isoformat(timespec="seconds")
|
|
53
|
+
path = data_dir / STATE_FILE
|
|
54
|
+
try:
|
|
55
|
+
state: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
|
|
56
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
57
|
+
state = {}
|
|
58
|
+
state.setdefault("schema", STATE_SCHEMA)
|
|
59
|
+
state.setdefault("first_version", version)
|
|
60
|
+
state.setdefault("first_run_at", stamp)
|
|
61
|
+
state["last_version"] = version
|
|
62
|
+
state["last_run_at"] = stamp
|
|
63
|
+
_atomic_write_json(path, state)
|
|
64
|
+
return state
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _atomic_write_json(path: Path, obj: object) -> None:
|
|
68
|
+
"""Write via a temp file + rename, so a crash never leaves half a file."""
|
|
69
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-", suffix=".json")
|
|
70
|
+
try:
|
|
71
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
72
|
+
json.dump(obj, f, indent=2, sort_keys=True)
|
|
73
|
+
f.write("\n")
|
|
74
|
+
Path(tmp).replace(path)
|
|
75
|
+
except BaseException:
|
|
76
|
+
Path(tmp).unlink(missing_ok=True)
|
|
77
|
+
raise
|
suca_pt/selfcheck.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""`suca-pt --self-check`: prove this installation works, without touching personal data.
|
|
2
|
+
|
|
3
|
+
The output is safe to send for support: library versions and OK/FAIL per check, with
|
|
4
|
+
no file paths, usernames or financial data. The PDF checks use a throwaway document
|
|
5
|
+
encrypted with a synthetic password (fake PANs start with ZZZZZ), exactly as broker
|
|
6
|
+
statements are encrypted with the holder's PAN.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import platform
|
|
12
|
+
import secrets
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from suca_pt import __version__
|
|
19
|
+
|
|
20
|
+
MARKER_TEXT = "SUCA SELF CHECK"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _fake_pan() -> str:
|
|
24
|
+
return "ZZZZZ" + "".join(secrets.choice("0123456789") for _ in range(4)) + "Z"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def run_self_check(include_keyring: bool = False, out: Callable[[str], None] = print) -> int:
|
|
28
|
+
out(f"suca-pt {__version__} self-check")
|
|
29
|
+
out(
|
|
30
|
+
f" python {platform.python_version()} ({platform.machine()}), "
|
|
31
|
+
f"macOS {platform.mac_ver()[0] or 'n/a'}, uv-managed: {_uv_managed()}"
|
|
32
|
+
)
|
|
33
|
+
failures = 0
|
|
34
|
+
password = _fake_pan()
|
|
35
|
+
with tempfile.TemporaryDirectory(prefix="suca-pt-selfcheck-") as tmp:
|
|
36
|
+
work = Path(tmp)
|
|
37
|
+
checks: list[tuple[str, Callable[[], str]]] = [
|
|
38
|
+
("pikepdf", lambda: _check_pikepdf(work, password)),
|
|
39
|
+
("pdfplumber", lambda: _check_pdfplumber(work, password)),
|
|
40
|
+
("pypdfium2", lambda: _check_pypdfium2(work, password)),
|
|
41
|
+
("cryptography", _check_cryptography),
|
|
42
|
+
]
|
|
43
|
+
if include_keyring:
|
|
44
|
+
checks.append(("keyring", _check_keyring))
|
|
45
|
+
for name, check in checks:
|
|
46
|
+
try:
|
|
47
|
+
detail = check()
|
|
48
|
+
out(f" OK {name}: {detail}")
|
|
49
|
+
except Exception as e: # report and continue; every check is independent
|
|
50
|
+
failures += 1
|
|
51
|
+
out(f" FAIL {name}: {type(e).__name__}: {e}")
|
|
52
|
+
out("All checks passed." if not failures else f"{failures} check(s) failed.")
|
|
53
|
+
return 1 if failures else 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _uv_managed() -> str:
|
|
57
|
+
exe = sys.executable.replace("\\", "/")
|
|
58
|
+
return "yes" if "/uv/python/" in exe or "/uv/tools/" in exe else "no"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _encrypted_pdfs(work: Path, password: str) -> dict[str, Path]:
|
|
62
|
+
"""Build a one-page PDF and save AES-256 (R6) and AES-128 (R4) encrypted copies."""
|
|
63
|
+
import pikepdf
|
|
64
|
+
|
|
65
|
+
existing = {k: work / f"{k}.pdf" for k in ("aes256", "aes128")}
|
|
66
|
+
if all(p.exists() for p in existing.values()):
|
|
67
|
+
return existing
|
|
68
|
+
pdf = pikepdf.new()
|
|
69
|
+
page = pdf.add_blank_page(page_size=(612, 792))
|
|
70
|
+
font = pikepdf.Dictionary(
|
|
71
|
+
Type=pikepdf.Name.Font, Subtype=pikepdf.Name.Type1, BaseFont=pikepdf.Name.Helvetica
|
|
72
|
+
)
|
|
73
|
+
page.obj.Resources = pikepdf.Dictionary(Font=pikepdf.Dictionary(F1=font))
|
|
74
|
+
page.obj.Contents = pdf.make_stream(f"BT /F1 18 Tf 72 700 Td ({MARKER_TEXT}) Tj ET".encode())
|
|
75
|
+
pdf.save(existing["aes256"], encryption=pikepdf.Encryption(owner=password, user=password, R=6))
|
|
76
|
+
pdf.save(
|
|
77
|
+
existing["aes128"],
|
|
78
|
+
encryption=pikepdf.Encryption(owner=password, user=password, R=4, aes=True),
|
|
79
|
+
)
|
|
80
|
+
return existing
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _check_pikepdf(work: Path, password: str) -> str:
|
|
84
|
+
import pikepdf
|
|
85
|
+
|
|
86
|
+
files = _encrypted_pdfs(work, password)
|
|
87
|
+
for path in files.values():
|
|
88
|
+
try:
|
|
89
|
+
pikepdf.open(path).close()
|
|
90
|
+
except pikepdf.PasswordError:
|
|
91
|
+
pass
|
|
92
|
+
else:
|
|
93
|
+
raise AssertionError("encrypted PDF opened without its password")
|
|
94
|
+
with pikepdf.open(path, password=password) as pdf:
|
|
95
|
+
pdf.save(work / f"decrypted-{path.name}") # what Demat used qpdf for
|
|
96
|
+
with pikepdf.open(work / f"decrypted-{path.name}") as plain:
|
|
97
|
+
if plain.is_encrypted:
|
|
98
|
+
raise AssertionError("decrypted copy is still encrypted")
|
|
99
|
+
return (
|
|
100
|
+
f"{pikepdf.__version__} (qpdf {pikepdf.__libqpdf_version__}); AES-256 + AES-128 round trip"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _check_pdfplumber(work: Path, password: str) -> str:
|
|
105
|
+
import pdfplumber
|
|
106
|
+
|
|
107
|
+
for path in _encrypted_pdfs(work, password).values():
|
|
108
|
+
with pdfplumber.open(path, password=password) as pdf:
|
|
109
|
+
text = pdf.pages[0].extract_text() or ""
|
|
110
|
+
if MARKER_TEXT not in text:
|
|
111
|
+
raise AssertionError(f"text not found in {path.stem}")
|
|
112
|
+
return f"{pdfplumber.__version__}; opened both with password, text extracted"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _check_pypdfium2(work: Path, password: str) -> str:
|
|
116
|
+
import pypdfium2 as pdfium
|
|
117
|
+
|
|
118
|
+
for path in _encrypted_pdfs(work, password).values():
|
|
119
|
+
doc = pdfium.PdfDocument(path, password=password)
|
|
120
|
+
try:
|
|
121
|
+
text = doc[0].get_textpage().get_text_range()
|
|
122
|
+
finally:
|
|
123
|
+
doc.close()
|
|
124
|
+
if MARKER_TEXT not in text:
|
|
125
|
+
raise AssertionError(f"text not found in {path.stem}")
|
|
126
|
+
return f"{pdfium.version.PYPDFIUM_INFO}; opened both with password, text extracted"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _check_cryptography() -> str:
|
|
130
|
+
import cryptography
|
|
131
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
132
|
+
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
|
133
|
+
|
|
134
|
+
salt = secrets.token_bytes(16)
|
|
135
|
+
key = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1).derive(b"synthetic passphrase")
|
|
136
|
+
nonce = secrets.token_bytes(12)
|
|
137
|
+
sealed = AESGCM(key).encrypt(nonce, b"synthetic payload", None)
|
|
138
|
+
if AESGCM(key).decrypt(nonce, sealed, None) != b"synthetic payload":
|
|
139
|
+
raise AssertionError("AES-GCM round trip mismatch")
|
|
140
|
+
return f"{cryptography.__version__}; AES-GCM + scrypt round trip"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _check_keyring() -> str:
|
|
144
|
+
import keyring
|
|
145
|
+
|
|
146
|
+
service, user = "suca-pt-selfcheck", "probe"
|
|
147
|
+
value = secrets.token_urlsafe(16)
|
|
148
|
+
keyring.set_password(service, user, value)
|
|
149
|
+
try:
|
|
150
|
+
if keyring.get_password(service, user) != value:
|
|
151
|
+
raise AssertionError("keychain returned a different value")
|
|
152
|
+
finally:
|
|
153
|
+
keyring.delete_password(service, user)
|
|
154
|
+
return f"{type(keyring.get_keyring()).__name__}; set/get/delete round trip"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The local web server: 127.0.0.1 only, guarded, one session per launch."""
|
suca_pt/server/app.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""The local web app: a handful of routes plus the packaged static UI.
|
|
2
|
+
|
|
3
|
+
Everything is wrapped by the middleware in middleware.py, which refuses requests from
|
|
4
|
+
other web pages and requires the per-launch session cookie.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import secrets
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from starlette.applications import Starlette
|
|
15
|
+
from starlette.requests import Request
|
|
16
|
+
from starlette.responses import JSONResponse, RedirectResponse, Response
|
|
17
|
+
from starlette.routing import Mount, Route
|
|
18
|
+
from starlette.staticfiles import StaticFiles
|
|
19
|
+
|
|
20
|
+
from suca_pt import __version__
|
|
21
|
+
from suca_pt.server.middleware import (
|
|
22
|
+
SESSION_COOKIE,
|
|
23
|
+
ASGIApp,
|
|
24
|
+
LocalAccessMiddleware,
|
|
25
|
+
SecurityHeadersMiddleware,
|
|
26
|
+
)
|
|
27
|
+
from suca_pt.updates import UpdateStatus
|
|
28
|
+
|
|
29
|
+
STATIC_DIR = Path(__file__).resolve().parent.parent / "web" / "static"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class AppConfig:
|
|
34
|
+
port: int
|
|
35
|
+
launch_token: str
|
|
36
|
+
session_secret: str
|
|
37
|
+
first_version: str
|
|
38
|
+
on_shutdown: Callable[[], None]
|
|
39
|
+
version: str = __version__
|
|
40
|
+
update_status: UpdateStatus = field(default_factory=UpdateStatus)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def create_app(cfg: AppConfig) -> ASGIApp:
|
|
44
|
+
async def auth(request: Request) -> Response:
|
|
45
|
+
token = request.query_params.get("t", "")
|
|
46
|
+
if not secrets.compare_digest(token.encode(), cfg.launch_token.encode()):
|
|
47
|
+
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
48
|
+
response = RedirectResponse("/", status_code=303)
|
|
49
|
+
# Session cookie (no Max-Age/Expires); host-only (no Domain); plain http, so no Secure.
|
|
50
|
+
response.set_cookie(
|
|
51
|
+
SESSION_COOKIE, cfg.session_secret, httponly=True, samesite="strict", path="/"
|
|
52
|
+
)
|
|
53
|
+
return response
|
|
54
|
+
|
|
55
|
+
async def health(request: Request) -> Response:
|
|
56
|
+
return JSONResponse(
|
|
57
|
+
{
|
|
58
|
+
"status": "ok",
|
|
59
|
+
"app": "suca-pt",
|
|
60
|
+
"version": cfg.version,
|
|
61
|
+
"first_version": cfg.first_version,
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
async def version(request: Request) -> Response:
|
|
66
|
+
return JSONResponse(cfg.update_status.as_dict(cfg.version))
|
|
67
|
+
|
|
68
|
+
async def shutdown(request: Request) -> Response:
|
|
69
|
+
cfg.on_shutdown()
|
|
70
|
+
return JSONResponse({"status": "stopping"}, status_code=202)
|
|
71
|
+
|
|
72
|
+
routes = [
|
|
73
|
+
Route("/auth", auth, methods=["GET"]),
|
|
74
|
+
Route("/health", health, methods=["GET"]),
|
|
75
|
+
Route("/api/version", version, methods=["GET"]),
|
|
76
|
+
Route("/api/shutdown", shutdown, methods=["POST"]),
|
|
77
|
+
Mount("/", StaticFiles(directory=STATIC_DIR, html=True, follow_symlink=False)),
|
|
78
|
+
]
|
|
79
|
+
app = Starlette(routes=routes)
|
|
80
|
+
guarded = LocalAccessMiddleware(app, port=cfg.port, session_secret=cfg.session_secret)
|
|
81
|
+
return SecurityHeadersMiddleware(guarded)
|
suca_pt/server/guard.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Refuse requests that don't come from this app's own page.
|
|
2
|
+
|
|
3
|
+
Ported from Demat's `_local_request_block_reason` (build_dashboard.py), which closed
|
|
4
|
+
a hole where any website open in the browser could read and rewrite the book.
|
|
5
|
+
|
|
6
|
+
The server binds 127.0.0.1, but every web page open in the browser can still send
|
|
7
|
+
requests to it. Browsers label those requests, so refuse any that:
|
|
8
|
+
- name a Host other than this server. This defeats DNS rebinding: a hostile
|
|
9
|
+
domain resolving to 127.0.0.1 still sends its own name as Host;
|
|
10
|
+
- carry an Origin other than this server (a cross-site fetch, a form post, or the
|
|
11
|
+
'null' origin of sandboxed frames and file:// pages);
|
|
12
|
+
- are marked cross-site by Sec-Fetch-Site, except a top-level load of the page
|
|
13
|
+
itself, which only renders it; everything the page then does is same-origin;
|
|
14
|
+
- write without a JSON body, so a plain HTML form can never post here.
|
|
15
|
+
Non-browser clients (curl) send neither Origin nor Sec-Fetch-* and are allowed.
|
|
16
|
+
They still need the per-launch session cookie (see middleware.py).
|
|
17
|
+
|
|
18
|
+
Changes from Demat: PATCH is a write too, and the media type must be exactly
|
|
19
|
+
application/json (Demat accepted any type that merely started with it).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections.abc import Mapping
|
|
25
|
+
|
|
26
|
+
# Pages a link from another site may open: they render the app and nothing else.
|
|
27
|
+
NAVIGABLE_PAGES = frozenset({"/", "/index.html"})
|
|
28
|
+
WRITE_METHODS = frozenset({"POST", "PUT", "PATCH"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def block_reason(method: str, path: str, headers: Mapping[str, str], port: int) -> str | None:
|
|
32
|
+
"""Return why the request must be refused, or None if it may proceed.
|
|
33
|
+
|
|
34
|
+
`headers` must use lowercase names (as ASGI provides them). `path` excludes the
|
|
35
|
+
query string.
|
|
36
|
+
"""
|
|
37
|
+
hosts = {f"localhost:{port}", f"127.0.0.1:{port}"}
|
|
38
|
+
if (headers.get("host") or "").strip().lower() not in hosts:
|
|
39
|
+
return "host"
|
|
40
|
+
|
|
41
|
+
origin = headers.get("origin")
|
|
42
|
+
if origin is not None and origin.strip().lower() not in {"http://" + h for h in hosts}:
|
|
43
|
+
return "origin"
|
|
44
|
+
|
|
45
|
+
site = headers.get("sec-fetch-site")
|
|
46
|
+
if site is not None and site not in ("same-origin", "none"):
|
|
47
|
+
page_load = (
|
|
48
|
+
method == "GET"
|
|
49
|
+
and path in NAVIGABLE_PAGES
|
|
50
|
+
and headers.get("sec-fetch-mode") == "navigate"
|
|
51
|
+
and headers.get("sec-fetch-dest") == "document"
|
|
52
|
+
)
|
|
53
|
+
if not page_load:
|
|
54
|
+
return "cross-site"
|
|
55
|
+
|
|
56
|
+
if method in WRITE_METHODS:
|
|
57
|
+
media_type = (headers.get("content-type") or "").split(";", 1)[0].strip().lower()
|
|
58
|
+
if media_type != "application/json":
|
|
59
|
+
return "content-type"
|
|
60
|
+
|
|
61
|
+
return None
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""ASGI middleware: security headers, the local-access guard, and the session cookie.
|
|
2
|
+
|
|
3
|
+
Order (outermost first): SecurityHeaders -> LocalAccess -> app. Every response,
|
|
4
|
+
including refusals and errors, therefore carries the security headers.
|
|
5
|
+
|
|
6
|
+
Session model:
|
|
7
|
+
- Each launch generates a random *launch token* (in the URL the launcher opens)
|
|
8
|
+
and a separate random *session secret*.
|
|
9
|
+
- GET /auth?t=<launch token> sets the session secret as an HttpOnly,
|
|
10
|
+
SameSite=Strict cookie. Every other request must carry that cookie.
|
|
11
|
+
- The guard (guard.py) stops other web pages and DNS rebinding. The token stops
|
|
12
|
+
other users and other programs on this computer, which share loopback.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import secrets
|
|
19
|
+
from collections.abc import Awaitable, Callable, MutableMapping
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from starlette.datastructures import MutableHeaders
|
|
23
|
+
from starlette.requests import cookie_parser
|
|
24
|
+
|
|
25
|
+
from suca_pt.server.guard import block_reason
|
|
26
|
+
|
|
27
|
+
Scope = MutableMapping[str, Any]
|
|
28
|
+
Message = MutableMapping[str, Any]
|
|
29
|
+
Receive = Callable[[], Awaitable[Message]]
|
|
30
|
+
Send = Callable[[Message], Awaitable[None]]
|
|
31
|
+
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
32
|
+
|
|
33
|
+
SESSION_COOKIE = "suca_pt_session"
|
|
34
|
+
AUTH_PATH = "/auth"
|
|
35
|
+
|
|
36
|
+
CSP = (
|
|
37
|
+
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
|
|
38
|
+
"connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; "
|
|
39
|
+
"frame-ancestors 'none'"
|
|
40
|
+
)
|
|
41
|
+
SECURITY_HEADERS: tuple[tuple[str, str], ...] = (
|
|
42
|
+
("Content-Security-Policy", CSP),
|
|
43
|
+
("X-Frame-Options", "DENY"),
|
|
44
|
+
("X-Content-Type-Options", "nosniff"),
|
|
45
|
+
("Referrer-Policy", "no-referrer"),
|
|
46
|
+
("Cross-Origin-Opener-Policy", "same-origin"),
|
|
47
|
+
("Cross-Origin-Resource-Policy", "same-origin"),
|
|
48
|
+
("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()"),
|
|
49
|
+
("Cache-Control", "no-store"),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
LAUNCHER_PAGE = (
|
|
53
|
+
b"<!doctype html><meta charset='utf-8'><title>SUCA PT</title>"
|
|
54
|
+
b"<p>Please start SUCA PT from its launcher: run <code>suca-pt</code> in Terminal, "
|
|
55
|
+
b"then use the link it prints.</p>"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SecurityHeadersMiddleware:
|
|
60
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
61
|
+
self.app = app
|
|
62
|
+
|
|
63
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
64
|
+
if scope["type"] != "http":
|
|
65
|
+
await self.app(scope, receive, send)
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
async def send_with_headers(message: Message) -> None:
|
|
69
|
+
if message["type"] == "http.response.start":
|
|
70
|
+
headers = MutableHeaders(scope=message)
|
|
71
|
+
for name, value in SECURITY_HEADERS:
|
|
72
|
+
headers[name] = value
|
|
73
|
+
for name in [h for h in headers if h.lower().startswith("access-control-")]:
|
|
74
|
+
del headers[name]
|
|
75
|
+
await send(message)
|
|
76
|
+
|
|
77
|
+
await self.app(scope, receive, send_with_headers)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class LocalAccessMiddleware:
|
|
81
|
+
def __init__(self, app: ASGIApp, *, port: int, session_secret: str) -> None:
|
|
82
|
+
self.app = app
|
|
83
|
+
self.port = port
|
|
84
|
+
self.session_secret = session_secret.encode()
|
|
85
|
+
|
|
86
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
87
|
+
kind = scope["type"]
|
|
88
|
+
if kind == "lifespan":
|
|
89
|
+
await self.app(scope, receive, send)
|
|
90
|
+
return
|
|
91
|
+
if kind == "websocket":
|
|
92
|
+
await send({"type": "websocket.close", "code": 1008})
|
|
93
|
+
return
|
|
94
|
+
if kind != "http":
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
raw: list[tuple[bytes, bytes]] = scope.get("headers", [])
|
|
98
|
+
names = [k.lower() for k, _ in raw]
|
|
99
|
+
if names.count(b"host") > 1 or names.count(b"origin") > 1:
|
|
100
|
+
await _send_json(send, 403, {"error": "forbidden", "reason": "duplicate-header"})
|
|
101
|
+
return
|
|
102
|
+
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in raw}
|
|
103
|
+
|
|
104
|
+
reason = block_reason(scope["method"], scope["path"], headers, self.port)
|
|
105
|
+
if reason:
|
|
106
|
+
print(f" [security] refused {scope['method']} {scope['path']} ({reason})", flush=True)
|
|
107
|
+
await _send_json(send, 403, {"error": "forbidden", "reason": reason})
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
if scope["path"] == AUTH_PATH:
|
|
111
|
+
await self.app(scope, receive, send)
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
cookie = cookie_parser(headers.get("cookie", "")).get(SESSION_COOKIE, "")
|
|
115
|
+
if not secrets.compare_digest(cookie.encode(), self.session_secret):
|
|
116
|
+
if _wants_html(headers):
|
|
117
|
+
await _send(send, 401, LAUNCHER_PAGE, "text/html; charset=utf-8")
|
|
118
|
+
else:
|
|
119
|
+
await _send_json(send, 401, {"error": "unauthorized"})
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
await self.app(scope, receive, send)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _wants_html(headers: dict[str, str]) -> bool:
|
|
126
|
+
return headers.get("sec-fetch-dest") == "document" or "text/html" in headers.get("accept", "")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def _send_json(send: Send, status: int, body: dict[str, Any]) -> None:
|
|
130
|
+
await _send(send, status, json.dumps(body).encode(), "application/json")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
async def _send(send: Send, status: int, body: bytes, content_type: str) -> None:
|
|
134
|
+
await send(
|
|
135
|
+
{
|
|
136
|
+
"type": "http.response.start",
|
|
137
|
+
"status": status,
|
|
138
|
+
"headers": [
|
|
139
|
+
(b"content-type", content_type.encode()),
|
|
140
|
+
(b"content-length", str(len(body)).encode()),
|
|
141
|
+
],
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
await send({"type": "http.response.body", "body": body})
|
suca_pt/server/runner.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Run the app on 127.0.0.1 and open it in the browser."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import errno
|
|
6
|
+
import secrets
|
|
7
|
+
import socket
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import webbrowser
|
|
12
|
+
|
|
13
|
+
import uvicorn
|
|
14
|
+
|
|
15
|
+
from suca_pt import __version__
|
|
16
|
+
from suca_pt.server.app import AppConfig, create_app
|
|
17
|
+
from suca_pt.updates import check_for_update, describe
|
|
18
|
+
|
|
19
|
+
EXIT_PORT_IN_USE = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def bind_loopback(port: int) -> socket.socket:
|
|
23
|
+
"""Bind 127.0.0.1 ourselves. Port 0 lets the OS choose, with no find-then-bind race."""
|
|
24
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
25
|
+
if port:
|
|
26
|
+
# Lets a fixed port be reused right after a restart (TIME_WAIT). It does not let
|
|
27
|
+
# us take over a port another program is actively listening on.
|
|
28
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
29
|
+
sock.bind(("127.0.0.1", port))
|
|
30
|
+
sock.listen(128)
|
|
31
|
+
return sock
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def serve(*, port: int, open_browser: bool, first_version: str, update_check: bool) -> int:
|
|
35
|
+
try:
|
|
36
|
+
sock = bind_loopback(port)
|
|
37
|
+
except OSError as e:
|
|
38
|
+
if e.errno == errno.EADDRINUSE:
|
|
39
|
+
print(f"Port {port} is already in use. Try another port, or omit --port.", flush=True)
|
|
40
|
+
return EXIT_PORT_IN_USE
|
|
41
|
+
raise
|
|
42
|
+
real_port = sock.getsockname()[1]
|
|
43
|
+
|
|
44
|
+
launch_token = secrets.token_urlsafe(32)
|
|
45
|
+
session_secret = secrets.token_urlsafe(32)
|
|
46
|
+
server: uvicorn.Server | None = None
|
|
47
|
+
|
|
48
|
+
def request_shutdown() -> None:
|
|
49
|
+
if server is not None:
|
|
50
|
+
server.should_exit = True
|
|
51
|
+
|
|
52
|
+
cfg = AppConfig(
|
|
53
|
+
port=real_port,
|
|
54
|
+
launch_token=launch_token,
|
|
55
|
+
session_secret=session_secret,
|
|
56
|
+
first_version=first_version,
|
|
57
|
+
on_shutdown=request_shutdown,
|
|
58
|
+
)
|
|
59
|
+
config = uvicorn.Config(
|
|
60
|
+
create_app(cfg),
|
|
61
|
+
http="h11",
|
|
62
|
+
loop="asyncio",
|
|
63
|
+
ws="none",
|
|
64
|
+
lifespan="off",
|
|
65
|
+
access_log=False, # the /auth?t= token must never reach a log
|
|
66
|
+
proxy_headers=False,
|
|
67
|
+
server_header=False,
|
|
68
|
+
date_header=False,
|
|
69
|
+
log_level="warning",
|
|
70
|
+
timeout_graceful_shutdown=3,
|
|
71
|
+
)
|
|
72
|
+
server = uvicorn.Server(config)
|
|
73
|
+
url = f"http://127.0.0.1:{real_port}/auth?t={launch_token}"
|
|
74
|
+
|
|
75
|
+
print(f"SUCA Portfolio Tracker {__version__}", flush=True)
|
|
76
|
+
print(f"Open: {url}", flush=True)
|
|
77
|
+
print("Keep this window open while you use the app. Press Ctrl+C or Quit to stop.", flush=True)
|
|
78
|
+
|
|
79
|
+
if update_check:
|
|
80
|
+
threading.Thread(target=_check_updates, args=(cfg,), daemon=True).start()
|
|
81
|
+
if open_browser:
|
|
82
|
+
threading.Thread(target=_open_when_ready, args=(server, url), daemon=True).start()
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
server.run(sockets=[sock])
|
|
86
|
+
except KeyboardInterrupt:
|
|
87
|
+
pass
|
|
88
|
+
finally:
|
|
89
|
+
sock.close()
|
|
90
|
+
print("SUCA PT stopped.", flush=True)
|
|
91
|
+
return 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _open_when_ready(server: uvicorn.Server, url: str) -> None:
|
|
95
|
+
deadline = time.monotonic() + 15
|
|
96
|
+
while not server.started and not server.should_exit and time.monotonic() < deadline:
|
|
97
|
+
time.sleep(0.05)
|
|
98
|
+
if server.started:
|
|
99
|
+
webbrowser.open(url)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _check_updates(cfg: AppConfig) -> None:
|
|
103
|
+
result = check_for_update(cfg.version)
|
|
104
|
+
cfg.update_status.set(result)
|
|
105
|
+
if result.update_available:
|
|
106
|
+
print(describe(result), flush=True, file=sys.stdout)
|
suca_pt/updates.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Check PyPI for a newer release.
|
|
2
|
+
|
|
3
|
+
One anonymous GET to PyPI's public JSON API, once per launch. No user data is sent.
|
|
4
|
+
PyPI does see this computer's IP address; the README documents that and the opt-out
|
|
5
|
+
(`--no-update-check` or SUCA_PT_NO_UPDATE_CHECK=1).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import threading
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from suca_pt import __version__
|
|
19
|
+
|
|
20
|
+
PYPI_URL = "https://pypi.org/pypi/suca-pt/json"
|
|
21
|
+
UPGRADE_COMMAND = "uv tool upgrade suca-pt"
|
|
22
|
+
TIMEOUT_SECONDS = 5.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class UpdateResult:
|
|
27
|
+
current: str
|
|
28
|
+
latest: str | None = None
|
|
29
|
+
error: str | None = None
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def update_available(self) -> bool:
|
|
33
|
+
cur, new = parse_version(self.current), parse_version(self.latest or "")
|
|
34
|
+
return cur is not None and new is not None and new > cur
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class UpdateStatus:
|
|
39
|
+
"""Shared between the background check and the /api/version endpoint."""
|
|
40
|
+
|
|
41
|
+
result: UpdateResult | None = None
|
|
42
|
+
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
43
|
+
|
|
44
|
+
def set(self, result: UpdateResult) -> None:
|
|
45
|
+
with self._lock:
|
|
46
|
+
self.result = result
|
|
47
|
+
|
|
48
|
+
def as_dict(self, current: str) -> dict[str, Any]:
|
|
49
|
+
with self._lock:
|
|
50
|
+
r = self.result
|
|
51
|
+
return {
|
|
52
|
+
"current": current,
|
|
53
|
+
"latest": r.latest if r else None,
|
|
54
|
+
"checked": r is not None,
|
|
55
|
+
"update_available": bool(r and r.update_available),
|
|
56
|
+
"upgrade_command": UPGRADE_COMMAND,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_version(text: str) -> tuple[int, ...] | None:
|
|
61
|
+
"""Parse a plain X.Y.Z release version. We never publish pre-releases."""
|
|
62
|
+
parts = text.strip().split(".")
|
|
63
|
+
if len(parts) != 3 or not all(p.isdigit() for p in parts):
|
|
64
|
+
return None
|
|
65
|
+
return tuple(int(p) for p in parts)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
Opener = Callable[..., Any]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_for_update(
|
|
72
|
+
current: str = __version__, opener: Opener = urllib.request.urlopen
|
|
73
|
+
) -> UpdateResult:
|
|
74
|
+
request = urllib.request.Request(
|
|
75
|
+
PYPI_URL, headers={"User-Agent": f"suca-pt/{current}", "Accept": "application/json"}
|
|
76
|
+
)
|
|
77
|
+
try:
|
|
78
|
+
with opener(request, timeout=TIMEOUT_SECONDS) as response:
|
|
79
|
+
latest = str(json.load(response)["info"]["version"])
|
|
80
|
+
except urllib.error.HTTPError as e:
|
|
81
|
+
return UpdateResult(current, error="not on PyPI yet" if e.code == 404 else f"HTTP {e.code}")
|
|
82
|
+
except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError) as e:
|
|
83
|
+
return UpdateResult(current, error=type(e).__name__)
|
|
84
|
+
return UpdateResult(current, latest=latest)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def describe(result: UpdateResult) -> str:
|
|
88
|
+
if result.error:
|
|
89
|
+
return f"suca-pt {result.current}: couldn't check for updates ({result.error})."
|
|
90
|
+
if result.update_available:
|
|
91
|
+
return (
|
|
92
|
+
f"Update available: {result.latest} (you have {result.current}). "
|
|
93
|
+
f"Quit SUCA PT, then run: {UPGRADE_COMMAND}"
|
|
94
|
+
)
|
|
95
|
+
return f"suca-pt {result.current} is up to date."
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
:root {
|
|
2
|
+
--bg: #f7f7f5;
|
|
3
|
+
--fg: #1a1a1a;
|
|
4
|
+
--muted: #5f6368;
|
|
5
|
+
--accent: #1f6feb;
|
|
6
|
+
--banner: #fff4d6;
|
|
7
|
+
}
|
|
8
|
+
@media (prefers-color-scheme: dark) {
|
|
9
|
+
:root { --bg: #111214; --fg: #ececec; --muted: #9aa0a6; --accent: #58a6ff; --banner: #3a2f10; }
|
|
10
|
+
}
|
|
11
|
+
* { box-sizing: border-box; }
|
|
12
|
+
body {
|
|
13
|
+
margin: 0;
|
|
14
|
+
background: var(--bg);
|
|
15
|
+
color: var(--fg);
|
|
16
|
+
font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
17
|
+
}
|
|
18
|
+
main { max-width: 640px; margin: 64px auto; padding: 0 16px; }
|
|
19
|
+
h1 { font-size: 22px; margin: 0 0 4px; }
|
|
20
|
+
.lede { color: var(--muted); margin: 0 0 24px; }
|
|
21
|
+
dl { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0 0 24px; }
|
|
22
|
+
dt { color: var(--muted); }
|
|
23
|
+
dd { margin: 0; font-variant-numeric: tabular-nums; }
|
|
24
|
+
.banner { background: var(--banner); padding: 10px 12px; border-radius: 6px; margin: 0 0 20px; }
|
|
25
|
+
code { font: 13px ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
26
|
+
button {
|
|
27
|
+
font: inherit;
|
|
28
|
+
padding: 6px 14px;
|
|
29
|
+
border-radius: 6px;
|
|
30
|
+
border: 1px solid var(--muted);
|
|
31
|
+
background: transparent;
|
|
32
|
+
color: var(--fg);
|
|
33
|
+
cursor: pointer;
|
|
34
|
+
}
|
|
35
|
+
button:disabled { opacity: 0.5; cursor: default; }
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Placeholder UI (Phase 0). The Phase 3 React build replaces this folder.
|
|
2
|
+
// Same-origin requests only; the session cookie is sent automatically.
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
function show(id, text) {
|
|
6
|
+
document.getElementById(id).textContent = text;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async function getJSON(path) {
|
|
10
|
+
const r = await fetch(path, { headers: { Accept: "application/json" } });
|
|
11
|
+
if (!r.ok) throw new Error(path + " " + r.status);
|
|
12
|
+
return r.json();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function load() {
|
|
16
|
+
try {
|
|
17
|
+
const h = await getJSON("/health");
|
|
18
|
+
show("version", h.version);
|
|
19
|
+
show("first-version", h.first_version);
|
|
20
|
+
show("status", "Running");
|
|
21
|
+
} catch (e) {
|
|
22
|
+
show("status", "Not connected. Start SUCA PT from Terminal.");
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
// The background update check may still be in flight; poll briefly.
|
|
26
|
+
for (let i = 0; i < 10; i++) {
|
|
27
|
+
const v = await getJSON("/api/version");
|
|
28
|
+
if (v.checked) {
|
|
29
|
+
if (v.update_available) {
|
|
30
|
+
show("update-text", "Update available: " + v.latest + ". Quit, then run: ");
|
|
31
|
+
show("update-cmd", v.upgrade_command);
|
|
32
|
+
document.getElementById("update").hidden = false;
|
|
33
|
+
}
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
document.getElementById("quit").addEventListener("click", async () => {
|
|
41
|
+
await fetch("/api/shutdown", {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "Content-Type": "application/json" },
|
|
44
|
+
body: "{}",
|
|
45
|
+
});
|
|
46
|
+
show("status", "Stopped. You can close this tab.");
|
|
47
|
+
document.getElementById("quit").disabled = true;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
load();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#1f6feb"/><path d="M8 22 L14 15 L18 18 L24 10" stroke="#fff" stroke-width="2.6" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>SUCA Portfolio Tracker</title>
|
|
7
|
+
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
|
8
|
+
<link rel="stylesheet" href="app.css">
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<main>
|
|
12
|
+
<h1>SUCA Portfolio Tracker</h1>
|
|
13
|
+
<p class="lede">Running on this computer only. Nothing you add here is uploaded.</p>
|
|
14
|
+
<div id="update" class="banner" hidden>
|
|
15
|
+
<span id="update-text"></span>
|
|
16
|
+
<code id="update-cmd"></code>
|
|
17
|
+
</div>
|
|
18
|
+
<dl>
|
|
19
|
+
<dt>Version</dt><dd id="version">…</dd>
|
|
20
|
+
<dt>First installed</dt><dd id="first-version">…</dd>
|
|
21
|
+
<dt>Status</dt><dd id="status">Connecting…</dd>
|
|
22
|
+
</dl>
|
|
23
|
+
<button id="quit" type="button">Quit SUCA PT</button>
|
|
24
|
+
</main>
|
|
25
|
+
<script src="app.js"></script>
|
|
26
|
+
</body>
|
|
27
|
+
</html>
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: suca-pt
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: SUCA Portfolio Tracker: a local-first portfolio tracker for Indian family investment managers
|
|
5
|
+
Author: SUCA Analytics
|
|
6
|
+
License-Expression: LicenseRef-Proprietary
|
|
7
|
+
Classifier: Operating System :: MacOS
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Requires-Dist: cryptography>=50.0.2
|
|
10
|
+
Requires-Dist: keyring>=25.7.0
|
|
11
|
+
Requires-Dist: pdfplumber>=0.11.10
|
|
12
|
+
Requires-Dist: pikepdf>=10.16.0
|
|
13
|
+
Requires-Dist: platformdirs>=4.12.3
|
|
14
|
+
Requires-Dist: starlette>=1.7.0
|
|
15
|
+
Requires-Dist: uvicorn>=0.54.0
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# SUCA Portfolio Tracker
|
|
20
|
+
|
|
21
|
+
A portfolio tracker for Indian families who manage several demat accounts:
|
|
22
|
+
people, HUFs and companies, across brokers. It runs on your own Mac and opens
|
|
23
|
+
in your browser.
|
|
24
|
+
|
|
25
|
+
> **Early preview.** Versions 0.0.x install and run but have no portfolio
|
|
26
|
+
> features yet. They exist to prove installation and updates.
|
|
27
|
+
|
|
28
|
+
## Your data stays on your Mac
|
|
29
|
+
|
|
30
|
+
- The app listens only on `127.0.0.1`, so other devices on your network cannot
|
|
31
|
+
reach it, and it serves only the browser tab it opened for you.
|
|
32
|
+
- Your statements, holdings and trades are never uploaded anywhere.
|
|
33
|
+
- The only request it makes to the internet is an optional check, once per
|
|
34
|
+
launch, for a newer version on pypi.org. That request sends no data. You can
|
|
35
|
+
turn it off (see *Options*).
|
|
36
|
+
|
|
37
|
+
## Requirements
|
|
38
|
+
|
|
39
|
+
An Apple Silicon Mac (M1 or later) running macOS 15 or later.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
Open **Terminal** and run these two commands. The first installs
|
|
44
|
+
[uv](https://docs.astral.sh/uv/), a free Python installer. The second installs
|
|
45
|
+
the app with its own copy of Python, so nothing else on your Mac changes.
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
49
|
+
uv tool install --managed-python --python 3.14 suca-pt
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Then open a **new** Terminal window and start it:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
suca-pt
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Your browser opens the app. Leave the Terminal window open while you use it.
|
|
59
|
+
To stop, click **Quit** in the app or press Ctrl-C in Terminal.
|
|
60
|
+
|
|
61
|
+
If `suca-pt` is not found, run `uv tool update-shell` and open a new window.
|
|
62
|
+
|
|
63
|
+
## Update
|
|
64
|
+
|
|
65
|
+
When the app shows that a new version is available, quit it, then run:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
uv tool upgrade suca-pt
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Your data is kept.
|
|
72
|
+
|
|
73
|
+
## Options
|
|
74
|
+
|
|
75
|
+
| Command | What it does |
|
|
76
|
+
|---|---|
|
|
77
|
+
| `suca-pt --no-browser` | Print the address instead of opening the browser |
|
|
78
|
+
| `suca-pt --port 8765` | Use a fixed port instead of a free one |
|
|
79
|
+
| `suca-pt --self-check` | Check that the app's components work on this Mac (prints no personal data) |
|
|
80
|
+
| `suca-pt --check-update` | Check for a new version and exit |
|
|
81
|
+
| `suca-pt --no-update-check` | Skip the update check this time |
|
|
82
|
+
| `SUCA_PT_NO_UPDATE_CHECK=1` | Skip it always (set in your shell profile) |
|
|
83
|
+
| `suca-pt --version` | Show the installed version |
|
|
84
|
+
|
|
85
|
+
## Uninstall
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
uv tool uninstall suca-pt
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
That removes the app. Your data stays in
|
|
92
|
+
`~/Library/Application Support/suca-pt`. Delete that folder to remove it too.
|
|
93
|
+
|
|
94
|
+
## Not advice
|
|
95
|
+
|
|
96
|
+
SUCA Portfolio Tracker reports what you hold and what it has earned. It does
|
|
97
|
+
not recommend what to buy or sell.
|
|
98
|
+
|
|
99
|
+
## Licence
|
|
100
|
+
|
|
101
|
+
© SUCA Analytics. All rights reserved. Free to use. Not open source.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
suca_pt/__init__.py,sha256=deyGoRCrh9AsqNJYkJrxJctD5hu72cU0sfCQ5L8K6bg,304
|
|
2
|
+
suca_pt/__main__.py,sha256=9NB8wOvLp7uoHiCtIox36xyZziJK4H2SxyFIlDby_YY,55
|
|
3
|
+
suca_pt/cli.py,sha256=ljGUCQJPUP77NSIPL53N67iuWtWfVYxJX4AtxFTY88A,2618
|
|
4
|
+
suca_pt/engine/__init__.py,sha256=YL1bssGjt1X4HmO5b72GjKkWsBCFgNBNNFfiFVVCcTc,81
|
|
5
|
+
suca_pt/ingest/__init__.py,sha256=w5B2yUsTf4cLIsHXKNf_ccI1Rh26KUKo9g_9K_j0N18,78
|
|
6
|
+
suca_pt/paths.py,sha256=pi3zyK13YDkO7epmg3WTnE-51zFBUNYc9kR51AQt6xs,2422
|
|
7
|
+
suca_pt/selfcheck.py,sha256=tw4WZj9qu0vPBtQbmT_RPf72JRmvuv-JGnyOqbrDfbQ,5938
|
|
8
|
+
suca_pt/server/__init__.py,sha256=_3sQhua5cd6mlTW5kjD2FmCLZmCD16MLFMS3sgK95Hc,77
|
|
9
|
+
suca_pt/server/app.py,sha256=LDlE04ilE45gUJigEHLgzEmHPEbmWysDD_p0j_UIc20,2808
|
|
10
|
+
suca_pt/server/guard.py,sha256=bn50KyWvYQQbks90jsivgumwUpzrRIlSIK29v1R--C8,2636
|
|
11
|
+
suca_pt/server/middleware.py,sha256=Q3oIk6c_kVHR6AAv9uDTAUK81IeQxrYKfnOmb9Lc0kE,5435
|
|
12
|
+
suca_pt/server/runner.py,sha256=NFS3hEVgYl1xkGR0LzR2-WXfsuVA62cnB2oFvZS4L48,3270
|
|
13
|
+
suca_pt/updates.py,sha256=7fo-OdJW8zsDQj97TltRxSB_KjVJOPn3qIXwFAhhfkE,3099
|
|
14
|
+
suca_pt/web/static/app.css,sha256=v39xhTNoLd6-XOqci16j6NlILef20ZgtveNGHb6P6pk,1134
|
|
15
|
+
suca_pt/web/static/app.js,sha256=90nA9O8FqjkYWf7EEH-OzlagulAXJg2RvNLtrKdtJwM,1509
|
|
16
|
+
suca_pt/web/static/favicon.svg,sha256=f_XVYdlVTxUY1yyZMEFUxAK5kk7Do4uTAFjunwV8Y9Y,249
|
|
17
|
+
suca_pt/web/static/index.html,sha256=oTwQIeU7ItXfMo8saqnCwh7EAmI6UZvdpZQ_vFFGkFU,856
|
|
18
|
+
suca_pt-0.0.1.dist-info/WHEEL,sha256=cmC5s21ojypbVslldL7IJq3hjZH-tINy4rziKePFsG0,81
|
|
19
|
+
suca_pt-0.0.1.dist-info/entry_points.txt,sha256=GbZirwVl7AhO9vBRUc-QUt4d1xu_Zpt3uMmHmIjOVEE,46
|
|
20
|
+
suca_pt-0.0.1.dist-info/METADATA,sha256=XyOHLKkkCaBWkoPFxjgI_1_tL5VsOMnEUrlulwgt_K8,3162
|
|
21
|
+
suca_pt-0.0.1.dist-info/RECORD,,
|