tenkyu 0.2.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.
tenkyu/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Tenkyu: stop free-tier and credit farming in AI apps."""
2
+ from .decision_log import DecisionLog
3
+ from .guard import ALLOW, BLOCK, REVIEW, Decision, Guard, Signup, ip_key
4
+ from .http import client_ip, signup_from_request
5
+ from .signals import Signal, load_domains, normalize_email
6
+ from .store import MemoryStore
7
+
8
+ __all__ = ["DecisionLog", "Guard", "Signup", "Decision", "Signal", "MemoryStore", "SQLiteStore", "normalize_email", "ip_key", "load_domains", "signup_from_request", "client_ip", "ALLOW", "REVIEW", "BLOCK"]
9
+ __version__ = "0.2.0"
10
+
11
+
12
+ def __getattr__(name):
13
+ # SQLiteStore is imported on first use, so `import tenkyu` works on Pythons built without sqlite3
14
+ # (Pyodide, some slim containers) as long as the SQLite store is not used.
15
+ if name == "SQLiteStore":
16
+ from .sqlite_store import SQLiteStore
17
+ return SQLiteStore
18
+ raise AttributeError(f"module 'tenkyu' has no attribute {name!r}")
tenkyu/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
tenkyu/audit.py ADDED
@@ -0,0 +1,135 @@
1
+ """Audit an app's own signup export offline: replay it through Tenkyu in time order and count the farming.
2
+
3
+ Nothing leaves the machine. The summary printed to the screen holds counts and reasons only; the optional
4
+ --out file lists the flagged rows from your own export so you can act on them."""
5
+ from __future__ import annotations
6
+
7
+ import csv
8
+ import math
9
+ from collections import Counter
10
+ from dataclasses import dataclass
11
+ from datetime import datetime, timezone
12
+ from typing import Dict, List, Optional
13
+
14
+ from .guard import ALLOW, BLOCK, REVIEW, Decision, Guard, Signup
15
+
16
+ MAX_ROWS = 2_000_000
17
+ SAMPLE_CSV = __import__("pathlib").Path(__file__).resolve().parent / "data" / "sample_signups.csv"
18
+ NEUTRAL_UA = "Mozilla/5.0 (tenkyu audit: no user-agent column)"
19
+ ALIASES = {
20
+ "email": ("email", "email_address", "email address", "e-mail", "user_email", "primary_email_address", "mail"),
21
+ "ip": ("ip", "ip_address", "ip address", "signup_ip", "remote_addr", "client_ip", "last_sign_in_ip"),
22
+ "ts": ("created_at", "createdat", "created (utc)", "created_at (utc)", "inserted_at", "signup_date", "timestamp",
23
+ "signup_time", "signed_up_at", "created", "date", "ts", "time"),
24
+ "device": ("device_id", "visitor_id", "fingerprint", "device", "dev"),
25
+ "ua": ("user_agent", "useragent", "user agent", "ua"),
26
+ }
27
+
28
+
29
+ def parse_ts(value) -> Optional[float]:
30
+ """Epoch seconds or milliseconds, or ISO 8601 (with Z or an offset; naive times are UTC). None if unreadable."""
31
+ if value is None:
32
+ return None
33
+ s = str(value).strip()
34
+ if not s:
35
+ return None
36
+ try:
37
+ t = float(s)
38
+ if not math.isfinite(t):
39
+ return None
40
+ return t / 1000.0 if t > 1e11 else t
41
+ except ValueError:
42
+ pass
43
+ try:
44
+ dt = datetime.fromisoformat(s.replace("Z", "+00:00").replace(" UTC", "+00:00"))
45
+ except ValueError:
46
+ return None
47
+ if dt.tzinfo is None:
48
+ dt = dt.replace(tzinfo=timezone.utc)
49
+ return dt.timestamp()
50
+
51
+
52
+ def _columns(header: List[str], links: Dict[str, str]) -> Dict[str, Optional[str]]:
53
+ lower = {h.strip().lower(): h for h in header}
54
+ found = {field: next((lower[a] for a in names if a in lower), None) for field, names in ALIASES.items()}
55
+ for name, col in links.items():
56
+ if col not in header:
57
+ raise ValueError(f"--link {name}={col}: no column named {col!r}")
58
+ if not found["email"] or not found["ts"]:
59
+ raise ValueError(f"need an email column and a time column; found columns: {', '.join(header)}")
60
+ return found
61
+
62
+
63
+ @dataclass
64
+ class AuditResult:
65
+ rows: int
66
+ bad_rows: int
67
+ decisions: List[tuple] # (original row index, Decision), in replay order
68
+ has_ua: bool
69
+ has_ip: bool
70
+ has_device: bool
71
+ unused_columns: tuple = ()
72
+
73
+ def summary(self, grant_usd: float = 0.0) -> dict:
74
+ acts = Counter(d.action for _, d in self.decisions)
75
+ flagged = acts[REVIEW] + acts[BLOCK]
76
+ import re
77
+ reasons = Counter(re.sub(r"\d+", "N", r) for _, d in self.decisions if d.action != ALLOW for r in d.reasons[:1])
78
+ n = len(self.decisions)
79
+ return {"signups": n, "unreadable_rows": self.bad_rows, "allow": acts[ALLOW], "review": acts[REVIEW], "block": acts[BLOCK],
80
+ "flagged_pct": round(100 * flagged / n, 1) if n else 0.0,
81
+ "usd_at_stake": round(sum(1.0 - d.credit_fraction for _, d in self.decisions) * grant_usd, 2),
82
+ "top_reasons": reasons.most_common(6),
83
+ "unused_columns": list(self.unused_columns),
84
+ "missing": [c for c, ok in (("user agent", self.has_ua), ("ip", self.has_ip), ("device id", self.has_device)) if not ok]}
85
+
86
+
87
+ def audit_csv(path, links: Optional[Dict[str, str]] = None, guard: Optional[Guard] = None) -> AuditResult:
88
+ """Replay a signup CSV through Tenkyu in time order. links maps a link name to a column, e.g. {"card": "card_fp"}."""
89
+ links = links or {}
90
+ with open(path, newline="", encoding="utf-8-sig", errors="replace") as fh:
91
+ reader = csv.DictReader(fh)
92
+ if not reader.fieldnames:
93
+ raise ValueError("the file has no header row")
94
+ cols = _columns(reader.fieldnames, links)
95
+ rows, bad = [], 0
96
+ for i, row in enumerate(reader):
97
+ if len(rows) >= MAX_ROWS:
98
+ raise ValueError(f"more than {MAX_ROWS:,} rows; split the file by date and audit each part")
99
+ ts = parse_ts(row.get(cols["ts"]))
100
+ if ts is None:
101
+ bad += 1
102
+ continue
103
+ rows.append((ts, i, row))
104
+ rows.sort(key=lambda x: (x[0], x[1]))
105
+ first = rows[0][0] if rows else 0.0
106
+ g = guard or Guard(clock=lambda: first)
107
+ out = []
108
+ for ts, i, row in rows:
109
+ lk = {name: row[col].strip() for name, col in links.items() if (row.get(col) or "").strip()}
110
+ su = Signup(email=row.get(cols["email"]), ip=row.get(cols["ip"]) if cols["ip"] else None,
111
+ device_id=row.get(cols["device"]) if cols["device"] else None,
112
+ user_agent=row.get(cols["ua"]) if cols["ua"] else NEUTRAL_UA, ts=ts, links=lk or None)
113
+ try:
114
+ d: Decision = g.check(su)
115
+ except ValueError:
116
+ bad += 1
117
+ continue
118
+ out.append((i, d))
119
+ used = {c for c in cols.values() if c} | set(links.values())
120
+ unused = tuple(h for h in reader.fieldnames if h not in used)
121
+ return AuditResult(len(rows), bad, out, cols["ua"] is not None, cols["ip"] is not None, cols["device"] is not None, unused)
122
+
123
+
124
+ def write_flagged(path_in, result: AuditResult, path_out) -> int:
125
+ """Copy the flagged rows of the original CSV to path_out with tenkyu_action, tenkyu_score and tenkyu_reason added."""
126
+ flagged = {i: d for i, d in result.decisions if d.action != ALLOW}
127
+ with open(path_in, newline="", encoding="utf-8-sig", errors="replace") as fh, open(path_out, "w", newline="", encoding="utf-8") as fo:
128
+ reader = csv.DictReader(fh)
129
+ w = csv.DictWriter(fo, fieldnames=list(reader.fieldnames) + ["tenkyu_action", "tenkyu_score", "tenkyu_reason"])
130
+ w.writeheader()
131
+ for i, row in enumerate(reader):
132
+ d = flagged.get(i)
133
+ if d:
134
+ w.writerow({**row, "tenkyu_action": d.action, "tenkyu_score": f"{d.score:.2f}", "tenkyu_reason": d.reasons[0] if d.reasons else ""})
135
+ return len(flagged)
tenkyu/cli.py ADDED
@@ -0,0 +1,202 @@
1
+ """Command line: `python -m tenkyu demo | score | version`."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from . import __version__
10
+ from .guard import ALLOW, BLOCK, REVIEW, Guard, Signup
11
+ from .audit import SAMPLE_CSV, audit_csv, write_flagged
12
+ from .decision_log import read_log, summarize
13
+
14
+ EXIT = {ALLOW: 0, REVIEW: 10, BLOCK: 20}
15
+ EXIT_DB_ERROR = 3 # the --db file could not be opened or read
16
+ BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0 Safari/537.36"
17
+ DEMO_T0 = 1_700_000_000.0
18
+
19
+
20
+ def _demo_scenes():
21
+ """(label, Signup) pairs: an honest user, an alias farmer, and a bot burst."""
22
+ scenes = [("honest user", Signup("ana@acme.io", "203.0.113.10", "dev-ana", BROWSER, DEMO_T0))]
23
+ for i, e in enumerate(["john@gmail.com", "j.o.h.n+free1@gmail.com", "john+free2@googlemail.com"]):
24
+ scenes.append(("alias farmer", Signup(e, "198.51.100.20", "dev-john", BROWSER, DEMO_T0 + 30 + i * 90)))
25
+ for i in range(4):
26
+ scenes.append(("bot burst", Signup(f"user{i}x@mailinator.com" if i % 2 else f"bot{i}@acme.io", "192.0.2.77",
27
+ f"dev-bot{i}", "python-requests/2.31", DEMO_T0 + 600 + i * 2)))
28
+ return scenes
29
+
30
+
31
+ def run_demo(out=None) -> int:
32
+ out = out or sys.stdout
33
+ guard = Guard(clock=lambda: DEMO_T0)
34
+ rows = []
35
+ for label, signup in _demo_scenes():
36
+ d = guard.check(signup)
37
+ reason = d.reasons[0] if d.reasons else "-"
38
+ rows.append((label, signup.email, d.action.upper(), f"{d.score:.2f}", f"{int(d.credit_fraction * 100)}%", reason))
39
+ head = ("scene", "email", "action", "score", "credits", "main reason")
40
+ widths = [max(len(str(r[i])) for r in rows + [head]) for i in range(5)]
41
+ fmt = lambda r: " ".join(str(r[i]).ljust(widths[i]) for i in range(5)) + " " + str(r[5])
42
+ print(fmt(head), file=out)
43
+ print(" ".join("-" * w for w in widths) + " " + "-" * 11, file=out)
44
+ for r in rows:
45
+ print(fmt(r), file=out)
46
+ return 0
47
+
48
+
49
+ def run_score(args, out=None) -> int:
50
+ out = out or sys.stdout
51
+ import sqlite3
52
+
53
+ from .sqlite_store import SQLiteStore
54
+ store = None
55
+ try:
56
+ store = SQLiteStore(args.db) if args.db else None
57
+ guard = Guard(store=store) if store else Guard()
58
+ d = guard.check(Signup(email=args.email, ip=args.ip, device_id=args.device, user_agent=args.ua), record=not args.dry_run)
59
+ except sqlite3.Error as e:
60
+ print(f"tenkyu: cannot use database {args.db}: {e}", file=sys.stderr)
61
+ return EXIT_DB_ERROR
62
+ finally:
63
+ if store:
64
+ store.close()
65
+ if args.json:
66
+ print(json.dumps(d.to_dict(), indent=2), file=out)
67
+ else:
68
+ print(f"{d.action.upper()} score={d.score:.2f} credits={int(d.credit_fraction * 100)}%", file=out)
69
+ for r in d.reasons:
70
+ print(f" - {r}", file=out)
71
+ return EXIT[d.action]
72
+
73
+
74
+ def run_report(args, out=None) -> int:
75
+ out = out or sys.stdout
76
+ try:
77
+ records, bad = read_log(args.log)
78
+ except OSError as e:
79
+ print(f"tenkyu: cannot read {args.log}: {e.strerror or e}", file=sys.stderr)
80
+ return EXIT_DB_ERROR
81
+ s = summarize(records, args.grant)
82
+ if args.json:
83
+ print(json.dumps({**s, "unreadable_lines": bad}, indent=2), file=out)
84
+ return 0
85
+ mode = "shadow mode: nobody was refused; this is what Tenkyu would have done" if s["shadow"] else "enforced decisions"
86
+ print(f"{s['decisions']} signups ({mode})", file=out)
87
+ for a in ("allow", "review", "block"):
88
+ n = s["by_action"][a]
89
+ pct = 100 * n / s["decisions"] if s["decisions"] else 0
90
+ print(f" {a:<7}{n:>6} {pct:5.1f}%", file=out)
91
+ print(f"Same inbox signing up again: {s['repeat_emails']}", file=out)
92
+ grant = f" = ${s['usd_withheld']:,.2f} at ${args.grant:g} per grant" if args.grant else ""
93
+ print(f"Free grants withheld from flagged signups: {s['grants_withheld']:g}{grant}", file=out)
94
+ if s["grants_held_until_verified"]:
95
+ held = f" (${s['usd_held_until_verified']:,.2f})" if args.grant else ""
96
+ print(f"Held from allowed users until they verify (not abuse): {s['grants_held_until_verified']:g} grants{held}", file=out)
97
+ if s["top_reasons"]:
98
+ print("Top reasons:", file=out)
99
+ for reason, n in s["top_reasons"]:
100
+ print(f" {n:>5} {reason}", file=out)
101
+ if bad:
102
+ print(f"Skipped {bad} unreadable line(s).", file=out)
103
+ return 0
104
+
105
+
106
+ def run_audit(args, out=None) -> int:
107
+ out = out or sys.stdout
108
+ links = {}
109
+ for spec in args.link or []:
110
+ name, _, col = spec.partition("=")
111
+ if not col:
112
+ print(f"tenkyu: --link must look like name=column, got {spec!r}", file=sys.stderr)
113
+ return 2
114
+ links[name.strip()] = col.strip()
115
+ if args.sample:
116
+ args.csv = str(SAMPLE_CSV)
117
+ if not args.grant: # the demo should show the money; a real audit only prints $ when you give your own grant
118
+ args.grant = 3.0
119
+ if not args.json: # --json output must stay pure JSON
120
+ print("Using the bundled sample (synthetic signups with known farms, not real users).", file=out)
121
+ elif not args.csv:
122
+ print("tenkyu: give a CSV file, or --sample to try it on bundled synthetic data", file=sys.stderr)
123
+ return 2
124
+ try:
125
+ res = audit_csv(args.csv, links)
126
+ except OSError as e:
127
+ print(f"tenkyu: cannot read {args.csv}: {e.strerror or e}", file=sys.stderr)
128
+ return EXIT_DB_ERROR
129
+ except ValueError as e:
130
+ print(f"tenkyu: {e}", file=sys.stderr)
131
+ return 2
132
+ s = res.summary(args.grant)
133
+ if args.out:
134
+ s["flagged_rows_written"] = write_flagged(args.csv, res, args.out)
135
+ if args.json:
136
+ print(json.dumps(s, indent=2), file=out)
137
+ return 0
138
+ print(f"Audited {s['signups']:,} signups (replayed in time order, nothing left this machine)", file=out)
139
+ for a in ("allow", "review", "block"):
140
+ print(f" {a:<7}{s[a]:>9,}", file=out)
141
+ print(f"Flagged for review or block: {s['flagged_pct']}% (review is a softer check; some honest users land there)", file=out)
142
+ if args.grant:
143
+ print(f"Free credits these decisions would have withheld: ${s['usd_at_stake']:,.2f} at ${args.grant:g} per grant", file=out)
144
+ if s["top_reasons"]:
145
+ print("Main reason per flagged signup:", file=out)
146
+ for reason, n in s["top_reasons"]:
147
+ print(f" {n:>7,} {reason}", file=out)
148
+ if s["unused_columns"] and not args.sample:
149
+ print(f"Columns not used: {', '.join(s['unused_columns'])} (rename one to device_id or user_agent, or use --link)", file=out)
150
+ if s["missing"]:
151
+ print(f"Not in your export, so those signals were off: {', '.join(s['missing'])}", file=out)
152
+ if s["unreadable_rows"]:
153
+ print(f"Skipped {s['unreadable_rows']:,} row(s) with no readable time or bad link values.", file=out)
154
+ if args.out:
155
+ print(f"Wrote {s['flagged_rows_written']:,} flagged rows to {args.out}", file=out)
156
+ return 0
157
+
158
+
159
+ def build_parser() -> argparse.ArgumentParser:
160
+ p = argparse.ArgumentParser(prog="tenkyu", description="Stop free-tier and credit farming in AI apps.",
161
+ epilog="`score` exit codes: 0 allow, 10 review, 20 block, 3 the --db file could not be used.")
162
+ sub = p.add_subparsers(dest="cmd")
163
+ sub.add_parser("demo", help="simulate an honest user, an alias farmer and a bot burst")
164
+ sub.add_parser("version", help="print the version")
165
+ s = sub.add_parser("score", help="score one signup")
166
+ s.add_argument("--email", required=True)
167
+ s.add_argument("--ip")
168
+ s.add_argument("--device")
169
+ s.add_argument("--ua", help="user agent string")
170
+ s.add_argument("--db", help="SQLite file to remember signups between runs")
171
+ s.add_argument("--dry-run", action="store_true", help="score without remembering the signup")
172
+ s.add_argument("--json", action="store_true")
173
+ a = sub.add_parser("audit", help="replay your own signup export (CSV) and count the farming")
174
+ a.add_argument("--sample", action="store_true", help="audit the bundled synthetic sample to see what the output looks like (uses an example $3 grant unless --grant is given)")
175
+ a.add_argument("csv", nargs="?", help="CSV with an email column and a time column (created_at, timestamp, ...); ip, device_id, user_agent optional")
176
+ a.add_argument("--link", action="append", metavar="NAME=COLUMN", help="treat a column as a link, e.g. card=card_fingerprint (repeatable)")
177
+ a.add_argument("--grant", type=float, default=0.0, help="dollar value of one free grant")
178
+ a.add_argument("--out", help="write the flagged rows of your CSV here, with Tenkyu's action and reason")
179
+ a.add_argument("--json", action="store_true")
180
+ r = sub.add_parser("report", help="summarize a decision log (for example from a shadow-mode trial)")
181
+ r.add_argument("log", help="JSONL file written by DecisionLog")
182
+ r.add_argument("--grant", type=float, default=0.0, help="dollar value of one free grant, to show $ at stake")
183
+ r.add_argument("--json", action="store_true")
184
+ return p
185
+
186
+
187
+ def main(argv: Optional[List[str]] = None) -> int:
188
+ parser = build_parser()
189
+ args = parser.parse_args(argv)
190
+ if args.cmd == "demo":
191
+ return run_demo()
192
+ if args.cmd == "score":
193
+ return run_score(args)
194
+ if args.cmd == "audit":
195
+ return run_audit(args)
196
+ if args.cmd == "report":
197
+ return run_report(args)
198
+ if args.cmd == "version":
199
+ print(__version__)
200
+ return 0
201
+ parser.print_help()
202
+ return 0