rithub-billing recorded who paid but told nobody and never linked a payment to a Rithub login. The lifecycle timer now runs a Pro pass: email -> login link, one 'rithub pro is on' mail to the customer, an owner mail on every status change, and pro-users.json as the one list later Pro limits read. Tested on railyard-box with a fake entitlement and mail.tm inboxes: mails delivered, second run sends nothing, revoke mails the owner only. rithub-billing source copied in from the box (it only lived there). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
483 lines
19 KiB
Python
483 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""rithub-lifecycle.py — two lifecycle emails per real new Rithub signup:
|
|
|
|
1. WELCOME, sent once, the first time this job ever sees a login (i.e. it
|
|
signed up after this service was installed).
|
|
2. NUDGE, sent once, ~NUDGE_MIN_HOURS (default 48h) after signup, ONLY if
|
|
the account still has zero repos — the "bring your code over" push.
|
|
|
|
Runs every RITHUB_LIFECYCLE_INTERVAL_MINUTES (default 15) via
|
|
rithub-lifecycle.timer (oneshot service). Reads Rithub's own admin REST API
|
|
over the box-local loopback (http://127.0.0.1:3350, same pattern already
|
|
used by rithub-mcp/the bulk-migrate scripts to skip Cloudflare's edge) —
|
|
read-only: GET /api/v1/admin/users (list) and GET /api/v1/users/<login>/repos
|
|
(count, via the X-Total-Count header, never fetching bodies). No writes to
|
|
Gitea's own DB or API; this job only ever sends mail and writes to its own
|
|
local state file.
|
|
|
|
Classification (never mails a non-human account):
|
|
- the Rithub owner account (OWNER_LOGIN, default caelum0x) is always
|
|
excluded.
|
|
- any login matching EXCLUDE_LOGIN_REGEX (agent-*, rithub-lev-* and other
|
|
known test-artifact prefixes, qa-/test-/demo-) is excluded.
|
|
- any account whose email domain matches EXCLUDE_EMAIL_DOMAIN_REGEX
|
|
(mail.tm and mail.tm-style disposable domains incl. euploading.com
|
|
which mail.tm itself currently hands out, guerrillamail, 10minutemail,
|
|
example.com, agents.rithub.dev — the synthetic domain agent-signup
|
|
accounts get) is excluded.
|
|
- an account with no email on file is excluded (nothing to mail).
|
|
|
|
Idempotent by design: every send is recorded in STATE_DIR/sent.json keyed
|
|
by login (`welcomed_at`, `nudged_at`) before the next run ever looks at that
|
|
login again — a login already carrying either timestamp is never mailed
|
|
that same kind of message twice, regardless of how many times the job runs
|
|
or how it's restarted. First-run seeding (see `--seed-existing`) marks every
|
|
account that already existed before this service was installed as already
|
|
both-welcomed (not nudged) so the automation only "welcomes" genuinely NEW
|
|
signups from here on — see module README section in
|
|
plans/railyard.md (RIT-RET) for why.
|
|
|
|
Each mail's body carries a one-line opt-out ("reply STOP ..."). There is no
|
|
inbound-mail parser wired up (this job only sends), so a real STOP reply is
|
|
handled by a human reading MAIL_REPLY_TO and running:
|
|
rithub-lifecycle.py --opt-out <login>
|
|
which is a single idempotent local command (no dashboard, no form) that
|
|
permanently stops both message kinds for that login.
|
|
|
|
CLI (all optional):
|
|
--env-file PATH config file (default /etc/products/rithub-lifecycle.env)
|
|
--state-dir PATH override STATE_DIR (use a throwaway dir for test runs)
|
|
--now EPOCH override "current time" (float seconds), for determinism
|
|
--test-to EMAIL send to this address instead of the real account email
|
|
--test-login LOGIN force-include exactly this login (bypasses the
|
|
owner/test/QA exclusion checks ONLY; already-sent /
|
|
opted-out / age-window checks still apply)
|
|
--dry-run list who would get mail and send nothing
|
|
--json print the full candidate list as JSON (dry-run only)
|
|
--seed-existing one-time setup: mark every account that exists RIGHT
|
|
NOW as already welcomed (not nudged), so the next
|
|
normal run only welcomes logins that did not exist
|
|
yet. Safe to re-run (idempotent: never un-marks or
|
|
re-marks an already-recorded login).
|
|
--opt-out LOGIN permanently stop mailing this login (both kinds),
|
|
for a real "reply STOP" handled by a human.
|
|
|
|
Disable: systemctl disable --now rithub-lifecycle.timer
|
|
Config: /etc/products/rithub-lifecycle.env (see .env.example in this
|
|
directory) for RITHUB_ADMIN_TOKEN (same token already minted for rithub-mcp,
|
|
read from /etc/products/rithub-mcp.env by default rather than minting a new
|
|
one) and the mail knobs. Sending reuses the same shared OCI Email Delivery
|
|
relay credentials already live for Rithub's own password-reset mail
|
|
(RAGO_SMTP_HOST/PORT/USERNAME/PASSWORD in /etc/products/rago.env, see
|
|
plans/railyard.md RIT-ACT 2026-11-30) from the same OCI-approved sender,
|
|
team@go.rithub.dev.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import logging
|
|
import os
|
|
import sys
|
|
import re
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from typing import Any
|
|
|
|
DEFAULT_ENV_FILE = "/etc/products/rithub-lifecycle.env"
|
|
DEFAULT_STATE_DIR = "/var/lib/rithub-lifecycle"
|
|
DEFAULT_RAGO_ENV_FILE = "/etc/products/rago.env"
|
|
DEFAULT_MCP_ENV_FILE = "/etc/products/rithub-mcp.env"
|
|
DEFAULT_API_BASE = "http://127.0.0.1:3350"
|
|
DEFAULT_PUBLIC_BASE_URL = "https://rithub.dev"
|
|
DEFAULT_OWNER_LOGIN = "caelum0x"
|
|
# Ritgram's own one-click "Continue with Rithub" OAuth entry point (RIT-RET,
|
|
# 2026-11-30) -- a stable Ritgram-owned redirect, not a Rithub template, so
|
|
# it's safe to link from here without touching any redesign-owned page.
|
|
RITGRAM_ONE_CLICK_URL = "https://ritgram.rithub.dev/go/rithub"
|
|
|
|
NUDGE_MIN_HOURS = 48
|
|
|
|
DEFAULT_EXCLUDE_LOGIN_REGEX = r"^(agent-|rithub-lev-|rit-[a-z]+-qa-|qa-|test-|demo-)"
|
|
DEFAULT_EXCLUDE_EMAIL_DOMAIN_REGEX = (
|
|
r"@(euploading\.com|mail\.tm|.*\.mail\.tm|guerrillamail\.[a-z]+|"
|
|
r"10minutemail\.[a-z]+|example\.(com|org|net)|agents\.rithub\.dev)$"
|
|
)
|
|
|
|
log = logging.getLogger("rithub-lifecycle")
|
|
|
|
|
|
# --------------------------- env file loading -------------------------------
|
|
|
|
|
|
def load_env_file(path: str) -> dict[str, str]:
|
|
cfg: dict[str, str] = {}
|
|
try:
|
|
with open(path, "r") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
key, _, val = line.partition("=")
|
|
cfg[key.strip()] = val.strip().strip('"').strip("'")
|
|
except FileNotFoundError:
|
|
pass
|
|
return cfg
|
|
|
|
|
|
# --------------------------- Rithub admin API (read-only) -------------------
|
|
|
|
|
|
def _api_get(base: str, path: str, token: str) -> tuple[Any, dict[str, str]]:
|
|
req = urllib.request.Request(
|
|
base.rstrip("/") + path,
|
|
headers={"Authorization": f"token {token}", "Accept": "application/json"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
|
headers = {k.lower(): v for k, v in resp.headers.items()}
|
|
body = resp.read()
|
|
data = json.loads(body) if body else None
|
|
return data, headers
|
|
|
|
|
|
def fetch_all_users(base: str, token: str) -> list[dict[str, Any]]:
|
|
users: list[dict[str, Any]] = []
|
|
page = 1
|
|
while True:
|
|
data, _ = _api_get(base, f"/api/v1/admin/users?limit=50&page={page}", token)
|
|
if not data:
|
|
break
|
|
users.extend(data)
|
|
if len(data) < 50:
|
|
break
|
|
page += 1
|
|
return users
|
|
|
|
|
|
def fetch_repo_count(base: str, token: str, login: str) -> int:
|
|
try:
|
|
_, headers = _api_get(base, f"/api/v1/users/{login}/repos?limit=1", token)
|
|
except urllib.error.HTTPError as exc:
|
|
log.warning("repo count fetch failed for %s: HTTP %s", login, exc.code)
|
|
return -1
|
|
total = headers.get("x-total-count")
|
|
if total is not None:
|
|
try:
|
|
return int(total)
|
|
except ValueError:
|
|
pass
|
|
return 0
|
|
|
|
|
|
# --------------------------- classification ----------------------------------
|
|
|
|
|
|
def classify(
|
|
user: dict[str, Any],
|
|
owner_login: str,
|
|
exclude_login_re: re.Pattern[str],
|
|
exclude_email_domain_re: re.Pattern[str],
|
|
force_login: str | None,
|
|
) -> tuple[bool, str]:
|
|
login = user.get("login", "")
|
|
email = user.get("email", "") or ""
|
|
if login == force_login:
|
|
return (bool(email), "no_email" if not email else "ok")
|
|
if login == owner_login:
|
|
return False, "owner"
|
|
if exclude_login_re.search(login):
|
|
return False, "test_or_agent_login"
|
|
if not email or exclude_email_domain_re.search(email):
|
|
return False, "test_or_disposable_email"
|
|
return True, "ok"
|
|
|
|
|
|
# --------------------------- mail content -------------------------------------
|
|
|
|
|
|
def build_welcome_mail(login: str, public_base_url: str, reply_to: str) -> tuple[str, str]:
|
|
subject = "welcome to rithub"
|
|
lines = [
|
|
"hey,",
|
|
"",
|
|
"you're in. rithub is a hosted git host - repos, issues, PRs, actions.",
|
|
"",
|
|
f"bring your existing code over any time: {public_base_url}/repo/migrate",
|
|
"paste a repo url (private repos too, with a token) and it lands as a full",
|
|
"working repo, history and all, usually in a few seconds.",
|
|
"",
|
|
f"there's also ritgram, a feed for your repos - one click signs you in",
|
|
f"with this same account: {RITGRAM_ONE_CLICK_URL}",
|
|
"",
|
|
f"anything broken or confusing, just reply to this email ({reply_to}) -",
|
|
"a person reads it.",
|
|
"",
|
|
"reply STOP any time and you won't get another one of these.",
|
|
]
|
|
return subject, "\n".join(lines) + "\n"
|
|
|
|
|
|
def build_nudge_mail(login: str, public_base_url: str, reply_to: str) -> tuple[str, str]:
|
|
subject = "bring your code over to rithub?"
|
|
lines = [
|
|
"hey,",
|
|
"",
|
|
"you signed up for rithub a couple days ago but don't have a repo on it yet.",
|
|
"a few real things got fixed since: sign-in and password reset both work now,",
|
|
"the box was timing out on imports under load (fixed), and the GitHub import",
|
|
"button on the homepage was pointing at a dead link (fixed too).",
|
|
"",
|
|
f"importing is one paste: {public_base_url}/repo/migrate",
|
|
"drop in your GitHub (or any git) repo url - private repos work too, with a",
|
|
"token - and it's a real working repo on rithub in a few seconds, full history.",
|
|
"",
|
|
f"or skip straight to ritgram, a feed for your repos: {RITGRAM_ONE_CLICK_URL}",
|
|
"",
|
|
f"stuck on anything, reply to this email ({reply_to}) - a person reads it.",
|
|
"",
|
|
"reply STOP any time and you won't get another one of these.",
|
|
]
|
|
return subject, "\n".join(lines) + "\n"
|
|
|
|
|
|
# --------------------------- sending ------------------------------------------
|
|
|
|
|
|
def send_mail(
|
|
rago_cfg: dict[str, str],
|
|
from_addr: str,
|
|
to_addr: str,
|
|
subject: str,
|
|
body: str,
|
|
dry_run: bool,
|
|
) -> bool:
|
|
import smtplib
|
|
import ssl
|
|
from email.message import EmailMessage
|
|
|
|
host = rago_cfg.get("RAGO_SMTP_HOST", "")
|
|
port = rago_cfg.get("RAGO_SMTP_PORT", "")
|
|
user = rago_cfg.get("RAGO_SMTP_USERNAME", "")
|
|
password = rago_cfg.get("RAGO_SMTP_PASSWORD", "")
|
|
if dry_run or not host or not port or not user or not password or not to_addr:
|
|
log.info("%s mail to %s: %s", "DRY" if dry_run else "NOT CONFIGURED", to_addr, subject)
|
|
log.info("%s", body)
|
|
return dry_run
|
|
|
|
msg = EmailMessage()
|
|
msg["From"] = from_addr
|
|
msg["To"] = to_addr
|
|
msg["Subject"] = subject
|
|
msg["Reply-To"] = from_addr if "Reply-To" not in msg else msg["Reply-To"]
|
|
msg.set_content(body)
|
|
|
|
try:
|
|
with smtplib.SMTP(host, int(port), timeout=20) as smtp:
|
|
smtp.starttls(context=ssl.create_default_context())
|
|
smtp.login(user, password)
|
|
smtp.send_message(msg)
|
|
except (OSError, smtplib.SMTPException) as exc:
|
|
log.error("mail send failed (smtp): %s", exc)
|
|
return False
|
|
log.info("mail sent to %s: %s", to_addr, subject)
|
|
return True
|
|
|
|
|
|
# --------------------------- state --------------------------------------------
|
|
|
|
|
|
def load_json(path: str, default: Any) -> Any:
|
|
try:
|
|
with open(path) as f:
|
|
return json.load(f)
|
|
except (FileNotFoundError, ValueError):
|
|
return default
|
|
|
|
|
|
def save_json(path: str, value: Any) -> None:
|
|
tmp = path + ".tmp"
|
|
with open(tmp, "w") as f:
|
|
json.dump(value, f, indent=2, sort_keys=True)
|
|
os.replace(tmp, path)
|
|
|
|
|
|
# --------------------------- main ---------------------------------------------
|
|
|
|
|
|
def main() -> int:
|
|
logging.basicConfig(level=logging.INFO, format="[rithub-lifecycle] %(message)s")
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--env-file", default=DEFAULT_ENV_FILE)
|
|
ap.add_argument("--state-dir", default=None)
|
|
ap.add_argument("--now", type=float, default=None)
|
|
ap.add_argument("--test-to", default=None)
|
|
ap.add_argument("--test-login", default=None)
|
|
ap.add_argument("--dry-run", action="store_true")
|
|
ap.add_argument("--json", action="store_true")
|
|
ap.add_argument("--seed-existing", action="store_true")
|
|
ap.add_argument("--opt-out", default=None)
|
|
args = ap.parse_args()
|
|
|
|
cfg = load_env_file(args.env_file)
|
|
rago_cfg = load_env_file(cfg.get("RAGO_ENV_FILE", DEFAULT_RAGO_ENV_FILE))
|
|
mcp_cfg = load_env_file(cfg.get("MCP_ENV_FILE", DEFAULT_MCP_ENV_FILE))
|
|
admin_token = cfg.get("RITHUB_ADMIN_TOKEN") or mcp_cfg.get("RITHUB_ADMIN_TOKEN", "")
|
|
api_base = cfg.get("RITHUB_API_BASE", DEFAULT_API_BASE)
|
|
public_base_url = cfg.get("RITHUB_PUBLIC_BASE_URL", DEFAULT_PUBLIC_BASE_URL)
|
|
owner_login = cfg.get("OWNER_LOGIN", DEFAULT_OWNER_LOGIN)
|
|
from_addr = cfg.get("MAIL_FROM", "Rithub <team@go.rithub.dev>")
|
|
reply_to = cfg.get("MAIL_REPLY_TO", "rithub@hi.ereboslab.com")
|
|
nudge_min_hours = float(cfg.get("NUDGE_MIN_HOURS", NUDGE_MIN_HOURS))
|
|
exclude_login_re = re.compile(cfg.get("EXCLUDE_LOGIN_REGEX", DEFAULT_EXCLUDE_LOGIN_REGEX))
|
|
exclude_email_domain_re = re.compile(
|
|
cfg.get("EXCLUDE_EMAIL_DOMAIN_REGEX", DEFAULT_EXCLUDE_EMAIL_DOMAIN_REGEX), re.IGNORECASE
|
|
)
|
|
now_ts = args.now if args.now is not None else time.time()
|
|
|
|
state_dir = args.state_dir or cfg.get("STATE_DIR", DEFAULT_STATE_DIR)
|
|
persist = not args.dry_run
|
|
if persist:
|
|
os.makedirs(state_dir, 0o755, exist_ok=True)
|
|
state_file = os.path.join(state_dir, "sent.json")
|
|
state = load_json(state_file, {})
|
|
|
|
if args.opt_out:
|
|
entry = state.get(args.opt_out, {})
|
|
entry["opted_out"] = True
|
|
entry["opted_out_at"] = int(now_ts)
|
|
state[args.opt_out] = entry
|
|
save_json(state_file, state)
|
|
log.info("login %s permanently opted out", args.opt_out)
|
|
return 0
|
|
|
|
if not admin_token:
|
|
log.error(
|
|
"no RITHUB_ADMIN_TOKEN readable from %s or %s; refusing to run",
|
|
args.env_file, cfg.get("MCP_ENV_FILE", DEFAULT_MCP_ENV_FILE),
|
|
)
|
|
return 1
|
|
|
|
try:
|
|
users = fetch_all_users(api_base, admin_token)
|
|
except (urllib.error.URLError, urllib.error.HTTPError) as exc:
|
|
log.error("admin API read failed: %s", exc)
|
|
return 1
|
|
|
|
if args.seed_existing:
|
|
seeded = 0
|
|
for user in users:
|
|
login = user.get("login", "")
|
|
if login in state:
|
|
continue
|
|
state[login] = {
|
|
"welcomed_at": int(now_ts),
|
|
"seeded": True,
|
|
"note": "pre-existing account at service install time, never auto-welcomed",
|
|
}
|
|
seeded += 1
|
|
if not args.dry_run:
|
|
save_json(state_file, state)
|
|
log.info("seeded %d pre-existing login(s) as already-welcomed", seeded)
|
|
return 0
|
|
|
|
to_welcome: list[dict[str, Any]] = []
|
|
to_nudge: list[dict[str, Any]] = []
|
|
skipped: list[tuple[str, str]] = []
|
|
|
|
for user in users:
|
|
login = user.get("login", "")
|
|
ok, reason = classify(user, owner_login, exclude_login_re, exclude_email_domain_re, args.test_login)
|
|
if not ok:
|
|
skipped.append((login, reason))
|
|
continue
|
|
entry = state.get(login, {})
|
|
if entry.get("opted_out"):
|
|
skipped.append((login, "opted_out"))
|
|
continue
|
|
email = args.test_to or user.get("email", "")
|
|
created = user.get("created")
|
|
created_ts = None
|
|
if created:
|
|
try:
|
|
import datetime
|
|
|
|
created_ts = datetime.datetime.strptime(
|
|
created.split(".")[0].replace("Z", ""), "%Y-%m-%dT%H:%M:%S"
|
|
).replace(tzinfo=datetime.timezone.utc).timestamp()
|
|
except ValueError:
|
|
created_ts = None
|
|
age_hours = (now_ts - created_ts) / 3600.0 if created_ts else None
|
|
|
|
if not entry.get("welcomed_at"):
|
|
to_welcome.append({"login": login, "email": email})
|
|
|
|
if not entry.get("nudged_at") and age_hours is not None and age_hours >= nudge_min_hours:
|
|
repo_count = fetch_repo_count(api_base, admin_token, login)
|
|
if repo_count == 0:
|
|
to_nudge.append({"login": login, "email": email, "age_hours": age_hours})
|
|
elif repo_count < 0:
|
|
skipped.append((login, "repo_count_unknown"))
|
|
else:
|
|
skipped.append((login, "already_has_repos"))
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
from rithub_pro import DEFAULT_ENTITLEMENTS_FILE, run_pro_pass
|
|
|
|
pro_counts = run_pro_pass(
|
|
users=users,
|
|
entitlements_file=cfg.get("PRO_ENTITLEMENTS_FILE", DEFAULT_ENTITLEMENTS_FILE),
|
|
state_dir=state_dir,
|
|
send=lambda to, subj, body: send_mail(rago_cfg, from_addr, to, subj, body, dry_run=False),
|
|
owner_email=cfg.get("OWNER_NOTIFY_EMAIL", reply_to),
|
|
public_base_url=public_base_url,
|
|
reply_to=reply_to,
|
|
now_ts=now_ts,
|
|
dry_run=args.dry_run,
|
|
)
|
|
log.info("pro: %s", pro_counts)
|
|
|
|
if args.dry_run:
|
|
if args.json:
|
|
print(json.dumps({"to_welcome": to_welcome, "to_nudge": to_nudge, "skipped": skipped}, indent=2))
|
|
else:
|
|
log.info("%d user(s) total, %d would get welcome, %d would get nudge",
|
|
len(users), len(to_welcome), len(to_nudge))
|
|
for c in to_welcome:
|
|
log.info(" WOULD WELCOME login=%s", c["login"])
|
|
for c in to_nudge:
|
|
log.info(" WOULD NUDGE login=%s age_hours=%.1f", c["login"], c["age_hours"])
|
|
for login, reason in skipped:
|
|
log.info(" skip login=%s reason=%s", login, reason)
|
|
return 0
|
|
|
|
welcomed_count = 0
|
|
for c in to_welcome:
|
|
subject, body = build_welcome_mail(c["login"], public_base_url, reply_to)
|
|
ok = send_mail(rago_cfg, from_addr, c["email"], subject, body, dry_run=False)
|
|
entry = state.get(c["login"], {})
|
|
if ok:
|
|
entry["welcomed_at"] = int(now_ts)
|
|
welcomed_count += 1
|
|
state[c["login"]] = entry
|
|
save_json(state_file, state)
|
|
|
|
nudged_count = 0
|
|
for c in to_nudge:
|
|
subject, body = build_nudge_mail(c["login"], public_base_url, reply_to)
|
|
ok = send_mail(rago_cfg, from_addr, c["email"], subject, body, dry_run=False)
|
|
entry = state.get(c["login"], {})
|
|
if ok:
|
|
entry["nudged_at"] = int(now_ts)
|
|
nudged_count += 1
|
|
state[c["login"]] = entry
|
|
save_json(state_file, state)
|
|
|
|
log.info(
|
|
"done: %d user(s), %d welcomed, %d nudged, %d skipped",
|
|
len(users), welcomed_count, nudged_count, len(skipped),
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|